babylon.max.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var rotation = Vector3.Zero();
  845. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  846. return rotation;
  847. };
  848. /**
  849. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  850. */
  851. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  852. var u = Vector3.Normalize(axis1);
  853. var w = Vector3.Normalize(axis3);
  854. // world axis
  855. var X = Axis.X;
  856. var Y = Axis.Y;
  857. // equation unknowns and vars
  858. var yaw = 0.0;
  859. var pitch = 0.0;
  860. var roll = 0.0;
  861. var x = 0.0;
  862. var y = 0.0;
  863. var z = 0.0;
  864. var t = 0.0;
  865. var sign = -1.0;
  866. var nbRevert = 0;
  867. var cross;
  868. var dot = 0.0;
  869. // step 1 : rotation around w
  870. // Rv3(u) = u1, and u1 belongs to plane xOz
  871. // Rv3(w) = w1 = w invariant
  872. var u1;
  873. var v1;
  874. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  875. z = 1.0;
  876. }
  877. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  878. x = 1.0;
  879. }
  880. else {
  881. t = w.z / w.x;
  882. x = -t * Math.sqrt(1 / (1 + t * t));
  883. z = Math.sqrt(1 / (1 + t * t));
  884. }
  885. u1 = new Vector3(x, y, z);
  886. u1.normalize();
  887. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  888. v1.normalize();
  889. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  890. cross.normalize();
  891. if (Vector3.Dot(w, cross) < 0) {
  892. sign = 1.0;
  893. }
  894. dot = Vector3.Dot(u, u1);
  895. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  896. roll = Math.acos(dot) * sign;
  897. if (Vector3.Dot(u1, X) < 0) {
  898. roll = Math.PI + roll;
  899. u1 = u1.scaleInPlace(-1);
  900. v1 = v1.scaleInPlace(-1);
  901. nbRevert++;
  902. }
  903. // step 2 : rotate around u1
  904. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  905. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  906. var w2;
  907. var v2;
  908. x = 0.0;
  909. y = 0.0;
  910. z = 0.0;
  911. sign = -1;
  912. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  913. x = 1.0;
  914. }
  915. else {
  916. t = u1.z / u1.x;
  917. x = -t * Math.sqrt(1 / (1 + t * t));
  918. z = Math.sqrt(1 / (1 + t * t));
  919. }
  920. w2 = new Vector3(x, y, z);
  921. w2.normalize();
  922. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  923. v2.normalize();
  924. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  925. cross.normalize();
  926. if (Vector3.Dot(u1, cross) < 0) {
  927. sign = 1.0;
  928. }
  929. dot = Vector3.Dot(w, w2);
  930. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  931. pitch = Math.acos(dot) * sign;
  932. if (Vector3.Dot(v2, Y) < 0) {
  933. pitch = Math.PI + pitch;
  934. v2 = v2.scaleInPlace(-1);
  935. w2 = w2.scaleInPlace(-1);
  936. nbRevert++;
  937. }
  938. // step 3 : rotate around v2
  939. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  940. sign = -1;
  941. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(cross, Y) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(u1, X);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  949. if (dot < 0 && nbRevert < 2) {
  950. yaw = Math.PI + yaw;
  951. }
  952. ref.x = pitch;
  953. ref.y = yaw;
  954. ref.z = roll;
  955. };
  956. return Vector3;
  957. })();
  958. BABYLON.Vector3 = Vector3;
  959. //Vector4 class created for EulerAngle class conversion to Quaternion
  960. var Vector4 = (function () {
  961. function Vector4(x, y, z, w) {
  962. this.x = x;
  963. this.y = y;
  964. this.z = z;
  965. this.w = w;
  966. }
  967. Vector4.prototype.toString = function () {
  968. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  969. };
  970. // Operators
  971. Vector4.prototype.asArray = function () {
  972. var result = [];
  973. this.toArray(result, 0);
  974. return result;
  975. };
  976. Vector4.prototype.toArray = function (array, index) {
  977. if (index === undefined) {
  978. index = 0;
  979. }
  980. array[index] = this.x;
  981. array[index + 1] = this.y;
  982. array[index + 2] = this.z;
  983. array[index + 3] = this.w;
  984. return this;
  985. };
  986. Vector4.prototype.addInPlace = function (otherVector) {
  987. this.x += otherVector.x;
  988. this.y += otherVector.y;
  989. this.z += otherVector.z;
  990. this.w += otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.add = function (otherVector) {
  994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  995. };
  996. Vector4.prototype.addToRef = function (otherVector, result) {
  997. result.x = this.x + otherVector.x;
  998. result.y = this.y + otherVector.y;
  999. result.z = this.z + otherVector.z;
  1000. result.w = this.w + otherVector.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.subtractInPlace = function (otherVector) {
  1004. this.x -= otherVector.x;
  1005. this.y -= otherVector.y;
  1006. this.z -= otherVector.z;
  1007. this.w -= otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtract = function (otherVector) {
  1011. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1012. };
  1013. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1014. result.x = this.x - otherVector.x;
  1015. result.y = this.y - otherVector.y;
  1016. result.z = this.z - otherVector.z;
  1017. result.w = this.w - otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1021. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1022. };
  1023. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1024. result.x = this.x - x;
  1025. result.y = this.y - y;
  1026. result.z = this.z - z;
  1027. result.w = this.w - w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.negate = function () {
  1031. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1032. };
  1033. Vector4.prototype.scaleInPlace = function (scale) {
  1034. this.x *= scale;
  1035. this.y *= scale;
  1036. this.z *= scale;
  1037. this.w *= scale;
  1038. return this;
  1039. };
  1040. Vector4.prototype.scale = function (scale) {
  1041. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1042. };
  1043. Vector4.prototype.scaleToRef = function (scale, result) {
  1044. result.x = this.x * scale;
  1045. result.y = this.y * scale;
  1046. result.z = this.z * scale;
  1047. result.w = this.w * scale;
  1048. };
  1049. Vector4.prototype.equals = function (otherVector) {
  1050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1051. };
  1052. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1053. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1054. return otherVector
  1055. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1056. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1057. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1059. };
  1060. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1061. return this.x === x && this.y === y && this.z === z && this.w === w;
  1062. };
  1063. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1064. this.x *= otherVector.x;
  1065. this.y *= otherVector.y;
  1066. this.z *= otherVector.z;
  1067. this.w *= otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiply = function (otherVector) {
  1071. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1072. };
  1073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1074. result.x = this.x * otherVector.x;
  1075. result.y = this.y * otherVector.y;
  1076. result.z = this.z * otherVector.z;
  1077. result.w = this.w * otherVector.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1082. };
  1083. Vector4.prototype.divide = function (otherVector) {
  1084. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1085. };
  1086. Vector4.prototype.divideToRef = function (otherVector, result) {
  1087. result.x = this.x / otherVector.x;
  1088. result.y = this.y / otherVector.y;
  1089. result.z = this.z / otherVector.z;
  1090. result.w = this.w / otherVector.w;
  1091. return this;
  1092. };
  1093. Vector4.prototype.MinimizeInPlace = function (other) {
  1094. if (other.x < this.x)
  1095. this.x = other.x;
  1096. if (other.y < this.y)
  1097. this.y = other.y;
  1098. if (other.z < this.z)
  1099. this.z = other.z;
  1100. if (other.w < this.w)
  1101. this.w = other.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MaximizeInPlace = function (other) {
  1105. if (other.x > this.x)
  1106. this.x = other.x;
  1107. if (other.y > this.y)
  1108. this.y = other.y;
  1109. if (other.z > this.z)
  1110. this.z = other.z;
  1111. if (other.w > this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. // Properties
  1116. Vector4.prototype.length = function () {
  1117. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1118. };
  1119. Vector4.prototype.lengthSquared = function () {
  1120. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1121. };
  1122. // Methods
  1123. Vector4.prototype.normalize = function () {
  1124. var len = this.length();
  1125. if (len === 0)
  1126. return this;
  1127. var num = 1.0 / len;
  1128. this.x *= num;
  1129. this.y *= num;
  1130. this.z *= num;
  1131. this.w *= num;
  1132. return this;
  1133. };
  1134. Vector4.prototype.clone = function () {
  1135. return new Vector4(this.x, this.y, this.z, this.w);
  1136. };
  1137. Vector4.prototype.copyFrom = function (source) {
  1138. this.x = source.x;
  1139. this.y = source.y;
  1140. this.z = source.z;
  1141. this.w = source.w;
  1142. return this;
  1143. };
  1144. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. this.w = w;
  1149. return this;
  1150. };
  1151. // Statics
  1152. Vector4.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Vector4.FromArrayToRef = function (array, offset, result) {
  1159. result.x = array[offset];
  1160. result.y = array[offset + 1];
  1161. result.z = array[offset + 2];
  1162. result.w = array[offset + 3];
  1163. };
  1164. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1165. result.x = array[offset];
  1166. result.y = array[offset + 1];
  1167. result.z = array[offset + 2];
  1168. result.w = array[offset + 3];
  1169. };
  1170. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1171. result.x = x;
  1172. result.y = y;
  1173. result.z = z;
  1174. result.w = w;
  1175. };
  1176. Vector4.Zero = function () {
  1177. return new Vector4(0, 0, 0, 0);
  1178. };
  1179. Vector4.Normalize = function (vector) {
  1180. var result = Vector4.Zero();
  1181. Vector4.NormalizeToRef(vector, result);
  1182. return result;
  1183. };
  1184. Vector4.NormalizeToRef = function (vector, result) {
  1185. result.copyFrom(vector);
  1186. result.normalize();
  1187. };
  1188. Vector4.Minimize = function (left, right) {
  1189. var min = left.clone();
  1190. min.MinimizeInPlace(right);
  1191. return min;
  1192. };
  1193. Vector4.Maximize = function (left, right) {
  1194. var max = left.clone();
  1195. max.MaximizeInPlace(right);
  1196. return max;
  1197. };
  1198. Vector4.Distance = function (value1, value2) {
  1199. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1200. };
  1201. Vector4.DistanceSquared = function (value1, value2) {
  1202. var x = value1.x - value2.x;
  1203. var y = value1.y - value2.y;
  1204. var z = value1.z - value2.z;
  1205. var w = value1.w - value2.w;
  1206. return (x * x) + (y * y) + (z * z) + (w * w);
  1207. };
  1208. Vector4.Center = function (value1, value2) {
  1209. var center = value1.add(value2);
  1210. center.scaleInPlace(0.5);
  1211. return center;
  1212. };
  1213. return Vector4;
  1214. })();
  1215. BABYLON.Vector4 = Vector4;
  1216. var Quaternion = (function () {
  1217. function Quaternion(x, y, z, w) {
  1218. if (x === void 0) { x = 0; }
  1219. if (y === void 0) { y = 0; }
  1220. if (z === void 0) { z = 0; }
  1221. if (w === void 0) { w = 1; }
  1222. this.x = x;
  1223. this.y = y;
  1224. this.z = z;
  1225. this.w = w;
  1226. }
  1227. Quaternion.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1229. };
  1230. Quaternion.prototype.asArray = function () {
  1231. return [this.x, this.y, this.z, this.w];
  1232. };
  1233. Quaternion.prototype.equals = function (otherQuaternion) {
  1234. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1235. };
  1236. Quaternion.prototype.clone = function () {
  1237. return new Quaternion(this.x, this.y, this.z, this.w);
  1238. };
  1239. Quaternion.prototype.copyFrom = function (other) {
  1240. this.x = other.x;
  1241. this.y = other.y;
  1242. this.z = other.z;
  1243. this.w = other.w;
  1244. return this;
  1245. };
  1246. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. };
  1253. Quaternion.prototype.add = function (other) {
  1254. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1255. };
  1256. Quaternion.prototype.subtract = function (other) {
  1257. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1258. };
  1259. Quaternion.prototype.scale = function (value) {
  1260. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1261. };
  1262. Quaternion.prototype.multiply = function (q1) {
  1263. var result = new Quaternion(0, 0, 0, 1.0);
  1264. this.multiplyToRef(q1, result);
  1265. return result;
  1266. };
  1267. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1268. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1269. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1270. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1271. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1272. result.copyFromFloats(x, y, z, w);
  1273. return this;
  1274. };
  1275. Quaternion.prototype.length = function () {
  1276. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1277. };
  1278. Quaternion.prototype.normalize = function () {
  1279. var length = 1.0 / this.length();
  1280. this.x *= length;
  1281. this.y *= length;
  1282. this.z *= length;
  1283. this.w *= length;
  1284. return this;
  1285. };
  1286. Quaternion.prototype.toEulerAngles = function () {
  1287. var result = Vector3.Zero();
  1288. this.toEulerAnglesToRef(result);
  1289. return result;
  1290. };
  1291. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1292. //result is an EulerAngles in the in the z-x-z convention
  1293. var qx = this.x;
  1294. var qy = this.y;
  1295. var qz = this.z;
  1296. var qw = this.w;
  1297. var qxy = qx * qy;
  1298. var qxz = qx * qz;
  1299. var qwy = qw * qy;
  1300. var qwz = qw * qz;
  1301. var qwx = qw * qx;
  1302. var qyz = qy * qz;
  1303. var sqx = qx * qx;
  1304. var sqy = qy * qy;
  1305. var determinant = sqx + sqy;
  1306. if (determinant !== 0.000 && determinant !== 1.000) {
  1307. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1308. result.y = Math.acos(1 - 2 * determinant);
  1309. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1310. }
  1311. else {
  1312. if (determinant === 0.0) {
  1313. result.x = 0.0;
  1314. result.y = 0.0;
  1315. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1316. }
  1317. else {
  1318. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1319. result.y = Math.PI;
  1320. result.z = 0.0;
  1321. }
  1322. }
  1323. return this;
  1324. };
  1325. Quaternion.prototype.toRotationMatrix = function (result) {
  1326. var xx = this.x * this.x;
  1327. var yy = this.y * this.y;
  1328. var zz = this.z * this.z;
  1329. var xy = this.x * this.y;
  1330. var zw = this.z * this.w;
  1331. var zx = this.z * this.x;
  1332. var yw = this.y * this.w;
  1333. var yz = this.y * this.z;
  1334. var xw = this.x * this.w;
  1335. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1336. result.m[1] = 2.0 * (xy + zw);
  1337. result.m[2] = 2.0 * (zx - yw);
  1338. result.m[3] = 0;
  1339. result.m[4] = 2.0 * (xy - zw);
  1340. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1341. result.m[6] = 2.0 * (yz + xw);
  1342. result.m[7] = 0;
  1343. result.m[8] = 2.0 * (zx + yw);
  1344. result.m[9] = 2.0 * (yz - xw);
  1345. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1346. result.m[11] = 0;
  1347. result.m[12] = 0;
  1348. result.m[13] = 0;
  1349. result.m[14] = 0;
  1350. result.m[15] = 1.0;
  1351. return this;
  1352. };
  1353. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1354. Quaternion.FromRotationMatrixToRef(matrix, this);
  1355. return this;
  1356. };
  1357. // Statics
  1358. Quaternion.FromRotationMatrix = function (matrix) {
  1359. var result = new Quaternion();
  1360. Quaternion.FromRotationMatrixToRef(matrix, result);
  1361. return result;
  1362. };
  1363. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1364. var data = matrix.m;
  1365. var m11 = data[0], m12 = data[4], m13 = data[8];
  1366. var m21 = data[1], m22 = data[5], m23 = data[9];
  1367. var m31 = data[2], m32 = data[6], m33 = data[10];
  1368. var trace = m11 + m22 + m33;
  1369. var s;
  1370. if (trace > 0) {
  1371. s = 0.5 / Math.sqrt(trace + 1.0);
  1372. result.w = 0.25 / s;
  1373. result.x = (m32 - m23) * s;
  1374. result.y = (m13 - m31) * s;
  1375. result.z = (m21 - m12) * s;
  1376. }
  1377. else if (m11 > m22 && m11 > m33) {
  1378. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1379. result.w = (m32 - m23) / s;
  1380. result.x = 0.25 * s;
  1381. result.y = (m12 + m21) / s;
  1382. result.z = (m13 + m31) / s;
  1383. }
  1384. else if (m22 > m33) {
  1385. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1386. result.w = (m13 - m31) / s;
  1387. result.x = (m12 + m21) / s;
  1388. result.y = 0.25 * s;
  1389. result.z = (m23 + m32) / s;
  1390. }
  1391. else {
  1392. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1393. result.w = (m21 - m12) / s;
  1394. result.x = (m13 + m31) / s;
  1395. result.y = (m23 + m32) / s;
  1396. result.z = 0.25 * s;
  1397. }
  1398. };
  1399. Quaternion.Inverse = function (q) {
  1400. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1401. };
  1402. Quaternion.Identity = function () {
  1403. return new Quaternion(0, 0, 0, 1);
  1404. };
  1405. Quaternion.RotationAxis = function (axis, angle) {
  1406. var result = new Quaternion();
  1407. var sin = Math.sin(angle / 2);
  1408. axis.normalize();
  1409. result.w = Math.cos(angle / 2);
  1410. result.x = axis.x * sin;
  1411. result.y = axis.y * sin;
  1412. result.z = axis.z * sin;
  1413. return result;
  1414. };
  1415. Quaternion.FromArray = function (array, offset) {
  1416. if (!offset) {
  1417. offset = 0;
  1418. }
  1419. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1420. };
  1421. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1422. var result = new Quaternion();
  1423. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1424. return result;
  1425. };
  1426. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1427. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1428. var halfRoll = roll * 0.5;
  1429. var halfPitch = pitch * 0.5;
  1430. var halfYaw = yaw * 0.5;
  1431. var sinRoll = Math.sin(halfRoll);
  1432. var cosRoll = Math.cos(halfRoll);
  1433. var sinPitch = Math.sin(halfPitch);
  1434. var cosPitch = Math.cos(halfPitch);
  1435. var sinYaw = Math.sin(halfYaw);
  1436. var cosYaw = Math.cos(halfYaw);
  1437. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1438. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1439. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1440. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1441. };
  1442. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1448. // Produces a quaternion from Euler angles in the z-x-z orientation
  1449. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1450. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1451. var halfBeta = beta * 0.5;
  1452. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1454. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1456. };
  1457. Quaternion.Slerp = function (left, right, amount) {
  1458. var num2;
  1459. var num3;
  1460. var num = amount;
  1461. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1462. var flag = false;
  1463. if (num4 < 0) {
  1464. flag = true;
  1465. num4 = -num4;
  1466. }
  1467. if (num4 > 0.999999) {
  1468. num3 = 1 - num;
  1469. num2 = flag ? -num : num;
  1470. }
  1471. else {
  1472. var num5 = Math.acos(num4);
  1473. var num6 = (1.0 / Math.sin(num5));
  1474. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1475. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1476. }
  1477. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1478. };
  1479. return Quaternion;
  1480. })();
  1481. BABYLON.Quaternion = Quaternion;
  1482. var Matrix = (function () {
  1483. function Matrix() {
  1484. this.m = new Float32Array(16);
  1485. }
  1486. // Properties
  1487. Matrix.prototype.isIdentity = function () {
  1488. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1489. return false;
  1490. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1491. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1492. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1493. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1494. return false;
  1495. return true;
  1496. };
  1497. Matrix.prototype.determinant = function () {
  1498. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1499. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1500. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1501. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1502. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1503. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1504. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1505. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1506. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1507. };
  1508. // Methods
  1509. Matrix.prototype.toArray = function () {
  1510. return this.m;
  1511. };
  1512. Matrix.prototype.asArray = function () {
  1513. return this.toArray();
  1514. };
  1515. Matrix.prototype.invert = function () {
  1516. this.invertToRef(this);
  1517. return this;
  1518. };
  1519. Matrix.prototype.reset = function () {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = 0;
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.add = function (other) {
  1526. var result = new Matrix();
  1527. this.addToRef(other, result);
  1528. return result;
  1529. };
  1530. Matrix.prototype.addToRef = function (other, result) {
  1531. for (var index = 0; index < 16; index++) {
  1532. result.m[index] = this.m[index] + other.m[index];
  1533. }
  1534. return this;
  1535. };
  1536. Matrix.prototype.addToSelf = function (other) {
  1537. for (var index = 0; index < 16; index++) {
  1538. this.m[index] += other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.invertToRef = function (other) {
  1543. var l1 = this.m[0];
  1544. var l2 = this.m[1];
  1545. var l3 = this.m[2];
  1546. var l4 = this.m[3];
  1547. var l5 = this.m[4];
  1548. var l6 = this.m[5];
  1549. var l7 = this.m[6];
  1550. var l8 = this.m[7];
  1551. var l9 = this.m[8];
  1552. var l10 = this.m[9];
  1553. var l11 = this.m[10];
  1554. var l12 = this.m[11];
  1555. var l13 = this.m[12];
  1556. var l14 = this.m[13];
  1557. var l15 = this.m[14];
  1558. var l16 = this.m[15];
  1559. var l17 = (l11 * l16) - (l12 * l15);
  1560. var l18 = (l10 * l16) - (l12 * l14);
  1561. var l19 = (l10 * l15) - (l11 * l14);
  1562. var l20 = (l9 * l16) - (l12 * l13);
  1563. var l21 = (l9 * l15) - (l11 * l13);
  1564. var l22 = (l9 * l14) - (l10 * l13);
  1565. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1566. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1567. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1568. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1569. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1570. var l28 = (l7 * l16) - (l8 * l15);
  1571. var l29 = (l6 * l16) - (l8 * l14);
  1572. var l30 = (l6 * l15) - (l7 * l14);
  1573. var l31 = (l5 * l16) - (l8 * l13);
  1574. var l32 = (l5 * l15) - (l7 * l13);
  1575. var l33 = (l5 * l14) - (l6 * l13);
  1576. var l34 = (l7 * l12) - (l8 * l11);
  1577. var l35 = (l6 * l12) - (l8 * l10);
  1578. var l36 = (l6 * l11) - (l7 * l10);
  1579. var l37 = (l5 * l12) - (l8 * l9);
  1580. var l38 = (l5 * l11) - (l7 * l9);
  1581. var l39 = (l5 * l10) - (l6 * l9);
  1582. other.m[0] = l23 * l27;
  1583. other.m[4] = l24 * l27;
  1584. other.m[8] = l25 * l27;
  1585. other.m[12] = l26 * l27;
  1586. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1587. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1588. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1589. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1590. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1591. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1592. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1593. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1594. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1595. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1596. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1597. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1598. return this;
  1599. };
  1600. Matrix.prototype.invertToRefSIMD = function (other) {
  1601. var src = this.m;
  1602. var dest = other.m;
  1603. var row0, row1, row2, row3;
  1604. var tmp1;
  1605. var minor0, minor1, minor2, minor3;
  1606. var det;
  1607. // Load the 4 rows
  1608. var src0 = SIMD.float32x4.load(src, 0);
  1609. var src1 = SIMD.float32x4.load(src, 4);
  1610. var src2 = SIMD.float32x4.load(src, 8);
  1611. var src3 = SIMD.float32x4.load(src, 12);
  1612. // Transpose the source matrix. Sort of. Not a true transpose operation
  1613. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1614. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1615. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1616. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1617. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1618. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1619. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1620. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1621. // This is a true transposition, but it will lead to an incorrect result
  1622. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1623. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1624. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1625. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1626. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1627. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1628. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1629. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1630. // ----
  1631. tmp1 = SIMD.float32x4.mul(row2, row3);
  1632. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1633. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1634. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1635. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1636. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1637. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1638. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1639. // ----
  1640. tmp1 = SIMD.float32x4.mul(row1, row2);
  1641. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1643. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1646. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1647. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1652. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1653. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1656. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1657. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1658. // ----
  1659. tmp1 = SIMD.float32x4.mul(row0, row1);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1661. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1662. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1663. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1665. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1666. // ----
  1667. tmp1 = SIMD.float32x4.mul(row0, row3);
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1670. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1672. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1673. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1674. // ----
  1675. tmp1 = SIMD.float32x4.mul(row0, row2);
  1676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1677. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1678. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1680. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1681. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1682. // Compute determinant
  1683. det = SIMD.float32x4.mul(row0, minor0);
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1685. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1686. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1687. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1688. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1689. // These shuffles aren't necessary if the faulty transposition is done
  1690. // up at the top of this function.
  1691. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1692. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1693. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1694. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1695. // Compute final values by multiplying with 1/det
  1696. minor0 = SIMD.float32x4.mul(det, minor0);
  1697. minor1 = SIMD.float32x4.mul(det, minor1);
  1698. minor2 = SIMD.float32x4.mul(det, minor2);
  1699. minor3 = SIMD.float32x4.mul(det, minor3);
  1700. SIMD.float32x4.store(dest, 0, minor0);
  1701. SIMD.float32x4.store(dest, 4, minor1);
  1702. SIMD.float32x4.store(dest, 8, minor2);
  1703. SIMD.float32x4.store(dest, 12, minor3);
  1704. return this;
  1705. };
  1706. Matrix.prototype.setTranslation = function (vector3) {
  1707. this.m[12] = vector3.x;
  1708. this.m[13] = vector3.y;
  1709. this.m[14] = vector3.z;
  1710. return this;
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1786. if (offset === void 0) { offset = 0; }
  1787. var tm = this.m;
  1788. var om = other.m;
  1789. var om0 = SIMD.float32x4.load(om, 0);
  1790. var om1 = SIMD.float32x4.load(om, 4);
  1791. var om2 = SIMD.float32x4.load(om, 8);
  1792. var om3 = SIMD.float32x4.load(om, 12);
  1793. var tm0 = SIMD.float32x4.load(tm, 0);
  1794. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1795. var tm1 = SIMD.float32x4.load(tm, 4);
  1796. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1797. var tm2 = SIMD.float32x4.load(tm, 8);
  1798. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1799. var tm3 = SIMD.float32x4.load(tm, 12);
  1800. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1801. };
  1802. Matrix.prototype.equals = function (value) {
  1803. return value &&
  1804. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1805. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1806. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1807. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1808. };
  1809. Matrix.prototype.clone = function () {
  1810. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1811. };
  1812. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1813. translation.x = this.m[12];
  1814. translation.y = this.m[13];
  1815. translation.z = this.m[14];
  1816. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1817. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1818. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1819. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1820. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1821. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1822. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1823. rotation.x = 0;
  1824. rotation.y = 0;
  1825. rotation.z = 0;
  1826. rotation.w = 1;
  1827. return false;
  1828. }
  1829. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1830. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1831. return true;
  1832. };
  1833. // Statics
  1834. Matrix.FromArray = function (array, offset) {
  1835. var result = new Matrix();
  1836. if (!offset) {
  1837. offset = 0;
  1838. }
  1839. Matrix.FromArrayToRef(array, offset, result);
  1840. return result;
  1841. };
  1842. Matrix.FromArrayToRef = function (array, offset, result) {
  1843. for (var index = 0; index < 16; index++) {
  1844. result.m[index] = array[index + offset];
  1845. }
  1846. };
  1847. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1848. for (var index = 0; index < 16; index++) {
  1849. result.m[index] = array[index + offset] * scale;
  1850. }
  1851. };
  1852. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1853. result.m[0] = initialM11;
  1854. result.m[1] = initialM12;
  1855. result.m[2] = initialM13;
  1856. result.m[3] = initialM14;
  1857. result.m[4] = initialM21;
  1858. result.m[5] = initialM22;
  1859. result.m[6] = initialM23;
  1860. result.m[7] = initialM24;
  1861. result.m[8] = initialM31;
  1862. result.m[9] = initialM32;
  1863. result.m[10] = initialM33;
  1864. result.m[11] = initialM34;
  1865. result.m[12] = initialM41;
  1866. result.m[13] = initialM42;
  1867. result.m[14] = initialM43;
  1868. result.m[15] = initialM44;
  1869. };
  1870. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1871. var result = new Matrix();
  1872. result.m[0] = initialM11;
  1873. result.m[1] = initialM12;
  1874. result.m[2] = initialM13;
  1875. result.m[3] = initialM14;
  1876. result.m[4] = initialM21;
  1877. result.m[5] = initialM22;
  1878. result.m[6] = initialM23;
  1879. result.m[7] = initialM24;
  1880. result.m[8] = initialM31;
  1881. result.m[9] = initialM32;
  1882. result.m[10] = initialM33;
  1883. result.m[11] = initialM34;
  1884. result.m[12] = initialM41;
  1885. result.m[13] = initialM42;
  1886. result.m[14] = initialM43;
  1887. result.m[15] = initialM44;
  1888. return result;
  1889. };
  1890. Matrix.Compose = function (scale, rotation, translation) {
  1891. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1892. var rotationMatrix = Matrix.Identity();
  1893. rotation.toRotationMatrix(rotationMatrix);
  1894. result = result.multiply(rotationMatrix);
  1895. result.setTranslation(translation);
  1896. return result;
  1897. };
  1898. Matrix.Identity = function () {
  1899. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1900. };
  1901. Matrix.IdentityToRef = function (result) {
  1902. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1903. };
  1904. Matrix.Zero = function () {
  1905. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1906. };
  1907. Matrix.RotationX = function (angle) {
  1908. var result = new Matrix();
  1909. Matrix.RotationXToRef(angle, result);
  1910. return result;
  1911. };
  1912. Matrix.Invert = function (source) {
  1913. var result = new Matrix();
  1914. source.invertToRef(result);
  1915. return result;
  1916. };
  1917. Matrix.RotationXToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[0] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[5] = c;
  1923. result.m[10] = c;
  1924. result.m[9] = -s;
  1925. result.m[6] = s;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[7] = 0;
  1931. result.m[8] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationY = function (angle) {
  1938. var result = new Matrix();
  1939. Matrix.RotationYToRef(angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationYToRef = function (angle, result) {
  1943. var s = Math.sin(angle);
  1944. var c = Math.cos(angle);
  1945. result.m[5] = 1.0;
  1946. result.m[15] = 1.0;
  1947. result.m[0] = c;
  1948. result.m[2] = -s;
  1949. result.m[8] = s;
  1950. result.m[10] = c;
  1951. result.m[1] = 0;
  1952. result.m[3] = 0;
  1953. result.m[4] = 0;
  1954. result.m[6] = 0;
  1955. result.m[7] = 0;
  1956. result.m[9] = 0;
  1957. result.m[11] = 0;
  1958. result.m[12] = 0;
  1959. result.m[13] = 0;
  1960. result.m[14] = 0;
  1961. };
  1962. Matrix.RotationZ = function (angle) {
  1963. var result = new Matrix();
  1964. Matrix.RotationZToRef(angle, result);
  1965. return result;
  1966. };
  1967. Matrix.RotationZToRef = function (angle, result) {
  1968. var s = Math.sin(angle);
  1969. var c = Math.cos(angle);
  1970. result.m[10] = 1.0;
  1971. result.m[15] = 1.0;
  1972. result.m[0] = c;
  1973. result.m[1] = s;
  1974. result.m[4] = -s;
  1975. result.m[5] = c;
  1976. result.m[2] = 0;
  1977. result.m[3] = 0;
  1978. result.m[6] = 0;
  1979. result.m[7] = 0;
  1980. result.m[8] = 0;
  1981. result.m[9] = 0;
  1982. result.m[11] = 0;
  1983. result.m[12] = 0;
  1984. result.m[13] = 0;
  1985. result.m[14] = 0;
  1986. };
  1987. Matrix.RotationAxis = function (axis, angle) {
  1988. var s = Math.sin(-angle);
  1989. var c = Math.cos(-angle);
  1990. var c1 = 1 - c;
  1991. axis.normalize();
  1992. var result = Matrix.Zero();
  1993. result.m[0] = (axis.x * axis.x) * c1 + c;
  1994. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1995. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1996. result.m[3] = 0.0;
  1997. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1998. result.m[5] = (axis.y * axis.y) * c1 + c;
  1999. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2000. result.m[7] = 0.0;
  2001. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2002. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2003. result.m[10] = (axis.z * axis.z) * c1 + c;
  2004. result.m[11] = 0.0;
  2005. result.m[15] = 1.0;
  2006. return result;
  2007. };
  2008. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2009. var result = new Matrix();
  2010. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2011. return result;
  2012. };
  2013. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2014. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2015. this._tempQuaternion.toRotationMatrix(result);
  2016. };
  2017. Matrix.Scaling = function (x, y, z) {
  2018. var result = Matrix.Zero();
  2019. Matrix.ScalingToRef(x, y, z, result);
  2020. return result;
  2021. };
  2022. Matrix.ScalingToRef = function (x, y, z, result) {
  2023. result.m[0] = x;
  2024. result.m[1] = 0;
  2025. result.m[2] = 0;
  2026. result.m[3] = 0;
  2027. result.m[4] = 0;
  2028. result.m[5] = y;
  2029. result.m[6] = 0;
  2030. result.m[7] = 0;
  2031. result.m[8] = 0;
  2032. result.m[9] = 0;
  2033. result.m[10] = z;
  2034. result.m[11] = 0;
  2035. result.m[12] = 0;
  2036. result.m[13] = 0;
  2037. result.m[14] = 0;
  2038. result.m[15] = 1.0;
  2039. };
  2040. Matrix.Translation = function (x, y, z) {
  2041. var result = Matrix.Identity();
  2042. Matrix.TranslationToRef(x, y, z, result);
  2043. return result;
  2044. };
  2045. Matrix.TranslationToRef = function (x, y, z, result) {
  2046. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2047. };
  2048. Matrix.LookAtLH = function (eye, target, up) {
  2049. var result = Matrix.Zero();
  2050. Matrix.LookAtLHToRef(eye, target, up, result);
  2051. return result;
  2052. };
  2053. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2054. // Z axis
  2055. target.subtractToRef(eye, this._zAxis);
  2056. this._zAxis.normalize();
  2057. // X axis
  2058. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2059. if (this._xAxis.lengthSquared() === 0) {
  2060. this._xAxis.x = 1.0;
  2061. }
  2062. else {
  2063. this._xAxis.normalize();
  2064. }
  2065. // Y axis
  2066. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2067. this._yAxis.normalize();
  2068. // Eye angles
  2069. var ex = -Vector3.Dot(this._xAxis, eye);
  2070. var ey = -Vector3.Dot(this._yAxis, eye);
  2071. var ez = -Vector3.Dot(this._zAxis, eye);
  2072. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2073. };
  2074. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2075. var out = result.m;
  2076. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2077. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2078. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2079. // cc.kmVec3Subtract(f, pCenter, pEye);
  2080. var f = SIMD.float32x4.sub(center, eye);
  2081. // cc.kmVec3Normalize(f, f);
  2082. var tmp = SIMD.float32x4.mul(f, f);
  2083. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2084. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2085. // cc.kmVec3Assign(up, pUp);
  2086. // cc.kmVec3Normalize(up, up);
  2087. tmp = SIMD.float32x4.mul(up, up);
  2088. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2089. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2090. // cc.kmVec3Cross(s, f, up);
  2091. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2092. // cc.kmVec3Normalize(s, s);
  2093. tmp = SIMD.float32x4.mul(s, s);
  2094. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2095. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2096. // cc.kmVec3Cross(u, s, f);
  2097. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2098. // cc.kmVec3Normalize(s, s);
  2099. tmp = SIMD.float32x4.mul(s, s);
  2100. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2101. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2102. var zero = SIMD.float32x4.splat(0.0);
  2103. s = SIMD.float32x4.neg(s);
  2104. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2105. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2106. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2107. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2108. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2109. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2110. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2111. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2112. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2113. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2114. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2115. var b3 = SIMD.float32x4.neg(eye);
  2116. b3 = SIMD.float32x4.withW(b3, 1.0);
  2117. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2118. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2119. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2120. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2121. };
  2122. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2123. var matrix = Matrix.Zero();
  2124. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2125. return matrix;
  2126. };
  2127. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2128. var hw = 2.0 / width;
  2129. var hh = 2.0 / height;
  2130. var id = 1.0 / (zfar - znear);
  2131. var nid = znear / (znear - zfar);
  2132. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2133. };
  2134. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2135. var matrix = Matrix.Zero();
  2136. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2137. return matrix;
  2138. };
  2139. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2140. result.m[0] = 2.0 / (right - left);
  2141. result.m[1] = result.m[2] = result.m[3] = 0;
  2142. result.m[5] = 2.0 / (top - bottom);
  2143. result.m[4] = result.m[6] = result.m[7] = 0;
  2144. result.m[10] = -1.0 / (znear - zfar);
  2145. result.m[8] = result.m[9] = result.m[11] = 0;
  2146. result.m[12] = (left + right) / (left - right);
  2147. result.m[13] = (top + bottom) / (bottom - top);
  2148. result.m[14] = znear / (znear - zfar);
  2149. result.m[15] = 1.0;
  2150. };
  2151. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2152. var matrix = Matrix.Zero();
  2153. matrix.m[0] = (2.0 * znear) / width;
  2154. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2155. matrix.m[5] = (2.0 * znear) / height;
  2156. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2157. matrix.m[10] = -zfar / (znear - zfar);
  2158. matrix.m[8] = matrix.m[9] = 0.0;
  2159. matrix.m[11] = 1.0;
  2160. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2161. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2162. return matrix;
  2163. };
  2164. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2165. var matrix = Matrix.Zero();
  2166. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2167. return matrix;
  2168. };
  2169. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2170. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2171. var tan = 1.0 / (Math.tan(fov * 0.5));
  2172. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2173. if (v_fixed) {
  2174. result.m[0] = tan / aspect;
  2175. }
  2176. else {
  2177. result.m[0] = tan;
  2178. }
  2179. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2180. if (v_fixed) {
  2181. result.m[5] = tan;
  2182. }
  2183. else {
  2184. result.m[5] = tan * aspect;
  2185. }
  2186. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2187. result.m[8] = result.m[9] = 0.0;
  2188. result.m[10] = -zfar / (znear - zfar);
  2189. result.m[11] = 1.0;
  2190. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2191. result.m[14] = (znear * zfar) / (znear - zfar);
  2192. };
  2193. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2194. var cw = viewport.width;
  2195. var ch = viewport.height;
  2196. var cx = viewport.x;
  2197. var cy = viewport.y;
  2198. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2199. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2200. };
  2201. Matrix.GetAsMatrix2x2 = function (matrix) {
  2202. return new Float32Array([
  2203. matrix.m[0], matrix.m[1],
  2204. matrix.m[4], matrix.m[5]
  2205. ]);
  2206. };
  2207. Matrix.GetAsMatrix3x3 = function (matrix) {
  2208. return new Float32Array([
  2209. matrix.m[0], matrix.m[1], matrix.m[2],
  2210. matrix.m[4], matrix.m[5], matrix.m[6],
  2211. matrix.m[8], matrix.m[9], matrix.m[10]
  2212. ]);
  2213. };
  2214. Matrix.Transpose = function (matrix) {
  2215. var result = new Matrix();
  2216. result.m[0] = matrix.m[0];
  2217. result.m[1] = matrix.m[4];
  2218. result.m[2] = matrix.m[8];
  2219. result.m[3] = matrix.m[12];
  2220. result.m[4] = matrix.m[1];
  2221. result.m[5] = matrix.m[5];
  2222. result.m[6] = matrix.m[9];
  2223. result.m[7] = matrix.m[13];
  2224. result.m[8] = matrix.m[2];
  2225. result.m[9] = matrix.m[6];
  2226. result.m[10] = matrix.m[10];
  2227. result.m[11] = matrix.m[14];
  2228. result.m[12] = matrix.m[3];
  2229. result.m[13] = matrix.m[7];
  2230. result.m[14] = matrix.m[11];
  2231. result.m[15] = matrix.m[15];
  2232. return result;
  2233. };
  2234. Matrix.Reflection = function (plane) {
  2235. var matrix = new Matrix();
  2236. Matrix.ReflectionToRef(plane, matrix);
  2237. return matrix;
  2238. };
  2239. Matrix.ReflectionToRef = function (plane, result) {
  2240. plane.normalize();
  2241. var x = plane.normal.x;
  2242. var y = plane.normal.y;
  2243. var z = plane.normal.z;
  2244. var temp = -2 * x;
  2245. var temp2 = -2 * y;
  2246. var temp3 = -2 * z;
  2247. result.m[0] = (temp * x) + 1;
  2248. result.m[1] = temp2 * x;
  2249. result.m[2] = temp3 * x;
  2250. result.m[3] = 0.0;
  2251. result.m[4] = temp * y;
  2252. result.m[5] = (temp2 * y) + 1;
  2253. result.m[6] = temp3 * y;
  2254. result.m[7] = 0.0;
  2255. result.m[8] = temp * z;
  2256. result.m[9] = temp2 * z;
  2257. result.m[10] = (temp3 * z) + 1;
  2258. result.m[11] = 0.0;
  2259. result.m[12] = temp * plane.d;
  2260. result.m[13] = temp2 * plane.d;
  2261. result.m[14] = temp3 * plane.d;
  2262. result.m[15] = 1.0;
  2263. };
  2264. Matrix._tempQuaternion = new Quaternion();
  2265. Matrix._xAxis = Vector3.Zero();
  2266. Matrix._yAxis = Vector3.Zero();
  2267. Matrix._zAxis = Vector3.Zero();
  2268. return Matrix;
  2269. })();
  2270. BABYLON.Matrix = Matrix;
  2271. var Plane = (function () {
  2272. function Plane(a, b, c, d) {
  2273. this.normal = new Vector3(a, b, c);
  2274. this.d = d;
  2275. }
  2276. Plane.prototype.asArray = function () {
  2277. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2278. };
  2279. // Methods
  2280. Plane.prototype.clone = function () {
  2281. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2282. };
  2283. Plane.prototype.normalize = function () {
  2284. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2285. var magnitude = 0;
  2286. if (norm !== 0) {
  2287. magnitude = 1.0 / norm;
  2288. }
  2289. this.normal.x *= magnitude;
  2290. this.normal.y *= magnitude;
  2291. this.normal.z *= magnitude;
  2292. this.d *= magnitude;
  2293. return this;
  2294. };
  2295. Plane.prototype.transform = function (transformation) {
  2296. var transposedMatrix = Matrix.Transpose(transformation);
  2297. var x = this.normal.x;
  2298. var y = this.normal.y;
  2299. var z = this.normal.z;
  2300. var d = this.d;
  2301. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2302. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2303. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2304. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2305. return new Plane(normalX, normalY, normalZ, finalD);
  2306. };
  2307. Plane.prototype.dotCoordinate = function (point) {
  2308. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2309. };
  2310. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2311. var x1 = point2.x - point1.x;
  2312. var y1 = point2.y - point1.y;
  2313. var z1 = point2.z - point1.z;
  2314. var x2 = point3.x - point1.x;
  2315. var y2 = point3.y - point1.y;
  2316. var z2 = point3.z - point1.z;
  2317. var yz = (y1 * z2) - (z1 * y2);
  2318. var xz = (z1 * x2) - (x1 * z2);
  2319. var xy = (x1 * y2) - (y1 * x2);
  2320. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2321. var invPyth;
  2322. if (pyth !== 0) {
  2323. invPyth = 1.0 / pyth;
  2324. }
  2325. else {
  2326. invPyth = 0;
  2327. }
  2328. this.normal.x = yz * invPyth;
  2329. this.normal.y = xz * invPyth;
  2330. this.normal.z = xy * invPyth;
  2331. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2332. return this;
  2333. };
  2334. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2335. var dot = Vector3.Dot(this.normal, direction);
  2336. return (dot <= epsilon);
  2337. };
  2338. Plane.prototype.signedDistanceTo = function (point) {
  2339. return Vector3.Dot(point, this.normal) + this.d;
  2340. };
  2341. // Statics
  2342. Plane.FromArray = function (array) {
  2343. return new Plane(array[0], array[1], array[2], array[3]);
  2344. };
  2345. Plane.FromPoints = function (point1, point2, point3) {
  2346. var result = new Plane(0, 0, 0, 0);
  2347. result.copyFromPoints(point1, point2, point3);
  2348. return result;
  2349. };
  2350. Plane.FromPositionAndNormal = function (origin, normal) {
  2351. var result = new Plane(0, 0, 0, 0);
  2352. normal.normalize();
  2353. result.normal = normal;
  2354. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2355. return result;
  2356. };
  2357. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2358. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2359. return Vector3.Dot(point, normal) + d;
  2360. };
  2361. return Plane;
  2362. })();
  2363. BABYLON.Plane = Plane;
  2364. var Viewport = (function () {
  2365. function Viewport(x, y, width, height) {
  2366. this.x = x;
  2367. this.y = y;
  2368. this.width = width;
  2369. this.height = height;
  2370. }
  2371. Viewport.prototype.toGlobal = function (engine) {
  2372. var width = engine.getRenderWidth();
  2373. var height = engine.getRenderHeight();
  2374. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2375. };
  2376. return Viewport;
  2377. })();
  2378. BABYLON.Viewport = Viewport;
  2379. var Frustum = (function () {
  2380. function Frustum() {
  2381. }
  2382. Frustum.GetPlanes = function (transform) {
  2383. var frustumPlanes = [];
  2384. for (var index = 0; index < 6; index++) {
  2385. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2386. }
  2387. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2388. return frustumPlanes;
  2389. };
  2390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2391. // Near
  2392. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2393. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2394. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2395. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2396. frustumPlanes[0].normalize();
  2397. // Far
  2398. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2399. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2400. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2401. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2402. frustumPlanes[1].normalize();
  2403. // Left
  2404. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2405. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2406. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2407. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2408. frustumPlanes[2].normalize();
  2409. // Right
  2410. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2411. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2412. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2413. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2414. frustumPlanes[3].normalize();
  2415. // Top
  2416. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2417. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2418. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2419. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2420. frustumPlanes[4].normalize();
  2421. // Bottom
  2422. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2423. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2424. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2425. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2426. frustumPlanes[5].normalize();
  2427. };
  2428. return Frustum;
  2429. })();
  2430. BABYLON.Frustum = Frustum;
  2431. var Ray = (function () {
  2432. function Ray(origin, direction, length) {
  2433. if (length === void 0) { length = Number.MAX_VALUE; }
  2434. this.origin = origin;
  2435. this.direction = direction;
  2436. this.length = length;
  2437. }
  2438. // Methods
  2439. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2440. var d = 0.0;
  2441. var maxValue = Number.MAX_VALUE;
  2442. var inv;
  2443. var min;
  2444. var max;
  2445. var temp;
  2446. if (Math.abs(this.direction.x) < 0.0000001) {
  2447. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2448. return false;
  2449. }
  2450. }
  2451. else {
  2452. inv = 1.0 / this.direction.x;
  2453. min = (minimum.x - this.origin.x) * inv;
  2454. max = (maximum.x - this.origin.x) * inv;
  2455. if (max === -Infinity) {
  2456. max = Infinity;
  2457. }
  2458. if (min > max) {
  2459. temp = min;
  2460. min = max;
  2461. max = temp;
  2462. }
  2463. d = Math.max(min, d);
  2464. maxValue = Math.min(max, maxValue);
  2465. if (d > maxValue) {
  2466. return false;
  2467. }
  2468. }
  2469. if (Math.abs(this.direction.y) < 0.0000001) {
  2470. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2471. return false;
  2472. }
  2473. }
  2474. else {
  2475. inv = 1.0 / this.direction.y;
  2476. min = (minimum.y - this.origin.y) * inv;
  2477. max = (maximum.y - this.origin.y) * inv;
  2478. if (max === -Infinity) {
  2479. max = Infinity;
  2480. }
  2481. if (min > max) {
  2482. temp = min;
  2483. min = max;
  2484. max = temp;
  2485. }
  2486. d = Math.max(min, d);
  2487. maxValue = Math.min(max, maxValue);
  2488. if (d > maxValue) {
  2489. return false;
  2490. }
  2491. }
  2492. if (Math.abs(this.direction.z) < 0.0000001) {
  2493. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2494. return false;
  2495. }
  2496. }
  2497. else {
  2498. inv = 1.0 / this.direction.z;
  2499. min = (minimum.z - this.origin.z) * inv;
  2500. max = (maximum.z - this.origin.z) * inv;
  2501. if (max === -Infinity) {
  2502. max = Infinity;
  2503. }
  2504. if (min > max) {
  2505. temp = min;
  2506. min = max;
  2507. max = temp;
  2508. }
  2509. d = Math.max(min, d);
  2510. maxValue = Math.min(max, maxValue);
  2511. if (d > maxValue) {
  2512. return false;
  2513. }
  2514. }
  2515. return true;
  2516. };
  2517. Ray.prototype.intersectsBox = function (box) {
  2518. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2519. };
  2520. Ray.prototype.intersectsSphere = function (sphere) {
  2521. var x = sphere.center.x - this.origin.x;
  2522. var y = sphere.center.y - this.origin.y;
  2523. var z = sphere.center.z - this.origin.z;
  2524. var pyth = (x * x) + (y * y) + (z * z);
  2525. var rr = sphere.radius * sphere.radius;
  2526. if (pyth <= rr) {
  2527. return true;
  2528. }
  2529. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2530. if (dot < 0.0) {
  2531. return false;
  2532. }
  2533. var temp = pyth - (dot * dot);
  2534. return temp <= rr;
  2535. };
  2536. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2537. if (!this._edge1) {
  2538. this._edge1 = Vector3.Zero();
  2539. this._edge2 = Vector3.Zero();
  2540. this._pvec = Vector3.Zero();
  2541. this._tvec = Vector3.Zero();
  2542. this._qvec = Vector3.Zero();
  2543. }
  2544. vertex1.subtractToRef(vertex0, this._edge1);
  2545. vertex2.subtractToRef(vertex0, this._edge2);
  2546. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2547. var det = Vector3.Dot(this._edge1, this._pvec);
  2548. if (det === 0) {
  2549. return null;
  2550. }
  2551. var invdet = 1 / det;
  2552. this.origin.subtractToRef(vertex0, this._tvec);
  2553. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2554. if (bu < 0 || bu > 1.0) {
  2555. return null;
  2556. }
  2557. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2558. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2559. if (bv < 0 || bu + bv > 1.0) {
  2560. return null;
  2561. }
  2562. //check if the distance is longer than the predefined length.
  2563. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2564. if (distance > this.length) {
  2565. return null;
  2566. }
  2567. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2568. };
  2569. // Statics
  2570. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2571. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2572. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2573. var direction = end.subtract(start);
  2574. direction.normalize();
  2575. return new Ray(start, direction);
  2576. };
  2577. /**
  2578. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2579. * transformed to the given world matrix.
  2580. * @param origin The origin point
  2581. * @param end The end point
  2582. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2583. */
  2584. Ray.CreateNewFromTo = function (origin, end, world) {
  2585. if (world === void 0) { world = Matrix.Identity(); }
  2586. var direction = end.subtract(origin);
  2587. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2588. direction.normalize();
  2589. return Ray.Transform(new Ray(origin, direction, length), world);
  2590. };
  2591. Ray.Transform = function (ray, matrix) {
  2592. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2593. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2594. return new Ray(newOrigin, newDirection, ray.length);
  2595. };
  2596. return Ray;
  2597. })();
  2598. BABYLON.Ray = Ray;
  2599. (function (Space) {
  2600. Space[Space["LOCAL"] = 0] = "LOCAL";
  2601. Space[Space["WORLD"] = 1] = "WORLD";
  2602. })(BABYLON.Space || (BABYLON.Space = {}));
  2603. var Space = BABYLON.Space;
  2604. var Axis = (function () {
  2605. function Axis() {
  2606. }
  2607. Axis.X = new Vector3(1, 0, 0);
  2608. Axis.Y = new Vector3(0, 1, 0);
  2609. Axis.Z = new Vector3(0, 0, 1);
  2610. return Axis;
  2611. })();
  2612. BABYLON.Axis = Axis;
  2613. ;
  2614. var BezierCurve = (function () {
  2615. function BezierCurve() {
  2616. }
  2617. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2618. // Extract X (which is equal to time here)
  2619. var f0 = 1 - 3 * x2 + 3 * x1;
  2620. var f1 = 3 * x2 - 6 * x1;
  2621. var f2 = 3 * x1;
  2622. var refinedT = t;
  2623. for (var i = 0; i < 5; i++) {
  2624. var refinedT2 = refinedT * refinedT;
  2625. var refinedT3 = refinedT2 * refinedT;
  2626. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2627. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2628. refinedT -= (x - t) * slope;
  2629. refinedT = Math.min(1, Math.max(0, refinedT));
  2630. }
  2631. // Resolve cubic bezier for the given x
  2632. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2633. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2634. Math.pow(refinedT, 3);
  2635. };
  2636. return BezierCurve;
  2637. })();
  2638. BABYLON.BezierCurve = BezierCurve;
  2639. (function (Orientation) {
  2640. Orientation[Orientation["CW"] = 0] = "CW";
  2641. Orientation[Orientation["CCW"] = 1] = "CCW";
  2642. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2643. var Orientation = BABYLON.Orientation;
  2644. var Angle = (function () {
  2645. function Angle(radians) {
  2646. var _this = this;
  2647. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2648. this.radians = function () { return _this._radians; };
  2649. this._radians = radians;
  2650. if (this._radians < 0)
  2651. this._radians += (2 * Math.PI);
  2652. }
  2653. Angle.BetweenTwoPoints = function (a, b) {
  2654. var delta = b.subtract(a);
  2655. var theta = Math.atan2(delta.y, delta.x);
  2656. return new Angle(theta);
  2657. };
  2658. Angle.FromRadians = function (radians) {
  2659. return new Angle(radians);
  2660. };
  2661. Angle.FromDegrees = function (degrees) {
  2662. return new Angle(degrees * Math.PI / 180);
  2663. };
  2664. return Angle;
  2665. })();
  2666. BABYLON.Angle = Angle;
  2667. var Arc2 = (function () {
  2668. function Arc2(startPoint, midPoint, endPoint) {
  2669. this.startPoint = startPoint;
  2670. this.midPoint = midPoint;
  2671. this.endPoint = endPoint;
  2672. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2673. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2674. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2675. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2676. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2677. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2678. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2679. var a1 = this.startAngle.degrees();
  2680. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2681. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2682. // angles correction
  2683. if (a2 - a1 > +180.0)
  2684. a2 -= 360.0;
  2685. if (a2 - a1 < -180.0)
  2686. a2 += 360.0;
  2687. if (a3 - a2 > +180.0)
  2688. a3 -= 360.0;
  2689. if (a3 - a2 < -180.0)
  2690. a3 += 360.0;
  2691. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2692. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2693. }
  2694. return Arc2;
  2695. })();
  2696. BABYLON.Arc2 = Arc2;
  2697. var PathCursor = (function () {
  2698. function PathCursor(path) {
  2699. this.path = path;
  2700. this._onchange = new Array();
  2701. this.value = 0;
  2702. this.animations = new Array();
  2703. }
  2704. PathCursor.prototype.getPoint = function () {
  2705. var point = this.path.getPointAtLengthPosition(this.value);
  2706. return new Vector3(point.x, 0, point.y);
  2707. };
  2708. PathCursor.prototype.moveAhead = function (step) {
  2709. if (step === void 0) { step = 0.002; }
  2710. this.move(step);
  2711. return this;
  2712. };
  2713. PathCursor.prototype.moveBack = function (step) {
  2714. if (step === void 0) { step = 0.002; }
  2715. this.move(-step);
  2716. return this;
  2717. };
  2718. PathCursor.prototype.move = function (step) {
  2719. if (Math.abs(step) > 1) {
  2720. throw "step size should be less than 1.";
  2721. }
  2722. this.value += step;
  2723. this.ensureLimits();
  2724. this.raiseOnChange();
  2725. return this;
  2726. };
  2727. PathCursor.prototype.ensureLimits = function () {
  2728. while (this.value > 1) {
  2729. this.value -= 1;
  2730. }
  2731. while (this.value < 0) {
  2732. this.value += 1;
  2733. }
  2734. return this;
  2735. };
  2736. // used by animation engine
  2737. PathCursor.prototype.markAsDirty = function (propertyName) {
  2738. this.ensureLimits();
  2739. this.raiseOnChange();
  2740. return this;
  2741. };
  2742. PathCursor.prototype.raiseOnChange = function () {
  2743. var _this = this;
  2744. this._onchange.forEach(function (f) { return f(_this); });
  2745. return this;
  2746. };
  2747. PathCursor.prototype.onchange = function (f) {
  2748. this._onchange.push(f);
  2749. return this;
  2750. };
  2751. return PathCursor;
  2752. })();
  2753. BABYLON.PathCursor = PathCursor;
  2754. var Path2 = (function () {
  2755. function Path2(x, y) {
  2756. this._points = new Array();
  2757. this._length = 0;
  2758. this.closed = false;
  2759. this._points.push(new Vector2(x, y));
  2760. }
  2761. Path2.prototype.addLineTo = function (x, y) {
  2762. if (closed) {
  2763. BABYLON.Tools.Error("cannot add lines to closed paths");
  2764. return this;
  2765. }
  2766. var newPoint = new Vector2(x, y);
  2767. var previousPoint = this._points[this._points.length - 1];
  2768. this._points.push(newPoint);
  2769. this._length += newPoint.subtract(previousPoint).length();
  2770. return this;
  2771. };
  2772. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2773. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2774. if (closed) {
  2775. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2776. return this;
  2777. }
  2778. var startPoint = this._points[this._points.length - 1];
  2779. var midPoint = new Vector2(midX, midY);
  2780. var endPoint = new Vector2(endX, endY);
  2781. var arc = new Arc2(startPoint, midPoint, endPoint);
  2782. var increment = arc.angle.radians() / numberOfSegments;
  2783. if (arc.orientation === Orientation.CW)
  2784. increment *= -1;
  2785. var currentAngle = arc.startAngle.radians() + increment;
  2786. for (var i = 0; i < numberOfSegments; i++) {
  2787. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2788. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2789. this.addLineTo(x, y);
  2790. currentAngle += increment;
  2791. }
  2792. return this;
  2793. };
  2794. Path2.prototype.close = function () {
  2795. this.closed = true;
  2796. return this;
  2797. };
  2798. Path2.prototype.length = function () {
  2799. var result = this._length;
  2800. if (!this.closed) {
  2801. var lastPoint = this._points[this._points.length - 1];
  2802. var firstPoint = this._points[0];
  2803. result += (firstPoint.subtract(lastPoint).length());
  2804. }
  2805. return result;
  2806. };
  2807. Path2.prototype.getPoints = function () {
  2808. return this._points;
  2809. };
  2810. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2811. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2812. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2813. return Vector2.Zero();
  2814. }
  2815. var lengthPosition = normalizedLengthPosition * this.length();
  2816. var previousOffset = 0;
  2817. for (var i = 0; i < this._points.length; i++) {
  2818. var j = (i + 1) % this._points.length;
  2819. var a = this._points[i];
  2820. var b = this._points[j];
  2821. var bToA = b.subtract(a);
  2822. var nextOffset = (bToA.length() + previousOffset);
  2823. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2824. var dir = bToA.normalize();
  2825. var localOffset = lengthPosition - previousOffset;
  2826. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2827. }
  2828. previousOffset = nextOffset;
  2829. }
  2830. BABYLON.Tools.Error("internal error");
  2831. return Vector2.Zero();
  2832. };
  2833. Path2.StartingAt = function (x, y) {
  2834. return new Path2(x, y);
  2835. };
  2836. return Path2;
  2837. })();
  2838. BABYLON.Path2 = Path2;
  2839. var Path3D = (function () {
  2840. /**
  2841. * new Path3D(path, normal, raw)
  2842. * path : an array of Vector3, the curve axis of the Path3D
  2843. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2844. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2845. */
  2846. function Path3D(path, firstNormal, raw) {
  2847. this.path = path;
  2848. this._curve = new Array();
  2849. this._distances = new Array();
  2850. this._tangents = new Array();
  2851. this._normals = new Array();
  2852. this._binormals = new Array();
  2853. for (var p = 0; p < path.length; p++) {
  2854. this._curve[p] = path[p].clone(); // hard copy
  2855. }
  2856. this._raw = raw || false;
  2857. this._compute(firstNormal);
  2858. }
  2859. Path3D.prototype.getCurve = function () {
  2860. return this._curve;
  2861. };
  2862. Path3D.prototype.getTangents = function () {
  2863. return this._tangents;
  2864. };
  2865. Path3D.prototype.getNormals = function () {
  2866. return this._normals;
  2867. };
  2868. Path3D.prototype.getBinormals = function () {
  2869. return this._binormals;
  2870. };
  2871. Path3D.prototype.getDistances = function () {
  2872. return this._distances;
  2873. };
  2874. Path3D.prototype.update = function (path, firstNormal) {
  2875. for (var p = 0; p < path.length; p++) {
  2876. this._curve[p].x = path[p].x;
  2877. this._curve[p].y = path[p].y;
  2878. this._curve[p].z = path[p].z;
  2879. }
  2880. this._compute(firstNormal);
  2881. return this;
  2882. };
  2883. // private function compute() : computes tangents, normals and binormals
  2884. Path3D.prototype._compute = function (firstNormal) {
  2885. var l = this._curve.length;
  2886. // first and last tangents
  2887. this._tangents[0] = this._getFirstNonNullVector(0);
  2888. if (!this._raw) {
  2889. this._tangents[0].normalize();
  2890. }
  2891. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2892. if (!this._raw) {
  2893. this._tangents[l - 1].normalize();
  2894. }
  2895. // normals and binormals at first point : arbitrary vector with _normalVector()
  2896. var tg0 = this._tangents[0];
  2897. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2898. this._normals[0] = pp0;
  2899. if (!this._raw) {
  2900. this._normals[0].normalize();
  2901. }
  2902. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2903. if (!this._raw) {
  2904. this._binormals[0].normalize();
  2905. }
  2906. this._distances[0] = 0;
  2907. // normals and binormals : next points
  2908. var prev; // previous vector (segment)
  2909. var cur; // current vector (segment)
  2910. var curTang; // current tangent
  2911. // previous normal
  2912. var prevBinor; // previous binormal
  2913. for (var i = 1; i < l; i++) {
  2914. // tangents
  2915. prev = this._getLastNonNullVector(i);
  2916. if (i < l - 1) {
  2917. cur = this._getFirstNonNullVector(i);
  2918. this._tangents[i] = prev.add(cur);
  2919. this._tangents[i].normalize();
  2920. }
  2921. this._distances[i] = this._distances[i - 1] + prev.length();
  2922. // normals and binormals
  2923. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2924. curTang = this._tangents[i];
  2925. prevBinor = this._binormals[i - 1];
  2926. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2927. if (!this._raw) {
  2928. this._normals[i].normalize();
  2929. }
  2930. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2931. if (!this._raw) {
  2932. this._binormals[i].normalize();
  2933. }
  2934. }
  2935. };
  2936. // private function getFirstNonNullVector(index)
  2937. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2938. Path3D.prototype._getFirstNonNullVector = function (index) {
  2939. var i = 1;
  2940. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2941. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2942. i++;
  2943. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. }
  2945. return nNVector;
  2946. };
  2947. // private function getLastNonNullVector(index)
  2948. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2949. Path3D.prototype._getLastNonNullVector = function (index) {
  2950. var i = 1;
  2951. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2952. while (nLVector.length() === 0 && index > i + 1) {
  2953. i++;
  2954. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. }
  2956. return nLVector;
  2957. };
  2958. // private function normalVector(v0, vt, va) :
  2959. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2960. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2961. Path3D.prototype._normalVector = function (v0, vt, va) {
  2962. var normal0;
  2963. if (va === undefined || va === null) {
  2964. var point;
  2965. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2966. point = new Vector3(0, -1, 0);
  2967. }
  2968. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(1, 0, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(0, 0, 1);
  2973. }
  2974. normal0 = Vector3.Cross(vt, point);
  2975. }
  2976. else {
  2977. normal0 = Vector3.Cross(vt, va);
  2978. Vector3.CrossToRef(normal0, vt, normal0);
  2979. }
  2980. normal0.normalize();
  2981. return normal0;
  2982. };
  2983. return Path3D;
  2984. })();
  2985. BABYLON.Path3D = Path3D;
  2986. var Curve3 = (function () {
  2987. function Curve3(points) {
  2988. this._length = 0;
  2989. this._points = points;
  2990. this._length = this._computeLength(points);
  2991. }
  2992. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2993. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2994. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2995. var bez = new Array();
  2996. var equation = function (t, val0, val1, val2) {
  2997. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2998. return res;
  2999. };
  3000. for (var i = 0; i <= nbPoints; i++) {
  3001. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3002. }
  3003. return new Curve3(bez);
  3004. };
  3005. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3006. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3007. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3008. var bez = new Array();
  3009. var equation = function (t, val0, val1, val2, val3) {
  3010. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  3011. return res;
  3012. };
  3013. for (var i = 0; i <= nbPoints; i++) {
  3014. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3015. }
  3016. return new Curve3(bez);
  3017. };
  3018. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3019. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3020. var hermite = new Array();
  3021. var step = 1 / nbPoints;
  3022. for (var i = 0; i <= nbPoints; i++) {
  3023. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3024. }
  3025. return new Curve3(hermite);
  3026. };
  3027. Curve3.prototype.getPoints = function () {
  3028. return this._points;
  3029. };
  3030. Curve3.prototype.length = function () {
  3031. return this._length;
  3032. };
  3033. Curve3.prototype.continue = function (curve) {
  3034. var lastPoint = this._points[this._points.length - 1];
  3035. var continuedPoints = this._points.slice();
  3036. var curvePoints = curve.getPoints();
  3037. for (var i = 1; i < curvePoints.length; i++) {
  3038. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3039. }
  3040. var continuedCurve = new Curve3(continuedPoints);
  3041. return continuedCurve;
  3042. };
  3043. Curve3.prototype._computeLength = function (path) {
  3044. var l = 0;
  3045. for (var i = 1; i < path.length; i++) {
  3046. l += (path[i].subtract(path[i - 1])).length();
  3047. }
  3048. return l;
  3049. };
  3050. return Curve3;
  3051. })();
  3052. BABYLON.Curve3 = Curve3;
  3053. // Vertex formats
  3054. var PositionNormalVertex = (function () {
  3055. function PositionNormalVertex(position, normal) {
  3056. if (position === void 0) { position = Vector3.Zero(); }
  3057. if (normal === void 0) { normal = Vector3.Up(); }
  3058. this.position = position;
  3059. this.normal = normal;
  3060. }
  3061. PositionNormalVertex.prototype.clone = function () {
  3062. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3063. };
  3064. return PositionNormalVertex;
  3065. })();
  3066. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3067. var PositionNormalTextureVertex = (function () {
  3068. function PositionNormalTextureVertex(position, normal, uv) {
  3069. if (position === void 0) { position = Vector3.Zero(); }
  3070. if (normal === void 0) { normal = Vector3.Up(); }
  3071. if (uv === void 0) { uv = Vector2.Zero(); }
  3072. this.position = position;
  3073. this.normal = normal;
  3074. this.uv = uv;
  3075. }
  3076. PositionNormalTextureVertex.prototype.clone = function () {
  3077. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3078. };
  3079. return PositionNormalTextureVertex;
  3080. })();
  3081. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3082. // SIMD
  3083. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3084. var previousInvertToRef = Matrix.prototype.invertToRef;
  3085. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3086. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3087. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3088. var SIMDHelper = (function () {
  3089. function SIMDHelper() {
  3090. }
  3091. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3092. get: function () {
  3093. return SIMDHelper._isEnabled;
  3094. },
  3095. enumerable: true,
  3096. configurable: true
  3097. });
  3098. SIMDHelper.DisableSIMD = function () {
  3099. // Replace functions
  3100. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3101. Matrix.prototype.invertToRef = previousInvertToRef;
  3102. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3103. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3104. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3105. SIMDHelper._isEnabled = false;
  3106. };
  3107. SIMDHelper.EnableSIMD = function () {
  3108. if (window.SIMD === undefined) {
  3109. return;
  3110. }
  3111. // Replace functions
  3112. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3113. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3114. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3115. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3116. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3117. Object.defineProperty(Vector3.prototype, "x", {
  3118. get: function () { return this._data[0]; },
  3119. set: function (value) {
  3120. if (!this._data) {
  3121. this._data = new Float32Array(3);
  3122. }
  3123. this._data[0] = value;
  3124. }
  3125. });
  3126. Object.defineProperty(Vector3.prototype, "y", {
  3127. get: function () { return this._data[1]; },
  3128. set: function (value) {
  3129. this._data[1] = value;
  3130. }
  3131. });
  3132. Object.defineProperty(Vector3.prototype, "z", {
  3133. get: function () { return this._data[2]; },
  3134. set: function (value) {
  3135. this._data[2] = value;
  3136. }
  3137. });
  3138. SIMDHelper._isEnabled = true;
  3139. };
  3140. SIMDHelper._isEnabled = false;
  3141. return SIMDHelper;
  3142. })();
  3143. BABYLON.SIMDHelper = SIMDHelper;
  3144. })(BABYLON || (BABYLON = {}));
  3145. var BABYLON;
  3146. (function (BABYLON) {
  3147. var Database = (function () {
  3148. function Database(urlToScene, callbackManifestChecked) {
  3149. // Handling various flavors of prefixed version of IndexedDB
  3150. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3151. this.callbackManifestChecked = callbackManifestChecked;
  3152. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3153. this.db = null;
  3154. this.enableSceneOffline = false;
  3155. this.enableTexturesOffline = false;
  3156. this.manifestVersionFound = 0;
  3157. this.mustUpdateRessources = false;
  3158. this.hasReachedQuota = false;
  3159. if (!Database.IDBStorageEnabled) {
  3160. this.callbackManifestChecked(true);
  3161. }
  3162. else {
  3163. this.checkManifestFile();
  3164. }
  3165. }
  3166. Database.prototype.checkManifestFile = function () {
  3167. var _this = this;
  3168. function noManifestFile() {
  3169. that.enableSceneOffline = false;
  3170. that.enableTexturesOffline = false;
  3171. that.callbackManifestChecked(false);
  3172. }
  3173. var that = this;
  3174. var manifestURL = this.currentSceneUrl + ".manifest";
  3175. var xhr = new XMLHttpRequest();
  3176. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3177. xhr.open("GET", manifestURLTimeStamped, true);
  3178. xhr.addEventListener("load", function () {
  3179. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3180. try {
  3181. var manifestFile = JSON.parse(xhr.response);
  3182. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3183. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3184. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3185. _this.manifestVersionFound = manifestFile.version;
  3186. }
  3187. if (_this.callbackManifestChecked) {
  3188. _this.callbackManifestChecked(true);
  3189. }
  3190. }
  3191. catch (ex) {
  3192. noManifestFile();
  3193. }
  3194. }
  3195. else {
  3196. noManifestFile();
  3197. }
  3198. }, false);
  3199. xhr.addEventListener("error", function (event) {
  3200. noManifestFile();
  3201. }, false);
  3202. try {
  3203. xhr.send();
  3204. }
  3205. catch (ex) {
  3206. BABYLON.Tools.Error("Error on XHR send request.");
  3207. that.callbackManifestChecked(false);
  3208. }
  3209. };
  3210. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3211. var _this = this;
  3212. function handleError() {
  3213. that.isSupported = false;
  3214. if (errorCallback)
  3215. errorCallback();
  3216. }
  3217. var that = this;
  3218. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3219. // Your browser doesn't support IndexedDB
  3220. this.isSupported = false;
  3221. if (errorCallback)
  3222. errorCallback();
  3223. }
  3224. else {
  3225. // If the DB hasn't been opened or created yet
  3226. if (!this.db) {
  3227. this.hasReachedQuota = false;
  3228. this.isSupported = true;
  3229. var request = this.idbFactory.open("babylonjs", 1);
  3230. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3231. request.onerror = function (event) {
  3232. handleError();
  3233. };
  3234. // executes when a version change transaction cannot complete due to other active transactions
  3235. request.onblocked = function (event) {
  3236. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3237. handleError();
  3238. };
  3239. // DB has been opened successfully
  3240. request.onsuccess = function (event) {
  3241. _this.db = request.result;
  3242. successCallback();
  3243. };
  3244. // Initialization of the DB. Creating Scenes & Textures stores
  3245. request.onupgradeneeded = function (event) {
  3246. _this.db = (event.target).result;
  3247. try {
  3248. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3249. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3250. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3251. }
  3252. catch (ex) {
  3253. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3254. handleError();
  3255. }
  3256. };
  3257. }
  3258. else {
  3259. if (successCallback)
  3260. successCallback();
  3261. }
  3262. }
  3263. };
  3264. Database.prototype.loadImageFromDB = function (url, image) {
  3265. var _this = this;
  3266. var completeURL = Database.ReturnFullUrlLocation(url);
  3267. var saveAndLoadImage = function () {
  3268. if (!_this.hasReachedQuota && _this.db !== null) {
  3269. // the texture is not yet in the DB, let's try to save it
  3270. _this._saveImageIntoDBAsync(completeURL, image);
  3271. }
  3272. else {
  3273. image.src = url;
  3274. }
  3275. };
  3276. if (!this.mustUpdateRessources) {
  3277. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3278. }
  3279. else {
  3280. saveAndLoadImage();
  3281. }
  3282. };
  3283. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3284. if (this.isSupported && this.db !== null) {
  3285. var texture;
  3286. var transaction = this.db.transaction(["textures"]);
  3287. transaction.onabort = function (event) {
  3288. image.src = url;
  3289. };
  3290. transaction.oncomplete = function (event) {
  3291. var blobTextureURL;
  3292. if (texture) {
  3293. var URL = window.URL || window.webkitURL;
  3294. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3295. image.onerror = function () {
  3296. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3297. image.src = url;
  3298. };
  3299. image.src = blobTextureURL;
  3300. }
  3301. else {
  3302. notInDBCallback();
  3303. }
  3304. };
  3305. var getRequest = transaction.objectStore("textures").get(url);
  3306. getRequest.onsuccess = function (event) {
  3307. texture = (event.target).result;
  3308. };
  3309. getRequest.onerror = function (event) {
  3310. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3311. image.src = url;
  3312. };
  3313. }
  3314. else {
  3315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3316. image.src = url;
  3317. }
  3318. };
  3319. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3320. var _this = this;
  3321. if (this.isSupported) {
  3322. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3323. var generateBlobUrl = function () {
  3324. var blobTextureURL;
  3325. if (blob) {
  3326. var URL = window.URL || window.webkitURL;
  3327. try {
  3328. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3329. }
  3330. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3331. catch (ex) {
  3332. blobTextureURL = URL.createObjectURL(blob);
  3333. }
  3334. }
  3335. image.src = blobTextureURL;
  3336. };
  3337. if (Database.IsUASupportingBlobStorage) {
  3338. var xhr = new XMLHttpRequest(), blob;
  3339. xhr.open("GET", url, true);
  3340. xhr.responseType = "blob";
  3341. xhr.addEventListener("load", function () {
  3342. if (xhr.status === 200) {
  3343. // Blob as response (XHR2)
  3344. blob = xhr.response;
  3345. var transaction = _this.db.transaction(["textures"], "readwrite");
  3346. // the transaction could abort because of a QuotaExceededError error
  3347. transaction.onabort = function (event) {
  3348. try {
  3349. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3350. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3351. this.hasReachedQuota = true;
  3352. }
  3353. }
  3354. catch (ex) { }
  3355. generateBlobUrl();
  3356. };
  3357. transaction.oncomplete = function (event) {
  3358. generateBlobUrl();
  3359. };
  3360. var newTexture = { textureUrl: url, data: blob };
  3361. try {
  3362. // Put the blob into the dabase
  3363. var addRequest = transaction.objectStore("textures").put(newTexture);
  3364. addRequest.onsuccess = function (event) {
  3365. };
  3366. addRequest.onerror = function (event) {
  3367. generateBlobUrl();
  3368. };
  3369. }
  3370. catch (ex) {
  3371. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3372. if (ex.code === 25) {
  3373. Database.IsUASupportingBlobStorage = false;
  3374. }
  3375. image.src = url;
  3376. }
  3377. }
  3378. else {
  3379. image.src = url;
  3380. }
  3381. }, false);
  3382. xhr.addEventListener("error", function (event) {
  3383. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3384. image.src = url;
  3385. }, false);
  3386. xhr.send();
  3387. }
  3388. else {
  3389. image.src = url;
  3390. }
  3391. }
  3392. else {
  3393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3394. image.src = url;
  3395. }
  3396. };
  3397. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3398. var _this = this;
  3399. var updateVersion = function (event) {
  3400. // the version is not yet in the DB or we need to update it
  3401. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3402. };
  3403. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3404. };
  3405. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3406. var _this = this;
  3407. if (this.isSupported) {
  3408. var version;
  3409. try {
  3410. var transaction = this.db.transaction(["versions"]);
  3411. transaction.oncomplete = function (event) {
  3412. if (version) {
  3413. // If the version in the JSON file is > than the version in DB
  3414. if (_this.manifestVersionFound > version.data) {
  3415. _this.mustUpdateRessources = true;
  3416. updateInDBCallback();
  3417. }
  3418. else {
  3419. callback(version.data);
  3420. }
  3421. }
  3422. else {
  3423. _this.mustUpdateRessources = true;
  3424. updateInDBCallback();
  3425. }
  3426. };
  3427. transaction.onabort = function (event) {
  3428. callback(-1);
  3429. };
  3430. var getRequest = transaction.objectStore("versions").get(url);
  3431. getRequest.onsuccess = function (event) {
  3432. version = (event.target).result;
  3433. };
  3434. getRequest.onerror = function (event) {
  3435. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3436. callback(-1);
  3437. };
  3438. }
  3439. catch (ex) {
  3440. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3441. callback(-1);
  3442. }
  3443. }
  3444. else {
  3445. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3446. callback(-1);
  3447. }
  3448. };
  3449. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3450. var _this = this;
  3451. if (this.isSupported && !this.hasReachedQuota) {
  3452. try {
  3453. // Open a transaction to the database
  3454. var transaction = this.db.transaction(["versions"], "readwrite");
  3455. // the transaction could abort because of a QuotaExceededError error
  3456. transaction.onabort = function (event) {
  3457. try {
  3458. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3459. _this.hasReachedQuota = true;
  3460. }
  3461. }
  3462. catch (ex) { }
  3463. callback(-1);
  3464. };
  3465. transaction.oncomplete = function (event) {
  3466. callback(_this.manifestVersionFound);
  3467. };
  3468. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3469. // Put the scene into the database
  3470. var addRequest = transaction.objectStore("versions").put(newVersion);
  3471. addRequest.onsuccess = function (event) {
  3472. };
  3473. addRequest.onerror = function (event) {
  3474. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3475. };
  3476. }
  3477. catch (ex) {
  3478. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3479. callback(-1);
  3480. }
  3481. }
  3482. else {
  3483. callback(-1);
  3484. }
  3485. };
  3486. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3487. var _this = this;
  3488. var completeUrl = Database.ReturnFullUrlLocation(url);
  3489. var saveAndLoadFile = function (event) {
  3490. // the scene is not yet in the DB, let's try to save it
  3491. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3492. };
  3493. this._checkVersionFromDB(completeUrl, function (version) {
  3494. if (version !== -1) {
  3495. if (!_this.mustUpdateRessources) {
  3496. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3497. }
  3498. else {
  3499. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3500. }
  3501. }
  3502. else {
  3503. errorCallback();
  3504. }
  3505. });
  3506. };
  3507. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3508. if (this.isSupported) {
  3509. var targetStore;
  3510. if (url.indexOf(".babylon") !== -1) {
  3511. targetStore = "scenes";
  3512. }
  3513. else {
  3514. targetStore = "textures";
  3515. }
  3516. var file;
  3517. var transaction = this.db.transaction([targetStore]);
  3518. transaction.oncomplete = function (event) {
  3519. if (file) {
  3520. callback(file.data);
  3521. }
  3522. else {
  3523. notInDBCallback();
  3524. }
  3525. };
  3526. transaction.onabort = function (event) {
  3527. notInDBCallback();
  3528. };
  3529. var getRequest = transaction.objectStore(targetStore).get(url);
  3530. getRequest.onsuccess = function (event) {
  3531. file = (event.target).result;
  3532. };
  3533. getRequest.onerror = function (event) {
  3534. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3535. notInDBCallback();
  3536. };
  3537. }
  3538. else {
  3539. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3540. callback();
  3541. }
  3542. };
  3543. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3544. var _this = this;
  3545. if (this.isSupported) {
  3546. var targetStore;
  3547. if (url.indexOf(".babylon") !== -1) {
  3548. targetStore = "scenes";
  3549. }
  3550. else {
  3551. targetStore = "textures";
  3552. }
  3553. // Create XHR
  3554. var xhr = new XMLHttpRequest(), fileData;
  3555. xhr.open("GET", url, true);
  3556. if (useArrayBuffer) {
  3557. xhr.responseType = "arraybuffer";
  3558. }
  3559. xhr.onprogress = progressCallback;
  3560. xhr.addEventListener("load", function () {
  3561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3562. // Blob as response (XHR2)
  3563. //fileData = xhr.responseText;
  3564. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3565. if (!_this.hasReachedQuota) {
  3566. // Open a transaction to the database
  3567. var transaction = _this.db.transaction([targetStore], "readwrite");
  3568. // the transaction could abort because of a QuotaExceededError error
  3569. transaction.onabort = function (event) {
  3570. try {
  3571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3572. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3573. this.hasReachedQuota = true;
  3574. }
  3575. }
  3576. catch (ex) { }
  3577. callback(fileData);
  3578. };
  3579. transaction.oncomplete = function (event) {
  3580. callback(fileData);
  3581. };
  3582. var newFile;
  3583. if (targetStore === "scenes") {
  3584. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3585. }
  3586. else {
  3587. newFile = { textureUrl: url, data: fileData };
  3588. }
  3589. try {
  3590. // Put the scene into the database
  3591. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3592. addRequest.onsuccess = function (event) {
  3593. };
  3594. addRequest.onerror = function (event) {
  3595. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3596. };
  3597. }
  3598. catch (ex) {
  3599. callback(fileData);
  3600. }
  3601. }
  3602. else {
  3603. callback(fileData);
  3604. }
  3605. }
  3606. else {
  3607. callback();
  3608. }
  3609. }, false);
  3610. xhr.addEventListener("error", function (event) {
  3611. BABYLON.Tools.Error("error on XHR request.");
  3612. callback();
  3613. }, false);
  3614. xhr.send();
  3615. }
  3616. else {
  3617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3618. callback();
  3619. }
  3620. };
  3621. Database.IsUASupportingBlobStorage = true;
  3622. Database.IDBStorageEnabled = true;
  3623. Database.parseURL = function (url) {
  3624. var a = document.createElement('a');
  3625. a.href = url;
  3626. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3627. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3628. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3629. return absLocation;
  3630. };
  3631. Database.ReturnFullUrlLocation = function (url) {
  3632. if (url.indexOf("http:/") === -1) {
  3633. return (Database.parseURL(window.location.href) + url);
  3634. }
  3635. else {
  3636. return url;
  3637. }
  3638. };
  3639. return Database;
  3640. })();
  3641. BABYLON.Database = Database;
  3642. })(BABYLON || (BABYLON = {}));
  3643. var BABYLON;
  3644. (function (BABYLON) {
  3645. var Internals;
  3646. (function (Internals) {
  3647. /*
  3648. * Based on jsTGALoader - Javascript loader for TGA file
  3649. * By Vincent Thibault
  3650. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3651. */
  3652. var TGATools = (function () {
  3653. function TGATools() {
  3654. }
  3655. TGATools.GetTGAHeader = function (data) {
  3656. var offset = 0;
  3657. var header = {
  3658. id_length: data[offset++],
  3659. colormap_type: data[offset++],
  3660. image_type: data[offset++],
  3661. colormap_index: data[offset++] | data[offset++] << 8,
  3662. colormap_length: data[offset++] | data[offset++] << 8,
  3663. colormap_size: data[offset++],
  3664. origin: [
  3665. data[offset++] | data[offset++] << 8,
  3666. data[offset++] | data[offset++] << 8
  3667. ],
  3668. width: data[offset++] | data[offset++] << 8,
  3669. height: data[offset++] | data[offset++] << 8,
  3670. pixel_size: data[offset++],
  3671. flags: data[offset++]
  3672. };
  3673. return header;
  3674. };
  3675. TGATools.UploadContent = function (gl, data) {
  3676. // Not enough data to contain header ?
  3677. if (data.length < 19) {
  3678. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3679. return;
  3680. }
  3681. // Read Header
  3682. var offset = 18;
  3683. var header = TGATools.GetTGAHeader(data);
  3684. // Assume it's a valid Targa file.
  3685. if (header.id_length + offset > data.length) {
  3686. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3687. return;
  3688. }
  3689. // Skip not needed data
  3690. offset += header.id_length;
  3691. var use_rle = false;
  3692. var use_pal = false;
  3693. var use_rgb = false;
  3694. var use_grey = false;
  3695. // Get some informations.
  3696. switch (header.image_type) {
  3697. case TGATools._TYPE_RLE_INDEXED:
  3698. use_rle = true;
  3699. case TGATools._TYPE_INDEXED:
  3700. use_pal = true;
  3701. break;
  3702. case TGATools._TYPE_RLE_RGB:
  3703. use_rle = true;
  3704. case TGATools._TYPE_RGB:
  3705. use_rgb = true;
  3706. break;
  3707. case TGATools._TYPE_RLE_GREY:
  3708. use_rle = true;
  3709. case TGATools._TYPE_GREY:
  3710. use_grey = true;
  3711. break;
  3712. }
  3713. var pixel_data;
  3714. var numAlphaBits = header.flags & 0xf;
  3715. var pixel_size = header.pixel_size >> 3;
  3716. var pixel_total = header.width * header.height * pixel_size;
  3717. // Read palettes
  3718. var palettes;
  3719. if (use_pal) {
  3720. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3721. }
  3722. // Read LRE
  3723. if (use_rle) {
  3724. pixel_data = new Uint8Array(pixel_total);
  3725. var c, count, i;
  3726. var localOffset = 0;
  3727. var pixels = new Uint8Array(pixel_size);
  3728. while (offset < pixel_total && localOffset < pixel_total) {
  3729. c = data[offset++];
  3730. count = (c & 0x7f) + 1;
  3731. // RLE pixels
  3732. if (c & 0x80) {
  3733. // Bind pixel tmp array
  3734. for (i = 0; i < pixel_size; ++i) {
  3735. pixels[i] = data[offset++];
  3736. }
  3737. // Copy pixel array
  3738. for (i = 0; i < count; ++i) {
  3739. pixel_data.set(pixels, localOffset + i * pixel_size);
  3740. }
  3741. localOffset += pixel_size * count;
  3742. }
  3743. else {
  3744. count *= pixel_size;
  3745. for (i = 0; i < count; ++i) {
  3746. pixel_data[localOffset + i] = data[offset++];
  3747. }
  3748. localOffset += count;
  3749. }
  3750. }
  3751. }
  3752. else {
  3753. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3754. }
  3755. // Load to texture
  3756. var x_start, y_start, x_step, y_step, y_end, x_end;
  3757. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3758. default:
  3759. case TGATools._ORIGIN_UL:
  3760. x_start = 0;
  3761. x_step = 1;
  3762. x_end = header.width;
  3763. y_start = 0;
  3764. y_step = 1;
  3765. y_end = header.height;
  3766. break;
  3767. case TGATools._ORIGIN_BL:
  3768. x_start = 0;
  3769. x_step = 1;
  3770. x_end = header.width;
  3771. y_start = header.height - 1;
  3772. y_step = -1;
  3773. y_end = -1;
  3774. break;
  3775. case TGATools._ORIGIN_UR:
  3776. x_start = header.width - 1;
  3777. x_step = -1;
  3778. x_end = -1;
  3779. y_start = 0;
  3780. y_step = 1;
  3781. y_end = header.height;
  3782. break;
  3783. case TGATools._ORIGIN_BR:
  3784. x_start = header.width - 1;
  3785. x_step = -1;
  3786. x_end = -1;
  3787. y_start = header.height - 1;
  3788. y_step = -1;
  3789. y_end = -1;
  3790. break;
  3791. }
  3792. // Load the specify method
  3793. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3794. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3795. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3796. };
  3797. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3798. var image = pixel_data, colormap = palettes;
  3799. var width = header.width, height = header.height;
  3800. var color, i = 0, x, y;
  3801. var imageData = new Uint8Array(width * height * 4);
  3802. for (y = y_start; y !== y_end; y += y_step) {
  3803. for (x = x_start; x !== x_end; x += x_step, i++) {
  3804. color = image[i];
  3805. imageData[(x + width * y) * 4 + 3] = 255;
  3806. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3807. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3808. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3809. }
  3810. }
  3811. return imageData;
  3812. };
  3813. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3814. var image = pixel_data;
  3815. var width = header.width, height = header.height;
  3816. var color, i = 0, x, y;
  3817. var imageData = new Uint8Array(width * height * 4);
  3818. for (y = y_start; y !== y_end; y += y_step) {
  3819. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3820. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3821. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3822. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3823. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3824. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3825. }
  3826. }
  3827. return imageData;
  3828. };
  3829. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3830. var image = pixel_data;
  3831. var width = header.width, height = header.height;
  3832. var i = 0, x, y;
  3833. var imageData = new Uint8Array(width * height * 4);
  3834. for (y = y_start; y !== y_end; y += y_step) {
  3835. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3836. imageData[(x + width * y) * 4 + 3] = 255;
  3837. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3838. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3839. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3840. }
  3841. }
  3842. return imageData;
  3843. };
  3844. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3845. var image = pixel_data;
  3846. var width = header.width, height = header.height;
  3847. var i = 0, x, y;
  3848. var imageData = new Uint8Array(width * height * 4);
  3849. for (y = y_start; y !== y_end; y += y_step) {
  3850. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3851. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3852. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3853. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3854. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3855. }
  3856. }
  3857. return imageData;
  3858. };
  3859. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3860. var image = pixel_data;
  3861. var width = header.width, height = header.height;
  3862. var color, i = 0, x, y;
  3863. var imageData = new Uint8Array(width * height * 4);
  3864. for (y = y_start; y !== y_end; y += y_step) {
  3865. for (x = x_start; x !== x_end; x += x_step, i++) {
  3866. color = image[i];
  3867. imageData[(x + width * y) * 4 + 0] = color;
  3868. imageData[(x + width * y) * 4 + 1] = color;
  3869. imageData[(x + width * y) * 4 + 2] = color;
  3870. imageData[(x + width * y) * 4 + 3] = 255;
  3871. }
  3872. }
  3873. return imageData;
  3874. };
  3875. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3876. var image = pixel_data;
  3877. var width = header.width, height = header.height;
  3878. var i = 0, x, y;
  3879. var imageData = new Uint8Array(width * height * 4);
  3880. for (y = y_start; y !== y_end; y += y_step) {
  3881. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3882. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3883. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3884. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3885. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3886. }
  3887. }
  3888. return imageData;
  3889. };
  3890. TGATools._TYPE_NO_DATA = 0;
  3891. TGATools._TYPE_INDEXED = 1;
  3892. TGATools._TYPE_RGB = 2;
  3893. TGATools._TYPE_GREY = 3;
  3894. TGATools._TYPE_RLE_INDEXED = 9;
  3895. TGATools._TYPE_RLE_RGB = 10;
  3896. TGATools._TYPE_RLE_GREY = 11;
  3897. TGATools._ORIGIN_MASK = 0x30;
  3898. TGATools._ORIGIN_SHIFT = 0x04;
  3899. TGATools._ORIGIN_BL = 0x00;
  3900. TGATools._ORIGIN_BR = 0x01;
  3901. TGATools._ORIGIN_UL = 0x02;
  3902. TGATools._ORIGIN_UR = 0x03;
  3903. return TGATools;
  3904. })();
  3905. Internals.TGATools = TGATools;
  3906. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3907. })(BABYLON || (BABYLON = {}));
  3908. var BABYLON;
  3909. (function (BABYLON) {
  3910. var Internals;
  3911. (function (Internals) {
  3912. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3913. // All values and structures referenced from:
  3914. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3915. var DDS_MAGIC = 0x20534444;
  3916. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  3917. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3918. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  3919. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3920. function FourCCToInt32(value) {
  3921. return value.charCodeAt(0) +
  3922. (value.charCodeAt(1) << 8) +
  3923. (value.charCodeAt(2) << 16) +
  3924. (value.charCodeAt(3) << 24);
  3925. }
  3926. function Int32ToFourCC(value) {
  3927. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3928. }
  3929. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3930. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3931. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3932. var headerLengthInt = 31; // The header length in 32 bit ints
  3933. // Offsets into the header array
  3934. var off_magic = 0;
  3935. var off_size = 1;
  3936. var off_flags = 2;
  3937. var off_height = 3;
  3938. var off_width = 4;
  3939. var off_mipmapCount = 7;
  3940. var off_pfFlags = 20;
  3941. var off_pfFourCC = 21;
  3942. var off_RGBbpp = 22;
  3943. var off_RMask = 23;
  3944. var off_GMask = 24;
  3945. var off_BMask = 25;
  3946. var off_AMask = 26;
  3947. var off_caps1 = 27;
  3948. var off_caps2 = 28;
  3949. ;
  3950. var DDSTools = (function () {
  3951. function DDSTools() {
  3952. }
  3953. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3954. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3955. var mipmapCount = 1;
  3956. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3957. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3958. }
  3959. return {
  3960. width: header[off_width],
  3961. height: header[off_height],
  3962. mipmapCount: mipmapCount,
  3963. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3964. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3965. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3966. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3967. };
  3968. };
  3969. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3970. var byteArray = new Uint8Array(dataLength);
  3971. var srcData = new Uint8Array(arrayBuffer);
  3972. var index = 0;
  3973. for (var y = height - 1; y >= 0; y--) {
  3974. for (var x = 0; x < width; x++) {
  3975. var srcPos = dataOffset + (x + y * width) * 4;
  3976. byteArray[index + 2] = srcData[srcPos];
  3977. byteArray[index + 1] = srcData[srcPos + 1];
  3978. byteArray[index] = srcData[srcPos + 2];
  3979. byteArray[index + 3] = srcData[srcPos + 3];
  3980. index += 4;
  3981. }
  3982. }
  3983. return byteArray;
  3984. };
  3985. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3986. var byteArray = new Uint8Array(dataLength);
  3987. var srcData = new Uint8Array(arrayBuffer);
  3988. var index = 0;
  3989. for (var y = height - 1; y >= 0; y--) {
  3990. for (var x = 0; x < width; x++) {
  3991. var srcPos = dataOffset + (x + y * width) * 3;
  3992. byteArray[index + 2] = srcData[srcPos];
  3993. byteArray[index + 1] = srcData[srcPos + 1];
  3994. byteArray[index] = srcData[srcPos + 2];
  3995. index += 3;
  3996. }
  3997. }
  3998. return byteArray;
  3999. };
  4000. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  4001. var byteArray = new Uint8Array(dataLength);
  4002. var srcData = new Uint8Array(arrayBuffer);
  4003. var index = 0;
  4004. for (var y = height - 1; y >= 0; y--) {
  4005. for (var x = 0; x < width; x++) {
  4006. var srcPos = dataOffset + (x + y * width);
  4007. byteArray[index] = srcData[srcPos];
  4008. index++;
  4009. }
  4010. }
  4011. return byteArray;
  4012. };
  4013. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4014. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4015. if (header[off_magic] != DDS_MAGIC) {
  4016. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4017. return;
  4018. }
  4019. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4020. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4021. return;
  4022. }
  4023. if (info.isFourCC) {
  4024. fourCC = header[off_pfFourCC];
  4025. switch (fourCC) {
  4026. case FOURCC_DXT1:
  4027. blockBytes = 8;
  4028. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4029. break;
  4030. case FOURCC_DXT3:
  4031. blockBytes = 16;
  4032. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4033. break;
  4034. case FOURCC_DXT5:
  4035. blockBytes = 16;
  4036. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4037. break;
  4038. default:
  4039. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4040. return;
  4041. }
  4042. }
  4043. mipmapCount = 1;
  4044. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4045. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4046. }
  4047. var bpp = header[off_RGBbpp];
  4048. for (var face = 0; face < faces; face++) {
  4049. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4050. width = header[off_width];
  4051. height = header[off_height];
  4052. dataOffset = header[off_size] + 4;
  4053. for (i = 0; i < mipmapCount; ++i) {
  4054. if (info.isRGB) {
  4055. if (bpp == 24) {
  4056. dataLength = width * height * 3;
  4057. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4058. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4059. }
  4060. else {
  4061. dataLength = width * height * 4;
  4062. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4063. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4064. }
  4065. }
  4066. else if (info.isLuminance) {
  4067. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4068. var unpaddedRowSize = width;
  4069. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4070. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4071. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4072. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4073. }
  4074. else {
  4075. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4076. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4077. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4078. }
  4079. dataOffset += dataLength;
  4080. width *= 0.5;
  4081. height *= 0.5;
  4082. width = Math.max(1.0, width);
  4083. height = Math.max(1.0, height);
  4084. }
  4085. }
  4086. };
  4087. return DDSTools;
  4088. })();
  4089. Internals.DDSTools = DDSTools;
  4090. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4091. })(BABYLON || (BABYLON = {}));
  4092. var BABYLON;
  4093. (function (BABYLON) {
  4094. var SmartArray = (function () {
  4095. function SmartArray(capacity) {
  4096. this.length = 0;
  4097. this._duplicateId = 0;
  4098. this.data = new Array(capacity);
  4099. this._id = SmartArray._GlobalId++;
  4100. }
  4101. SmartArray.prototype.push = function (value) {
  4102. this.data[this.length++] = value;
  4103. if (this.length > this.data.length) {
  4104. this.data.length *= 2;
  4105. }
  4106. if (!value.__smartArrayFlags) {
  4107. value.__smartArrayFlags = {};
  4108. }
  4109. value.__smartArrayFlags[this._id] = this._duplicateId;
  4110. };
  4111. SmartArray.prototype.pushNoDuplicate = function (value) {
  4112. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4113. return;
  4114. }
  4115. this.push(value);
  4116. };
  4117. SmartArray.prototype.sort = function (compareFn) {
  4118. this.data.sort(compareFn);
  4119. };
  4120. SmartArray.prototype.reset = function () {
  4121. this.length = 0;
  4122. this._duplicateId++;
  4123. };
  4124. SmartArray.prototype.concat = function (array) {
  4125. if (array.length === 0) {
  4126. return;
  4127. }
  4128. if (this.length + array.length > this.data.length) {
  4129. this.data.length = (this.length + array.length) * 2;
  4130. }
  4131. for (var index = 0; index < array.length; index++) {
  4132. this.data[this.length++] = (array.data || array)[index];
  4133. }
  4134. };
  4135. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4136. if (array.length === 0) {
  4137. return;
  4138. }
  4139. if (this.length + array.length > this.data.length) {
  4140. this.data.length = (this.length + array.length) * 2;
  4141. }
  4142. for (var index = 0; index < array.length; index++) {
  4143. var item = (array.data || array)[index];
  4144. this.pushNoDuplicate(item);
  4145. }
  4146. };
  4147. SmartArray.prototype.indexOf = function (value) {
  4148. var position = this.data.indexOf(value);
  4149. if (position >= this.length) {
  4150. return -1;
  4151. }
  4152. return position;
  4153. };
  4154. // Statics
  4155. SmartArray._GlobalId = 0;
  4156. return SmartArray;
  4157. })();
  4158. BABYLON.SmartArray = SmartArray;
  4159. })(BABYLON || (BABYLON = {}));
  4160. var BABYLON;
  4161. (function (BABYLON) {
  4162. var SmartCollection = (function () {
  4163. function SmartCollection(capacity) {
  4164. if (capacity === void 0) { capacity = 10; }
  4165. this.count = 0;
  4166. this._initialCapacity = capacity;
  4167. this.items = {};
  4168. this._keys = new Array(this._initialCapacity);
  4169. }
  4170. SmartCollection.prototype.add = function (key, item) {
  4171. if (this.items[key] != undefined) {
  4172. return -1;
  4173. }
  4174. this.items[key] = item;
  4175. //literal keys are always strings, but we keep source type of key in _keys array
  4176. this._keys[this.count++] = key;
  4177. if (this.count > this._keys.length) {
  4178. this._keys.length *= 2;
  4179. }
  4180. return this.count;
  4181. };
  4182. SmartCollection.prototype.remove = function (key) {
  4183. if (this.items[key] == undefined) {
  4184. return -1;
  4185. }
  4186. return this.removeItemOfIndex(this.indexOf(key));
  4187. };
  4188. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4189. if (index < this.count && index > -1) {
  4190. delete this.items[this._keys[index]];
  4191. //here, shifting by hand is better optimised than .splice
  4192. while (index < this.count) {
  4193. this._keys[index] = this._keys[index + 1];
  4194. index++;
  4195. }
  4196. }
  4197. else {
  4198. return -1;
  4199. }
  4200. return --this.count;
  4201. };
  4202. SmartCollection.prototype.indexOf = function (key) {
  4203. for (var i = 0; i !== this.count; i++) {
  4204. if (this._keys[i] === key) {
  4205. return i;
  4206. }
  4207. }
  4208. return -1;
  4209. };
  4210. SmartCollection.prototype.item = function (key) {
  4211. return this.items[key];
  4212. };
  4213. SmartCollection.prototype.getAllKeys = function () {
  4214. if (this.count > 0) {
  4215. var keys = new Array(this.count);
  4216. for (var i = 0; i < this.count; i++) {
  4217. keys[i] = this._keys[i];
  4218. }
  4219. return keys;
  4220. }
  4221. else {
  4222. return undefined;
  4223. }
  4224. };
  4225. SmartCollection.prototype.getKeyByIndex = function (index) {
  4226. if (index < this.count && index > -1) {
  4227. return this._keys[index];
  4228. }
  4229. else {
  4230. return undefined;
  4231. }
  4232. };
  4233. SmartCollection.prototype.getItemByIndex = function (index) {
  4234. if (index < this.count && index > -1) {
  4235. return this.items[this._keys[index]];
  4236. }
  4237. else {
  4238. return undefined;
  4239. }
  4240. };
  4241. SmartCollection.prototype.empty = function () {
  4242. if (this.count > 0) {
  4243. this.count = 0;
  4244. this.items = {};
  4245. this._keys = new Array(this._initialCapacity);
  4246. }
  4247. };
  4248. SmartCollection.prototype.forEach = function (block) {
  4249. var key;
  4250. for (key in this.items) {
  4251. if (this.items.hasOwnProperty(key)) {
  4252. block(this.items[key]);
  4253. }
  4254. }
  4255. };
  4256. return SmartCollection;
  4257. })();
  4258. BABYLON.SmartCollection = SmartCollection;
  4259. })(BABYLON || (BABYLON = {}));
  4260. var BABYLON;
  4261. (function (BABYLON) {
  4262. // Screenshots
  4263. var screenshotCanvas;
  4264. var cloneValue = function (source, destinationObject) {
  4265. if (!source)
  4266. return null;
  4267. if (source instanceof BABYLON.Mesh) {
  4268. return null;
  4269. }
  4270. if (source instanceof BABYLON.SubMesh) {
  4271. return source.clone(destinationObject);
  4272. }
  4273. else if (source.clone) {
  4274. return source.clone();
  4275. }
  4276. return null;
  4277. };
  4278. var Tools = (function () {
  4279. function Tools() {
  4280. }
  4281. Tools.ToHex = function (i) {
  4282. var str = i.toString(16);
  4283. if (i <= 15) {
  4284. return ("0" + str).toUpperCase();
  4285. }
  4286. return str.toUpperCase();
  4287. };
  4288. Tools.SetImmediate = function (action) {
  4289. if (window.setImmediate) {
  4290. window.setImmediate(action);
  4291. }
  4292. else {
  4293. setTimeout(action, 1);
  4294. }
  4295. };
  4296. Tools.IsExponantOfTwo = function (value) {
  4297. var count = 1;
  4298. do {
  4299. count *= 2;
  4300. } while (count < value);
  4301. return count === value;
  4302. };
  4303. Tools.GetExponantOfTwo = function (value, max) {
  4304. var count = 1;
  4305. do {
  4306. count *= 2;
  4307. } while (count < value);
  4308. if (count > max)
  4309. count = max;
  4310. return count;
  4311. };
  4312. Tools.GetFilename = function (path) {
  4313. var index = path.lastIndexOf("/");
  4314. if (index < 0)
  4315. return path;
  4316. return path.substring(index + 1);
  4317. };
  4318. Tools.GetDOMTextContent = function (element) {
  4319. var result = "";
  4320. var child = element.firstChild;
  4321. while (child) {
  4322. if (child.nodeType === 3) {
  4323. result += child.textContent;
  4324. }
  4325. child = child.nextSibling;
  4326. }
  4327. return result;
  4328. };
  4329. Tools.ToDegrees = function (angle) {
  4330. return angle * 180 / Math.PI;
  4331. };
  4332. Tools.ToRadians = function (angle) {
  4333. return angle * Math.PI / 180;
  4334. };
  4335. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4336. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4337. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4338. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4339. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4340. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4341. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4342. }
  4343. return {
  4344. minimum: minimum,
  4345. maximum: maximum
  4346. };
  4347. };
  4348. Tools.ExtractMinAndMax = function (positions, start, count) {
  4349. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4350. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4351. for (var index = start; index < start + count; index++) {
  4352. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4353. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4354. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4355. }
  4356. return {
  4357. minimum: minimum,
  4358. maximum: maximum
  4359. };
  4360. };
  4361. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4362. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4363. return undefined;
  4364. return Array.isArray(obj) ? obj : [obj];
  4365. };
  4366. // Misc.
  4367. Tools.GetPointerPrefix = function () {
  4368. var eventPrefix = "pointer";
  4369. // Check if hand.js is referenced or if the browser natively supports pointer events
  4370. if (!navigator.pointerEnabled) {
  4371. eventPrefix = "mouse";
  4372. }
  4373. return eventPrefix;
  4374. };
  4375. Tools.QueueNewFrame = function (func) {
  4376. if (window.requestAnimationFrame)
  4377. window.requestAnimationFrame(func);
  4378. else if (window.msRequestAnimationFrame)
  4379. window.msRequestAnimationFrame(func);
  4380. else if (window.webkitRequestAnimationFrame)
  4381. window.webkitRequestAnimationFrame(func);
  4382. else if (window.mozRequestAnimationFrame)
  4383. window.mozRequestAnimationFrame(func);
  4384. else if (window.oRequestAnimationFrame)
  4385. window.oRequestAnimationFrame(func);
  4386. else {
  4387. window.setTimeout(func, 16);
  4388. }
  4389. };
  4390. Tools.RequestFullscreen = function (element) {
  4391. if (element.requestFullscreen)
  4392. element.requestFullscreen();
  4393. else if (element.msRequestFullscreen)
  4394. element.msRequestFullscreen();
  4395. else if (element.webkitRequestFullscreen)
  4396. element.webkitRequestFullscreen();
  4397. else if (element.mozRequestFullScreen)
  4398. element.mozRequestFullScreen();
  4399. };
  4400. Tools.ExitFullscreen = function () {
  4401. if (document.exitFullscreen) {
  4402. document.exitFullscreen();
  4403. }
  4404. else if (document.mozCancelFullScreen) {
  4405. document.mozCancelFullScreen();
  4406. }
  4407. else if (document.webkitCancelFullScreen) {
  4408. document.webkitCancelFullScreen();
  4409. }
  4410. else if (document.msCancelFullScreen) {
  4411. document.msCancelFullScreen();
  4412. }
  4413. };
  4414. // External files
  4415. Tools.CleanUrl = function (url) {
  4416. url = url.replace(/#/mg, "%23");
  4417. return url;
  4418. };
  4419. Tools.LoadImage = function (url, onload, onerror, database) {
  4420. url = Tools.CleanUrl(url);
  4421. var img = new Image();
  4422. if (url.substr(0, 5) !== "data:")
  4423. img.crossOrigin = 'anonymous';
  4424. img.onload = function () {
  4425. onload(img);
  4426. };
  4427. img.onerror = function (err) {
  4428. Tools.Error("Error while trying to load texture: " + url);
  4429. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4430. onload(img);
  4431. };
  4432. var noIndexedDB = function () {
  4433. img.src = url;
  4434. };
  4435. var loadFromIndexedDB = function () {
  4436. database.loadImageFromDB(url, img);
  4437. };
  4438. //ANY database to do!
  4439. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4440. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4441. }
  4442. else {
  4443. if (url.indexOf("file:") === -1) {
  4444. noIndexedDB();
  4445. }
  4446. else {
  4447. try {
  4448. var textureName = url.substring(5);
  4449. var blobURL;
  4450. try {
  4451. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4452. }
  4453. catch (ex) {
  4454. // Chrome doesn't support oneTimeOnly parameter
  4455. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4456. }
  4457. img.src = blobURL;
  4458. }
  4459. catch (e) {
  4460. img.src = null;
  4461. }
  4462. }
  4463. }
  4464. return img;
  4465. };
  4466. //ANY
  4467. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4468. url = Tools.CleanUrl(url);
  4469. var noIndexedDB = function () {
  4470. var request = new XMLHttpRequest();
  4471. var loadUrl = Tools.BaseUrl + url;
  4472. request.open('GET', loadUrl, true);
  4473. if (useArrayBuffer) {
  4474. request.responseType = "arraybuffer";
  4475. }
  4476. request.onprogress = progressCallBack;
  4477. request.onreadystatechange = function () {
  4478. if (request.readyState === 4) {
  4479. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4480. callback(!useArrayBuffer ? request.responseText : request.response);
  4481. }
  4482. else {
  4483. if (onError) {
  4484. onError();
  4485. }
  4486. else {
  4487. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4488. }
  4489. }
  4490. }
  4491. };
  4492. request.send(null);
  4493. };
  4494. var loadFromIndexedDB = function () {
  4495. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4496. };
  4497. if (url.indexOf("file:") !== -1) {
  4498. var fileName = url.substring(5);
  4499. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4500. }
  4501. else {
  4502. // Caching all files
  4503. if (database && database.enableSceneOffline) {
  4504. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4505. }
  4506. else {
  4507. noIndexedDB();
  4508. }
  4509. }
  4510. };
  4511. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4512. var reader = new FileReader();
  4513. reader.onload = function (e) {
  4514. //target doesn't have result from ts 1.3
  4515. callback(e.target['result']);
  4516. };
  4517. reader.onprogress = progressCallback;
  4518. reader.readAsDataURL(fileToLoad);
  4519. };
  4520. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4521. var reader = new FileReader();
  4522. reader.onerror = function (e) {
  4523. Tools.Log("Error while reading file: " + fileToLoad.name);
  4524. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4525. };
  4526. reader.onload = function (e) {
  4527. //target doesn't have result from ts 1.3
  4528. callback(e.target['result']);
  4529. };
  4530. reader.onprogress = progressCallBack;
  4531. if (!useArrayBuffer) {
  4532. // Asynchronous read
  4533. reader.readAsText(fileToLoad);
  4534. }
  4535. else {
  4536. reader.readAsArrayBuffer(fileToLoad);
  4537. }
  4538. };
  4539. // Misc.
  4540. Tools.Clamp = function (value, min, max) {
  4541. if (min === void 0) { min = 0; }
  4542. if (max === void 0) { max = 1; }
  4543. return Math.min(max, Math.max(min, value));
  4544. };
  4545. // Returns -1 when value is a negative number and
  4546. // +1 when value is a positive number.
  4547. Tools.Sign = function (value) {
  4548. value = +value; // convert to a number
  4549. if (value === 0 || isNaN(value))
  4550. return value;
  4551. return value > 0 ? 1 : -1;
  4552. };
  4553. Tools.Format = function (value, decimals) {
  4554. if (decimals === void 0) { decimals = 2; }
  4555. return value.toFixed(decimals);
  4556. };
  4557. Tools.CheckExtends = function (v, min, max) {
  4558. if (v.x < min.x)
  4559. min.x = v.x;
  4560. if (v.y < min.y)
  4561. min.y = v.y;
  4562. if (v.z < min.z)
  4563. min.z = v.z;
  4564. if (v.x > max.x)
  4565. max.x = v.x;
  4566. if (v.y > max.y)
  4567. max.y = v.y;
  4568. if (v.z > max.z)
  4569. max.z = v.z;
  4570. };
  4571. Tools.WithinEpsilon = function (a, b, epsilon) {
  4572. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4573. var num = a - b;
  4574. return -epsilon <= num && num <= epsilon;
  4575. };
  4576. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4577. for (var prop in source) {
  4578. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4579. continue;
  4580. }
  4581. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4582. continue;
  4583. }
  4584. var sourceValue = source[prop];
  4585. var typeOfSourceValue = typeof sourceValue;
  4586. if (typeOfSourceValue === "function") {
  4587. continue;
  4588. }
  4589. if (typeOfSourceValue === "object") {
  4590. if (sourceValue instanceof Array) {
  4591. destination[prop] = [];
  4592. if (sourceValue.length > 0) {
  4593. if (typeof sourceValue[0] == "object") {
  4594. for (var index = 0; index < sourceValue.length; index++) {
  4595. var clonedValue = cloneValue(sourceValue[index], destination);
  4596. if (destination[prop].indexOf(clonedValue) === -1) {
  4597. destination[prop].push(clonedValue);
  4598. }
  4599. }
  4600. }
  4601. else {
  4602. destination[prop] = sourceValue.slice(0);
  4603. }
  4604. }
  4605. }
  4606. else {
  4607. destination[prop] = cloneValue(sourceValue, destination);
  4608. }
  4609. }
  4610. else {
  4611. destination[prop] = sourceValue;
  4612. }
  4613. }
  4614. };
  4615. Tools.IsEmpty = function (obj) {
  4616. for (var i in obj) {
  4617. return false;
  4618. }
  4619. return true;
  4620. };
  4621. Tools.RegisterTopRootEvents = function (events) {
  4622. for (var index = 0; index < events.length; index++) {
  4623. var event = events[index];
  4624. window.addEventListener(event.name, event.handler, false);
  4625. try {
  4626. if (window.parent) {
  4627. window.parent.addEventListener(event.name, event.handler, false);
  4628. }
  4629. }
  4630. catch (e) {
  4631. }
  4632. }
  4633. };
  4634. Tools.UnregisterTopRootEvents = function (events) {
  4635. for (var index = 0; index < events.length; index++) {
  4636. var event = events[index];
  4637. window.removeEventListener(event.name, event.handler);
  4638. try {
  4639. if (window.parent) {
  4640. window.parent.removeEventListener(event.name, event.handler);
  4641. }
  4642. }
  4643. catch (e) {
  4644. }
  4645. }
  4646. };
  4647. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4648. // Read the contents of the framebuffer
  4649. var numberOfChannelsByLine = width * 4;
  4650. var halfHeight = height / 2;
  4651. //Reading datas from WebGL
  4652. var data = engine.readPixels(0, 0, width, height);
  4653. //To flip image on Y axis.
  4654. for (var i = 0; i < halfHeight; i++) {
  4655. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4656. var currentCell = j + i * numberOfChannelsByLine;
  4657. var targetLine = height - i - 1;
  4658. var targetCell = j + targetLine * numberOfChannelsByLine;
  4659. var temp = data[currentCell];
  4660. data[currentCell] = data[targetCell];
  4661. data[targetCell] = temp;
  4662. }
  4663. }
  4664. // Create a 2D canvas to store the result
  4665. if (!screenshotCanvas) {
  4666. screenshotCanvas = document.createElement('canvas');
  4667. }
  4668. screenshotCanvas.width = width;
  4669. screenshotCanvas.height = height;
  4670. var context = screenshotCanvas.getContext('2d');
  4671. // Copy the pixels to a 2D canvas
  4672. var imageData = context.createImageData(width, height);
  4673. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4674. var castData = imageData.data;
  4675. castData.set(data);
  4676. context.putImageData(imageData, 0, 0);
  4677. var base64Image = screenshotCanvas.toDataURL();
  4678. if (successCallback) {
  4679. successCallback(base64Image);
  4680. }
  4681. else {
  4682. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4683. if (("download" in document.createElement("a"))) {
  4684. var a = window.document.createElement("a");
  4685. a.href = base64Image;
  4686. var date = new Date();
  4687. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4688. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4689. window.document.body.appendChild(a);
  4690. a.addEventListener("click", function () {
  4691. a.parentElement.removeChild(a);
  4692. });
  4693. a.click();
  4694. }
  4695. else {
  4696. var newWindow = window.open("");
  4697. var img = newWindow.document.createElement("img");
  4698. img.src = base64Image;
  4699. newWindow.document.body.appendChild(img);
  4700. }
  4701. }
  4702. };
  4703. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4704. var width;
  4705. var height;
  4706. //If a precision value is specified
  4707. if (size.precision) {
  4708. width = Math.round(engine.getRenderWidth() * size.precision);
  4709. height = Math.round(width / engine.getAspectRatio(camera));
  4710. size = { width: width, height: height };
  4711. }
  4712. else if (size.width && size.height) {
  4713. width = size.width;
  4714. height = size.height;
  4715. }
  4716. else if (size.width && !size.height) {
  4717. width = size.width;
  4718. height = Math.round(width / engine.getAspectRatio(camera));
  4719. size = { width: width, height: height };
  4720. }
  4721. else if (size.height && !size.width) {
  4722. height = size.height;
  4723. width = Math.round(height * engine.getAspectRatio(camera));
  4724. size = { width: width, height: height };
  4725. }
  4726. else if (!isNaN(size)) {
  4727. height = size;
  4728. width = size;
  4729. }
  4730. else {
  4731. Tools.Error("Invalid 'size' parameter !");
  4732. return;
  4733. }
  4734. var scene = camera.getScene();
  4735. var previousCamera = null;
  4736. if (scene.activeCamera !== camera) {
  4737. previousCamera = scene.activeCamera;
  4738. scene.activeCamera = camera;
  4739. }
  4740. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4741. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4742. texture.renderList = scene.meshes;
  4743. texture.onAfterRender = function () {
  4744. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4745. };
  4746. scene.incrementRenderId();
  4747. texture.render(true);
  4748. texture.dispose();
  4749. if (previousCamera) {
  4750. scene.activeCamera = previousCamera;
  4751. }
  4752. };
  4753. // XHR response validator for local file scenario
  4754. Tools.ValidateXHRData = function (xhr, dataType) {
  4755. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4756. if (dataType === void 0) { dataType = 7; }
  4757. try {
  4758. if (dataType & 1) {
  4759. if (xhr.responseText && xhr.responseText.length > 0) {
  4760. return true;
  4761. }
  4762. else if (dataType === 1) {
  4763. return false;
  4764. }
  4765. }
  4766. if (dataType & 2) {
  4767. // Check header width and height since there is no "TGA" magic number
  4768. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4769. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4770. return true;
  4771. }
  4772. else if (dataType === 2) {
  4773. return false;
  4774. }
  4775. }
  4776. if (dataType & 4) {
  4777. // Check for the "DDS" magic number
  4778. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4779. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4780. return true;
  4781. }
  4782. else {
  4783. return false;
  4784. }
  4785. }
  4786. }
  4787. catch (e) {
  4788. }
  4789. return false;
  4790. };
  4791. Object.defineProperty(Tools, "NoneLogLevel", {
  4792. get: function () {
  4793. return Tools._NoneLogLevel;
  4794. },
  4795. enumerable: true,
  4796. configurable: true
  4797. });
  4798. Object.defineProperty(Tools, "MessageLogLevel", {
  4799. get: function () {
  4800. return Tools._MessageLogLevel;
  4801. },
  4802. enumerable: true,
  4803. configurable: true
  4804. });
  4805. Object.defineProperty(Tools, "WarningLogLevel", {
  4806. get: function () {
  4807. return Tools._WarningLogLevel;
  4808. },
  4809. enumerable: true,
  4810. configurable: true
  4811. });
  4812. Object.defineProperty(Tools, "ErrorLogLevel", {
  4813. get: function () {
  4814. return Tools._ErrorLogLevel;
  4815. },
  4816. enumerable: true,
  4817. configurable: true
  4818. });
  4819. Object.defineProperty(Tools, "AllLogLevel", {
  4820. get: function () {
  4821. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4822. },
  4823. enumerable: true,
  4824. configurable: true
  4825. });
  4826. Tools._AddLogEntry = function (entry) {
  4827. Tools._LogCache = entry + Tools._LogCache;
  4828. if (Tools.OnNewCacheEntry) {
  4829. Tools.OnNewCacheEntry(entry);
  4830. }
  4831. };
  4832. Tools._FormatMessage = function (message) {
  4833. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4834. var date = new Date();
  4835. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4836. };
  4837. Tools._LogDisabled = function (message) {
  4838. // nothing to do
  4839. };
  4840. Tools._LogEnabled = function (message) {
  4841. var formattedMessage = Tools._FormatMessage(message);
  4842. console.log("BJS - " + formattedMessage);
  4843. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4844. Tools._AddLogEntry(entry);
  4845. };
  4846. Tools._WarnDisabled = function (message) {
  4847. // nothing to do
  4848. };
  4849. Tools._WarnEnabled = function (message) {
  4850. var formattedMessage = Tools._FormatMessage(message);
  4851. console.warn("BJS - " + formattedMessage);
  4852. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4853. Tools._AddLogEntry(entry);
  4854. };
  4855. Tools._ErrorDisabled = function (message) {
  4856. // nothing to do
  4857. };
  4858. Tools._ErrorEnabled = function (message) {
  4859. Tools.errorsCount++;
  4860. var formattedMessage = Tools._FormatMessage(message);
  4861. console.error("BJS - " + formattedMessage);
  4862. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4863. Tools._AddLogEntry(entry);
  4864. };
  4865. Object.defineProperty(Tools, "LogCache", {
  4866. get: function () {
  4867. return Tools._LogCache;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Tools.ClearLogCache = function () {
  4873. Tools._LogCache = "";
  4874. Tools.errorsCount = 0;
  4875. };
  4876. Object.defineProperty(Tools, "LogLevels", {
  4877. set: function (level) {
  4878. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4879. Tools.Log = Tools._LogEnabled;
  4880. }
  4881. else {
  4882. Tools.Log = Tools._LogDisabled;
  4883. }
  4884. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4885. Tools.Warn = Tools._WarnEnabled;
  4886. }
  4887. else {
  4888. Tools.Warn = Tools._WarnDisabled;
  4889. }
  4890. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4891. Tools.Error = Tools._ErrorEnabled;
  4892. }
  4893. else {
  4894. Tools.Error = Tools._ErrorDisabled;
  4895. }
  4896. },
  4897. enumerable: true,
  4898. configurable: true
  4899. });
  4900. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4901. get: function () {
  4902. return Tools._PerformanceNoneLogLevel;
  4903. },
  4904. enumerable: true,
  4905. configurable: true
  4906. });
  4907. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4908. get: function () {
  4909. return Tools._PerformanceUserMarkLogLevel;
  4910. },
  4911. enumerable: true,
  4912. configurable: true
  4913. });
  4914. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4915. get: function () {
  4916. return Tools._PerformanceConsoleLogLevel;
  4917. },
  4918. enumerable: true,
  4919. configurable: true
  4920. });
  4921. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4922. set: function (level) {
  4923. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4924. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4925. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4926. return;
  4927. }
  4928. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4929. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4930. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4931. return;
  4932. }
  4933. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4934. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4940. };
  4941. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4942. };
  4943. Tools._StartUserMark = function (counterName, condition) {
  4944. if (condition === void 0) { condition = true; }
  4945. if (!condition || !Tools._performance.mark) {
  4946. return;
  4947. }
  4948. Tools._performance.mark(counterName + "-Begin");
  4949. };
  4950. Tools._EndUserMark = function (counterName, condition) {
  4951. if (condition === void 0) { condition = true; }
  4952. if (!condition || !Tools._performance.mark) {
  4953. return;
  4954. }
  4955. Tools._performance.mark(counterName + "-End");
  4956. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4957. };
  4958. Tools._StartPerformanceConsole = function (counterName, condition) {
  4959. if (condition === void 0) { condition = true; }
  4960. if (!condition) {
  4961. return;
  4962. }
  4963. Tools._StartUserMark(counterName, condition);
  4964. if (console.time) {
  4965. console.time(counterName);
  4966. }
  4967. };
  4968. Tools._EndPerformanceConsole = function (counterName, condition) {
  4969. if (condition === void 0) { condition = true; }
  4970. if (!condition) {
  4971. return;
  4972. }
  4973. Tools._EndUserMark(counterName, condition);
  4974. if (console.time) {
  4975. console.timeEnd(counterName);
  4976. }
  4977. };
  4978. Object.defineProperty(Tools, "Now", {
  4979. get: function () {
  4980. if (window.performance && window.performance.now) {
  4981. return window.performance.now();
  4982. }
  4983. return new Date().getTime();
  4984. },
  4985. enumerable: true,
  4986. configurable: true
  4987. });
  4988. // Deprecated
  4989. Tools.GetFps = function () {
  4990. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4991. return 0;
  4992. };
  4993. Tools.BaseUrl = "";
  4994. // Logs
  4995. Tools._NoneLogLevel = 0;
  4996. Tools._MessageLogLevel = 1;
  4997. Tools._WarningLogLevel = 2;
  4998. Tools._ErrorLogLevel = 4;
  4999. Tools._LogCache = "";
  5000. Tools.errorsCount = 0;
  5001. Tools.Log = Tools._LogEnabled;
  5002. Tools.Warn = Tools._WarnEnabled;
  5003. Tools.Error = Tools._ErrorEnabled;
  5004. // Performances
  5005. Tools._PerformanceNoneLogLevel = 0;
  5006. Tools._PerformanceUserMarkLogLevel = 1;
  5007. Tools._PerformanceConsoleLogLevel = 2;
  5008. Tools._performance = window.performance;
  5009. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5010. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5011. return Tools;
  5012. })();
  5013. BABYLON.Tools = Tools;
  5014. /**
  5015. * An implementation of a loop for asynchronous functions.
  5016. */
  5017. var AsyncLoop = (function () {
  5018. /**
  5019. * Constroctor.
  5020. * @param iterations the number of iterations.
  5021. * @param _fn the function to run each iteration
  5022. * @param _successCallback the callback that will be called upon succesful execution
  5023. * @param offset starting offset.
  5024. */
  5025. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5026. if (offset === void 0) { offset = 0; }
  5027. this.iterations = iterations;
  5028. this._fn = _fn;
  5029. this._successCallback = _successCallback;
  5030. this.index = offset - 1;
  5031. this._done = false;
  5032. }
  5033. /**
  5034. * Execute the next iteration. Must be called after the last iteration was finished.
  5035. */
  5036. AsyncLoop.prototype.executeNext = function () {
  5037. if (!this._done) {
  5038. if (this.index + 1 < this.iterations) {
  5039. ++this.index;
  5040. this._fn(this);
  5041. }
  5042. else {
  5043. this.breakLoop();
  5044. }
  5045. }
  5046. };
  5047. /**
  5048. * Break the loop and run the success callback.
  5049. */
  5050. AsyncLoop.prototype.breakLoop = function () {
  5051. this._done = true;
  5052. this._successCallback();
  5053. };
  5054. /**
  5055. * Helper function
  5056. */
  5057. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5058. if (offset === void 0) { offset = 0; }
  5059. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5060. loop.executeNext();
  5061. return loop;
  5062. };
  5063. /**
  5064. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5065. * @param iterations total number of iterations
  5066. * @param syncedIterations number of synchronous iterations in each async iteration.
  5067. * @param fn the function to call each iteration.
  5068. * @param callback a success call back that will be called when iterating stops.
  5069. * @param breakFunction a break condition (optional)
  5070. * @param timeout timeout settings for the setTimeout function. default - 0.
  5071. * @constructor
  5072. */
  5073. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5074. if (timeout === void 0) { timeout = 0; }
  5075. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5076. if (breakFunction && breakFunction())
  5077. loop.breakLoop();
  5078. else {
  5079. setTimeout(function () {
  5080. for (var i = 0; i < syncedIterations; ++i) {
  5081. var iteration = (loop.index * syncedIterations) + i;
  5082. if (iteration >= iterations)
  5083. break;
  5084. fn(iteration);
  5085. if (breakFunction && breakFunction()) {
  5086. loop.breakLoop();
  5087. break;
  5088. }
  5089. }
  5090. loop.executeNext();
  5091. }, timeout);
  5092. }
  5093. }, callback);
  5094. };
  5095. return AsyncLoop;
  5096. })();
  5097. BABYLON.AsyncLoop = AsyncLoop;
  5098. })(BABYLON || (BABYLON = {}));
  5099. var BABYLON;
  5100. (function (BABYLON) {
  5101. var _DepthCullingState = (function () {
  5102. function _DepthCullingState() {
  5103. this._isDepthTestDirty = false;
  5104. this._isDepthMaskDirty = false;
  5105. this._isDepthFuncDirty = false;
  5106. this._isCullFaceDirty = false;
  5107. this._isCullDirty = false;
  5108. this._isZOffsetDirty = false;
  5109. }
  5110. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5111. get: function () {
  5112. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5118. get: function () {
  5119. return this._zOffset;
  5120. },
  5121. set: function (value) {
  5122. if (this._zOffset === value) {
  5123. return;
  5124. }
  5125. this._zOffset = value;
  5126. this._isZOffsetDirty = true;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5132. get: function () {
  5133. return this._cullFace;
  5134. },
  5135. set: function (value) {
  5136. if (this._cullFace === value) {
  5137. return;
  5138. }
  5139. this._cullFace = value;
  5140. this._isCullFaceDirty = true;
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5146. get: function () {
  5147. return this._cull;
  5148. },
  5149. set: function (value) {
  5150. if (this._cull === value) {
  5151. return;
  5152. }
  5153. this._cull = value;
  5154. this._isCullDirty = true;
  5155. },
  5156. enumerable: true,
  5157. configurable: true
  5158. });
  5159. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5160. get: function () {
  5161. return this._depthFunc;
  5162. },
  5163. set: function (value) {
  5164. if (this._depthFunc === value) {
  5165. return;
  5166. }
  5167. this._depthFunc = value;
  5168. this._isDepthFuncDirty = true;
  5169. },
  5170. enumerable: true,
  5171. configurable: true
  5172. });
  5173. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5174. get: function () {
  5175. return this._depthMask;
  5176. },
  5177. set: function (value) {
  5178. if (this._depthMask === value) {
  5179. return;
  5180. }
  5181. this._depthMask = value;
  5182. this._isDepthMaskDirty = true;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5188. get: function () {
  5189. return this._depthTest;
  5190. },
  5191. set: function (value) {
  5192. if (this._depthTest === value) {
  5193. return;
  5194. }
  5195. this._depthTest = value;
  5196. this._isDepthTestDirty = true;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. _DepthCullingState.prototype.reset = function () {
  5202. this._depthMask = true;
  5203. this._depthTest = true;
  5204. this._depthFunc = null;
  5205. this._cull = null;
  5206. this._cullFace = null;
  5207. this._zOffset = 0;
  5208. this._isDepthTestDirty = true;
  5209. this._isDepthMaskDirty = true;
  5210. this._isDepthFuncDirty = false;
  5211. this._isCullFaceDirty = false;
  5212. this._isCullDirty = false;
  5213. this._isZOffsetDirty = false;
  5214. };
  5215. _DepthCullingState.prototype.apply = function (gl) {
  5216. if (!this.isDirty) {
  5217. return;
  5218. }
  5219. // Cull
  5220. if (this._isCullDirty) {
  5221. if (this.cull) {
  5222. gl.enable(gl.CULL_FACE);
  5223. }
  5224. else {
  5225. gl.disable(gl.CULL_FACE);
  5226. }
  5227. this._isCullDirty = false;
  5228. }
  5229. // Cull face
  5230. if (this._isCullFaceDirty) {
  5231. gl.cullFace(this.cullFace);
  5232. this._isCullFaceDirty = false;
  5233. }
  5234. // Depth mask
  5235. if (this._isDepthMaskDirty) {
  5236. gl.depthMask(this.depthMask);
  5237. this._isDepthMaskDirty = false;
  5238. }
  5239. // Depth test
  5240. if (this._isDepthTestDirty) {
  5241. if (this.depthTest) {
  5242. gl.enable(gl.DEPTH_TEST);
  5243. }
  5244. else {
  5245. gl.disable(gl.DEPTH_TEST);
  5246. }
  5247. this._isDepthTestDirty = false;
  5248. }
  5249. // Depth func
  5250. if (this._isDepthFuncDirty) {
  5251. gl.depthFunc(this.depthFunc);
  5252. this._isDepthFuncDirty = false;
  5253. }
  5254. // zOffset
  5255. if (this._isZOffsetDirty) {
  5256. if (this.zOffset) {
  5257. gl.enable(gl.POLYGON_OFFSET_FILL);
  5258. gl.polygonOffset(this.zOffset, 0);
  5259. }
  5260. else {
  5261. gl.disable(gl.POLYGON_OFFSET_FILL);
  5262. }
  5263. this._isZOffsetDirty = false;
  5264. }
  5265. };
  5266. return _DepthCullingState;
  5267. })();
  5268. BABYLON._DepthCullingState = _DepthCullingState;
  5269. var _AlphaState = (function () {
  5270. function _AlphaState() {
  5271. this._isAlphaBlendDirty = false;
  5272. this._isBlendFunctionParametersDirty = false;
  5273. this._alphaBlend = false;
  5274. this._blendFunctionParameters = new Array(4);
  5275. }
  5276. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5277. get: function () {
  5278. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5279. },
  5280. enumerable: true,
  5281. configurable: true
  5282. });
  5283. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5284. get: function () {
  5285. return this._alphaBlend;
  5286. },
  5287. set: function (value) {
  5288. if (this._alphaBlend === value) {
  5289. return;
  5290. }
  5291. this._alphaBlend = value;
  5292. this._isAlphaBlendDirty = true;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5298. if (this._blendFunctionParameters[0] === value0 &&
  5299. this._blendFunctionParameters[1] === value1 &&
  5300. this._blendFunctionParameters[2] === value2 &&
  5301. this._blendFunctionParameters[3] === value3) {
  5302. return;
  5303. }
  5304. this._blendFunctionParameters[0] = value0;
  5305. this._blendFunctionParameters[1] = value1;
  5306. this._blendFunctionParameters[2] = value2;
  5307. this._blendFunctionParameters[3] = value3;
  5308. this._isBlendFunctionParametersDirty = true;
  5309. };
  5310. _AlphaState.prototype.reset = function () {
  5311. this._alphaBlend = false;
  5312. this._blendFunctionParameters[0] = null;
  5313. this._blendFunctionParameters[1] = null;
  5314. this._blendFunctionParameters[2] = null;
  5315. this._blendFunctionParameters[3] = null;
  5316. this._isAlphaBlendDirty = true;
  5317. this._isBlendFunctionParametersDirty = false;
  5318. };
  5319. _AlphaState.prototype.apply = function (gl) {
  5320. if (!this.isDirty) {
  5321. return;
  5322. }
  5323. // Alpha blend
  5324. if (this._isAlphaBlendDirty) {
  5325. if (this._alphaBlend) {
  5326. gl.enable(gl.BLEND);
  5327. }
  5328. else {
  5329. gl.disable(gl.BLEND);
  5330. }
  5331. this._isAlphaBlendDirty = false;
  5332. }
  5333. // Alpha function
  5334. if (this._isBlendFunctionParametersDirty) {
  5335. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5336. this._isBlendFunctionParametersDirty = false;
  5337. }
  5338. };
  5339. return _AlphaState;
  5340. })();
  5341. BABYLON._AlphaState = _AlphaState;
  5342. var compileShader = function (gl, source, type, defines) {
  5343. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5344. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5345. gl.compileShader(shader);
  5346. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5347. throw new Error(gl.getShaderInfoLog(shader));
  5348. }
  5349. return shader;
  5350. };
  5351. var getWebGLTextureType = function (gl, type) {
  5352. var textureType = gl.UNSIGNED_BYTE;
  5353. if (type === Engine.TEXTURETYPE_FLOAT)
  5354. textureType = gl.FLOAT;
  5355. return textureType;
  5356. };
  5357. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5358. var magFilter = gl.NEAREST;
  5359. var minFilter = gl.NEAREST;
  5360. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5361. magFilter = gl.LINEAR;
  5362. if (generateMipMaps) {
  5363. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5364. }
  5365. else {
  5366. minFilter = gl.LINEAR;
  5367. }
  5368. }
  5369. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5370. magFilter = gl.LINEAR;
  5371. if (generateMipMaps) {
  5372. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5373. }
  5374. else {
  5375. minFilter = gl.LINEAR;
  5376. }
  5377. }
  5378. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5379. magFilter = gl.NEAREST;
  5380. if (generateMipMaps) {
  5381. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5382. }
  5383. else {
  5384. minFilter = gl.NEAREST;
  5385. }
  5386. }
  5387. return {
  5388. min: minFilter,
  5389. mag: magFilter
  5390. };
  5391. };
  5392. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5394. var engine = scene.getEngine();
  5395. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5396. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5397. gl.bindTexture(gl.TEXTURE_2D, texture);
  5398. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5399. texture._baseWidth = width;
  5400. texture._baseHeight = height;
  5401. texture._width = potWidth;
  5402. texture._height = potHeight;
  5403. texture.isReady = true;
  5404. processFunction(potWidth, potHeight);
  5405. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5408. if (!noMipmap && !isCompressed) {
  5409. gl.generateMipmap(gl.TEXTURE_2D);
  5410. }
  5411. gl.bindTexture(gl.TEXTURE_2D, null);
  5412. engine._activeTexturesCache = [];
  5413. scene._removePendingData(texture);
  5414. };
  5415. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5416. var onload = function () {
  5417. loadedImages[index] = img;
  5418. loadedImages._internalCount++;
  5419. scene._removePendingData(img);
  5420. if (loadedImages._internalCount === 6) {
  5421. onfinish(loadedImages);
  5422. }
  5423. };
  5424. var onerror = function () {
  5425. scene._removePendingData(img);
  5426. };
  5427. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5428. scene._addPendingData(img);
  5429. };
  5430. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5431. var loadedImages = [];
  5432. loadedImages._internalCount = 0;
  5433. for (var index = 0; index < 6; index++) {
  5434. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5435. }
  5436. };
  5437. var EngineCapabilities = (function () {
  5438. function EngineCapabilities() {
  5439. }
  5440. return EngineCapabilities;
  5441. })();
  5442. BABYLON.EngineCapabilities = EngineCapabilities;
  5443. /**
  5444. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5445. */
  5446. var Engine = (function () {
  5447. /**
  5448. * @constructor
  5449. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5450. * @param {boolean} [antialias] - enable antialias
  5451. * @param options - further options to be sent to the getContext function
  5452. */
  5453. function Engine(canvas, antialias, options) {
  5454. var _this = this;
  5455. // Public members
  5456. this.isFullscreen = false;
  5457. this.isPointerLock = false;
  5458. this.cullBackFaces = true;
  5459. this.renderEvenInBackground = true;
  5460. // To enable/disable IDB support and avoid XHR on .manifest
  5461. this.enableOfflineSupport = true;
  5462. this.scenes = new Array();
  5463. this._windowIsBackground = false;
  5464. this._drawCalls = 0;
  5465. this._renderingQueueLaunched = false;
  5466. this._activeRenderLoops = [];
  5467. // FPS
  5468. this.fpsRange = 60;
  5469. this.previousFramesDuration = [];
  5470. this.fps = 60;
  5471. this.deltaTime = 0;
  5472. // States
  5473. this._depthCullingState = new _DepthCullingState();
  5474. this._alphaState = new _AlphaState();
  5475. this._alphaMode = Engine.ALPHA_DISABLE;
  5476. // Cache
  5477. this._loadedTexturesCache = new Array();
  5478. this._activeTexturesCache = new Array();
  5479. this._compiledEffects = {};
  5480. this._uintIndicesCurrentlySet = false;
  5481. this._renderingCanvas = canvas;
  5482. options = options || {};
  5483. options.antialias = antialias;
  5484. if (options.preserveDrawingBuffer === undefined) {
  5485. options.preserveDrawingBuffer = false;
  5486. }
  5487. // GL
  5488. try {
  5489. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5490. }
  5491. catch (e) {
  5492. throw new Error("WebGL not supported");
  5493. }
  5494. if (!this._gl) {
  5495. throw new Error("WebGL not supported");
  5496. }
  5497. this._onBlur = function () {
  5498. _this._windowIsBackground = true;
  5499. };
  5500. this._onFocus = function () {
  5501. _this._windowIsBackground = false;
  5502. };
  5503. window.addEventListener("blur", this._onBlur);
  5504. window.addEventListener("focus", this._onFocus);
  5505. // Viewport
  5506. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5507. this.resize();
  5508. // Caps
  5509. this._caps = new EngineCapabilities();
  5510. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5511. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5512. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5513. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5514. // Infos
  5515. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5516. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5517. if (rendererInfo != null) {
  5518. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5519. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5520. }
  5521. if (!this._glVendor) {
  5522. this._glVendor = "Unknown vendor";
  5523. }
  5524. if (!this._glRenderer) {
  5525. this._glRenderer = "Unknown renderer";
  5526. }
  5527. // Extensions
  5528. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5529. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5530. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5531. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5532. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5533. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5534. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5535. this._caps.highPrecisionShaderSupported = true;
  5536. if (this._gl.getShaderPrecisionFormat) {
  5537. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5538. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5539. }
  5540. // Depth buffer
  5541. this.setDepthBuffer(true);
  5542. this.setDepthFunctionToLessOrEqual();
  5543. this.setDepthWrite(true);
  5544. // Fullscreen
  5545. this._onFullscreenChange = function () {
  5546. if (document.fullscreen !== undefined) {
  5547. _this.isFullscreen = document.fullscreen;
  5548. }
  5549. else if (document.mozFullScreen !== undefined) {
  5550. _this.isFullscreen = document.mozFullScreen;
  5551. }
  5552. else if (document.webkitIsFullScreen !== undefined) {
  5553. _this.isFullscreen = document.webkitIsFullScreen;
  5554. }
  5555. else if (document.msIsFullScreen !== undefined) {
  5556. _this.isFullscreen = document.msIsFullScreen;
  5557. }
  5558. // Pointer lock
  5559. if (_this.isFullscreen && _this._pointerLockRequested) {
  5560. canvas.requestPointerLock = canvas.requestPointerLock ||
  5561. canvas.msRequestPointerLock ||
  5562. canvas.mozRequestPointerLock ||
  5563. canvas.webkitRequestPointerLock;
  5564. if (canvas.requestPointerLock) {
  5565. canvas.requestPointerLock();
  5566. }
  5567. }
  5568. };
  5569. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5570. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5571. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5572. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5573. // Pointer lock
  5574. this._onPointerLockChange = function () {
  5575. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5576. document.webkitPointerLockElement === canvas ||
  5577. document.msPointerLockElement === canvas ||
  5578. document.pointerLockElement === canvas);
  5579. };
  5580. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5581. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5582. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5583. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5584. if (!Engine.audioEngine) {
  5585. Engine.audioEngine = new BABYLON.AudioEngine();
  5586. }
  5587. //default loading screen
  5588. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5589. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5590. }
  5591. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5592. get: function () {
  5593. return Engine._ALPHA_DISABLE;
  5594. },
  5595. enumerable: true,
  5596. configurable: true
  5597. });
  5598. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5599. get: function () {
  5600. return Engine._ALPHA_ONEONE;
  5601. },
  5602. enumerable: true,
  5603. configurable: true
  5604. });
  5605. Object.defineProperty(Engine, "ALPHA_ADD", {
  5606. get: function () {
  5607. return Engine._ALPHA_ADD;
  5608. },
  5609. enumerable: true,
  5610. configurable: true
  5611. });
  5612. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5613. get: function () {
  5614. return Engine._ALPHA_COMBINE;
  5615. },
  5616. enumerable: true,
  5617. configurable: true
  5618. });
  5619. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5620. get: function () {
  5621. return Engine._ALPHA_SUBTRACT;
  5622. },
  5623. enumerable: true,
  5624. configurable: true
  5625. });
  5626. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5627. get: function () {
  5628. return Engine._ALPHA_MULTIPLY;
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5634. get: function () {
  5635. return Engine._ALPHA_MAXIMIZED;
  5636. },
  5637. enumerable: true,
  5638. configurable: true
  5639. });
  5640. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5641. get: function () {
  5642. return Engine._DELAYLOADSTATE_NONE;
  5643. },
  5644. enumerable: true,
  5645. configurable: true
  5646. });
  5647. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5648. get: function () {
  5649. return Engine._DELAYLOADSTATE_LOADED;
  5650. },
  5651. enumerable: true,
  5652. configurable: true
  5653. });
  5654. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5655. get: function () {
  5656. return Engine._DELAYLOADSTATE_LOADING;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5662. get: function () {
  5663. return Engine._DELAYLOADSTATE_NOTLOADED;
  5664. },
  5665. enumerable: true,
  5666. configurable: true
  5667. });
  5668. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5669. get: function () {
  5670. return Engine._TEXTUREFORMAT_ALPHA;
  5671. },
  5672. enumerable: true,
  5673. configurable: true
  5674. });
  5675. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5676. get: function () {
  5677. return Engine._TEXTUREFORMAT_LUMINANCE;
  5678. },
  5679. enumerable: true,
  5680. configurable: true
  5681. });
  5682. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5683. get: function () {
  5684. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5685. },
  5686. enumerable: true,
  5687. configurable: true
  5688. });
  5689. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5690. get: function () {
  5691. return Engine._TEXTUREFORMAT_RGB;
  5692. },
  5693. enumerable: true,
  5694. configurable: true
  5695. });
  5696. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5697. get: function () {
  5698. return Engine._TEXTUREFORMAT_RGBA;
  5699. },
  5700. enumerable: true,
  5701. configurable: true
  5702. });
  5703. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5704. get: function () {
  5705. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5706. },
  5707. enumerable: true,
  5708. configurable: true
  5709. });
  5710. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5711. get: function () {
  5712. return Engine._TEXTURETYPE_FLOAT;
  5713. },
  5714. enumerable: true,
  5715. configurable: true
  5716. });
  5717. Object.defineProperty(Engine, "Version", {
  5718. get: function () {
  5719. return "2.3.0-alpha";
  5720. },
  5721. enumerable: true,
  5722. configurable: true
  5723. });
  5724. Engine.prototype._prepareWorkingCanvas = function () {
  5725. if (this._workingCanvas) {
  5726. return;
  5727. }
  5728. this._workingCanvas = document.createElement("canvas");
  5729. this._workingContext = this._workingCanvas.getContext("2d");
  5730. };
  5731. Engine.prototype.getGlInfo = function () {
  5732. return {
  5733. vendor: this._glVendor,
  5734. renderer: this._glRenderer,
  5735. version: this._glVersion
  5736. };
  5737. };
  5738. Engine.prototype.getAspectRatio = function (camera) {
  5739. var viewport = camera.viewport;
  5740. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5741. };
  5742. Engine.prototype.getRenderWidth = function () {
  5743. if (this._currentRenderTarget) {
  5744. return this._currentRenderTarget._width;
  5745. }
  5746. return this._renderingCanvas.width;
  5747. };
  5748. Engine.prototype.getRenderHeight = function () {
  5749. if (this._currentRenderTarget) {
  5750. return this._currentRenderTarget._height;
  5751. }
  5752. return this._renderingCanvas.height;
  5753. };
  5754. Engine.prototype.getRenderingCanvas = function () {
  5755. return this._renderingCanvas;
  5756. };
  5757. Engine.prototype.getRenderingCanvasClientRect = function () {
  5758. return this._renderingCanvas.getBoundingClientRect();
  5759. };
  5760. Engine.prototype.setHardwareScalingLevel = function (level) {
  5761. this._hardwareScalingLevel = level;
  5762. this.resize();
  5763. };
  5764. Engine.prototype.getHardwareScalingLevel = function () {
  5765. return this._hardwareScalingLevel;
  5766. };
  5767. Engine.prototype.getLoadedTexturesCache = function () {
  5768. return this._loadedTexturesCache;
  5769. };
  5770. Engine.prototype.getCaps = function () {
  5771. return this._caps;
  5772. };
  5773. Object.defineProperty(Engine.prototype, "drawCalls", {
  5774. get: function () {
  5775. return this._drawCalls;
  5776. },
  5777. enumerable: true,
  5778. configurable: true
  5779. });
  5780. // Methods
  5781. Engine.prototype.resetDrawCalls = function () {
  5782. this._drawCalls = 0;
  5783. };
  5784. Engine.prototype.setDepthFunctionToGreater = function () {
  5785. this._depthCullingState.depthFunc = this._gl.GREATER;
  5786. };
  5787. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5788. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5789. };
  5790. Engine.prototype.setDepthFunctionToLess = function () {
  5791. this._depthCullingState.depthFunc = this._gl.LESS;
  5792. };
  5793. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5794. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5795. };
  5796. /**
  5797. * stop executing a render loop function and remove it from the execution array
  5798. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5799. */
  5800. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5801. if (!renderFunction) {
  5802. this._activeRenderLoops = [];
  5803. return;
  5804. }
  5805. var index = this._activeRenderLoops.indexOf(renderFunction);
  5806. if (index >= 0) {
  5807. this._activeRenderLoops.splice(index, 1);
  5808. }
  5809. };
  5810. Engine.prototype._renderLoop = function () {
  5811. var _this = this;
  5812. var shouldRender = true;
  5813. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5814. shouldRender = false;
  5815. }
  5816. if (shouldRender) {
  5817. // Start new frame
  5818. this.beginFrame();
  5819. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5820. var renderFunction = this._activeRenderLoops[index];
  5821. renderFunction();
  5822. }
  5823. // Present
  5824. this.endFrame();
  5825. }
  5826. if (this._activeRenderLoops.length > 0) {
  5827. // Register new frame
  5828. BABYLON.Tools.QueueNewFrame(function () {
  5829. _this._renderLoop();
  5830. });
  5831. }
  5832. else {
  5833. this._renderingQueueLaunched = false;
  5834. }
  5835. };
  5836. /**
  5837. * Register and execute a render loop. The engine can have more than one render function.
  5838. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5839. * @example
  5840. * engine.runRenderLoop(function () {
  5841. * scene.render()
  5842. * })
  5843. */
  5844. Engine.prototype.runRenderLoop = function (renderFunction) {
  5845. var _this = this;
  5846. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5847. return;
  5848. }
  5849. this._activeRenderLoops.push(renderFunction);
  5850. if (!this._renderingQueueLaunched) {
  5851. this._renderingQueueLaunched = true;
  5852. BABYLON.Tools.QueueNewFrame(function () {
  5853. _this._renderLoop();
  5854. });
  5855. }
  5856. };
  5857. /**
  5858. * Toggle full screen mode.
  5859. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5860. */
  5861. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5862. if (this.isFullscreen) {
  5863. BABYLON.Tools.ExitFullscreen();
  5864. }
  5865. else {
  5866. this._pointerLockRequested = requestPointerLock;
  5867. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5868. }
  5869. };
  5870. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5871. this.applyStates();
  5872. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5873. if (this._depthCullingState.depthMask) {
  5874. this._gl.clearDepth(1.0);
  5875. }
  5876. var mode = 0;
  5877. if (backBuffer)
  5878. mode |= this._gl.COLOR_BUFFER_BIT;
  5879. if (depthStencil && this._depthCullingState.depthMask)
  5880. mode |= this._gl.DEPTH_BUFFER_BIT;
  5881. this._gl.clear(mode);
  5882. };
  5883. /**
  5884. * Set the WebGL's viewport
  5885. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5886. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5887. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5888. */
  5889. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5890. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5891. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5892. var x = viewport.x || 0;
  5893. var y = viewport.y || 0;
  5894. this._cachedViewport = viewport;
  5895. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5896. };
  5897. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5898. this._cachedViewport = null;
  5899. this._gl.viewport(x, y, width, height);
  5900. };
  5901. Engine.prototype.beginFrame = function () {
  5902. this._measureFps();
  5903. };
  5904. Engine.prototype.endFrame = function () {
  5905. //this.flushFramebuffer();
  5906. };
  5907. /**
  5908. * resize the view according to the canvas' size.
  5909. * @example
  5910. * window.addEventListener("resize", function () {
  5911. * engine.resize();
  5912. * });
  5913. */
  5914. Engine.prototype.resize = function () {
  5915. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5916. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5917. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5918. };
  5919. /**
  5920. * force a specific size of the canvas
  5921. * @param {number} width - the new canvas' width
  5922. * @param {number} height - the new canvas' height
  5923. */
  5924. Engine.prototype.setSize = function (width, height) {
  5925. this._renderingCanvas.width = width;
  5926. this._renderingCanvas.height = height;
  5927. for (var index = 0; index < this.scenes.length; index++) {
  5928. var scene = this.scenes[index];
  5929. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5930. var cam = scene.cameras[camIndex];
  5931. cam._currentRenderId = 0;
  5932. }
  5933. }
  5934. };
  5935. Engine.prototype.bindFramebuffer = function (texture) {
  5936. this._currentRenderTarget = texture;
  5937. var gl = this._gl;
  5938. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5939. this._gl.viewport(0, 0, texture._width, texture._height);
  5940. this.wipeCaches();
  5941. };
  5942. Engine.prototype.unBindFramebuffer = function (texture) {
  5943. this._currentRenderTarget = null;
  5944. if (texture.generateMipMaps) {
  5945. var gl = this._gl;
  5946. gl.bindTexture(gl.TEXTURE_2D, texture);
  5947. gl.generateMipmap(gl.TEXTURE_2D);
  5948. gl.bindTexture(gl.TEXTURE_2D, null);
  5949. }
  5950. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5951. };
  5952. Engine.prototype.flushFramebuffer = function () {
  5953. this._gl.flush();
  5954. };
  5955. Engine.prototype.restoreDefaultFramebuffer = function () {
  5956. this._currentRenderTarget = null;
  5957. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5958. this.setViewport(this._cachedViewport);
  5959. this.wipeCaches();
  5960. };
  5961. // VBOs
  5962. Engine.prototype._resetVertexBufferBinding = function () {
  5963. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5964. this._cachedVertexBuffers = null;
  5965. };
  5966. Engine.prototype.createVertexBuffer = function (vertices) {
  5967. var vbo = this._gl.createBuffer();
  5968. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5969. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5970. this._resetVertexBufferBinding();
  5971. vbo.references = 1;
  5972. return vbo;
  5973. };
  5974. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5975. var vbo = this._gl.createBuffer();
  5976. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5977. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5978. this._resetVertexBufferBinding();
  5979. vbo.references = 1;
  5980. return vbo;
  5981. };
  5982. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5984. if (offset === undefined) {
  5985. offset = 0;
  5986. }
  5987. if (vertices instanceof Float32Array) {
  5988. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5989. }
  5990. else {
  5991. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5992. }
  5993. this._resetVertexBufferBinding();
  5994. };
  5995. Engine.prototype._resetIndexBufferBinding = function () {
  5996. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5997. this._cachedIndexBuffer = null;
  5998. };
  5999. Engine.prototype.createIndexBuffer = function (indices) {
  6000. var vbo = this._gl.createBuffer();
  6001. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6002. // Check for 32 bits indices
  6003. var arrayBuffer;
  6004. var need32Bits = false;
  6005. if (this._caps.uintIndices) {
  6006. for (var index = 0; index < indices.length; index++) {
  6007. if (indices[index] > 65535) {
  6008. need32Bits = true;
  6009. break;
  6010. }
  6011. }
  6012. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6013. }
  6014. else {
  6015. arrayBuffer = new Uint16Array(indices);
  6016. }
  6017. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6018. this._resetIndexBufferBinding();
  6019. vbo.references = 1;
  6020. vbo.is32Bits = need32Bits;
  6021. return vbo;
  6022. };
  6023. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6024. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6025. this._cachedVertexBuffers = vertexBuffer;
  6026. this._cachedEffectForVertexBuffers = effect;
  6027. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6028. var offset = 0;
  6029. for (var index = 0; index < vertexDeclaration.length; index++) {
  6030. var order = effect.getAttributeLocation(index);
  6031. if (order >= 0) {
  6032. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6033. }
  6034. offset += vertexDeclaration[index] * 4;
  6035. }
  6036. }
  6037. if (this._cachedIndexBuffer !== indexBuffer) {
  6038. this._cachedIndexBuffer = indexBuffer;
  6039. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6040. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6041. }
  6042. };
  6043. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6044. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6045. this._cachedVertexBuffers = vertexBuffers;
  6046. this._cachedEffectForVertexBuffers = effect;
  6047. var attributes = effect.getAttributesNames();
  6048. for (var index = 0; index < attributes.length; index++) {
  6049. var order = effect.getAttributeLocation(index);
  6050. if (order >= 0) {
  6051. var vertexBuffer = vertexBuffers[attributes[index]];
  6052. if (!vertexBuffer) {
  6053. continue;
  6054. }
  6055. var stride = vertexBuffer.getStrideSize();
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6057. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6058. }
  6059. }
  6060. }
  6061. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6062. this._cachedIndexBuffer = indexBuffer;
  6063. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6064. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6065. }
  6066. };
  6067. Engine.prototype._releaseBuffer = function (buffer) {
  6068. buffer.references--;
  6069. if (buffer.references === 0) {
  6070. this._gl.deleteBuffer(buffer);
  6071. return true;
  6072. }
  6073. return false;
  6074. };
  6075. Engine.prototype.createInstancesBuffer = function (capacity) {
  6076. var buffer = this._gl.createBuffer();
  6077. buffer.capacity = capacity;
  6078. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6079. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6080. return buffer;
  6081. };
  6082. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6083. this._gl.deleteBuffer(buffer);
  6084. };
  6085. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6086. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6088. for (var index = 0; index < 4; index++) {
  6089. var offsetLocation = offsetLocations[index];
  6090. this._gl.enableVertexAttribArray(offsetLocation);
  6091. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6092. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6093. }
  6094. };
  6095. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6096. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6097. for (var index = 0; index < 4; index++) {
  6098. var offsetLocation = offsetLocations[index];
  6099. this._gl.disableVertexAttribArray(offsetLocation);
  6100. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6101. }
  6102. };
  6103. Engine.prototype.applyStates = function () {
  6104. this._depthCullingState.apply(this._gl);
  6105. this._alphaState.apply(this._gl);
  6106. };
  6107. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6108. // Apply states
  6109. this.applyStates();
  6110. this._drawCalls++;
  6111. // Render
  6112. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6113. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6114. if (instancesCount) {
  6115. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6116. return;
  6117. }
  6118. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6119. };
  6120. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6121. // Apply states
  6122. this.applyStates();
  6123. this._drawCalls++;
  6124. if (instancesCount) {
  6125. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6126. return;
  6127. }
  6128. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6129. };
  6130. // Shaders
  6131. Engine.prototype._releaseEffect = function (effect) {
  6132. if (this._compiledEffects[effect._key]) {
  6133. delete this._compiledEffects[effect._key];
  6134. if (effect.getProgram()) {
  6135. this._gl.deleteProgram(effect.getProgram());
  6136. }
  6137. }
  6138. };
  6139. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6140. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6141. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6142. var name = vertex + "+" + fragment + "@" + defines;
  6143. if (this._compiledEffects[name]) {
  6144. return this._compiledEffects[name];
  6145. }
  6146. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6147. effect._key = name;
  6148. this._compiledEffects[name] = effect;
  6149. return effect;
  6150. };
  6151. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6152. if (uniformsNames === void 0) { uniformsNames = []; }
  6153. if (samplers === void 0) { samplers = []; }
  6154. if (defines === void 0) { defines = ""; }
  6155. return this.createEffect({
  6156. vertex: "particles",
  6157. fragmentElement: fragmentName
  6158. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6159. };
  6160. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6161. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6162. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6163. var shaderProgram = this._gl.createProgram();
  6164. this._gl.attachShader(shaderProgram, vertexShader);
  6165. this._gl.attachShader(shaderProgram, fragmentShader);
  6166. this._gl.linkProgram(shaderProgram);
  6167. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6168. if (!linked) {
  6169. var error = this._gl.getProgramInfoLog(shaderProgram);
  6170. if (error) {
  6171. throw new Error(error);
  6172. }
  6173. }
  6174. this._gl.deleteShader(vertexShader);
  6175. this._gl.deleteShader(fragmentShader);
  6176. return shaderProgram;
  6177. };
  6178. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6179. var results = [];
  6180. for (var index = 0; index < uniformsNames.length; index++) {
  6181. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6182. }
  6183. return results;
  6184. };
  6185. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6186. var results = [];
  6187. for (var index = 0; index < attributesNames.length; index++) {
  6188. try {
  6189. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6190. }
  6191. catch (e) {
  6192. results.push(-1);
  6193. }
  6194. }
  6195. return results;
  6196. };
  6197. Engine.prototype.enableEffect = function (effect) {
  6198. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6199. if (effect && effect.onBind) {
  6200. effect.onBind(effect);
  6201. }
  6202. return;
  6203. }
  6204. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6205. // Use program
  6206. this._gl.useProgram(effect.getProgram());
  6207. for (var i in this._vertexAttribArrays) {
  6208. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6209. continue;
  6210. }
  6211. this._vertexAttribArrays[i] = false;
  6212. this._gl.disableVertexAttribArray(i);
  6213. }
  6214. var attributesCount = effect.getAttributesCount();
  6215. for (var index = 0; index < attributesCount; index++) {
  6216. // Attributes
  6217. var order = effect.getAttributeLocation(index);
  6218. if (order >= 0) {
  6219. this._vertexAttribArrays[order] = true;
  6220. this._gl.enableVertexAttribArray(order);
  6221. }
  6222. }
  6223. this._currentEffect = effect;
  6224. if (effect.onBind) {
  6225. effect.onBind(effect);
  6226. }
  6227. };
  6228. Engine.prototype.setArray = function (uniform, array) {
  6229. if (!uniform)
  6230. return;
  6231. this._gl.uniform1fv(uniform, array);
  6232. };
  6233. Engine.prototype.setArray2 = function (uniform, array) {
  6234. if (!uniform || array.length % 2 !== 0)
  6235. return;
  6236. this._gl.uniform2fv(uniform, array);
  6237. };
  6238. Engine.prototype.setArray3 = function (uniform, array) {
  6239. if (!uniform || array.length % 3 !== 0)
  6240. return;
  6241. this._gl.uniform3fv(uniform, array);
  6242. };
  6243. Engine.prototype.setArray4 = function (uniform, array) {
  6244. if (!uniform || array.length % 4 !== 0)
  6245. return;
  6246. this._gl.uniform4fv(uniform, array);
  6247. };
  6248. Engine.prototype.setMatrices = function (uniform, matrices) {
  6249. if (!uniform)
  6250. return;
  6251. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6252. };
  6253. Engine.prototype.setMatrix = function (uniform, matrix) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6257. };
  6258. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6259. if (!uniform)
  6260. return;
  6261. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6262. };
  6263. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6264. if (!uniform)
  6265. return;
  6266. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6267. };
  6268. Engine.prototype.setFloat = function (uniform, value) {
  6269. if (!uniform)
  6270. return;
  6271. this._gl.uniform1f(uniform, value);
  6272. };
  6273. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6274. if (!uniform)
  6275. return;
  6276. this._gl.uniform2f(uniform, x, y);
  6277. };
  6278. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6279. if (!uniform)
  6280. return;
  6281. this._gl.uniform3f(uniform, x, y, z);
  6282. };
  6283. Engine.prototype.setBool = function (uniform, bool) {
  6284. if (!uniform)
  6285. return;
  6286. this._gl.uniform1i(uniform, bool);
  6287. };
  6288. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6289. if (!uniform)
  6290. return;
  6291. this._gl.uniform4f(uniform, x, y, z, w);
  6292. };
  6293. Engine.prototype.setColor3 = function (uniform, color3) {
  6294. if (!uniform)
  6295. return;
  6296. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6297. };
  6298. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6299. if (!uniform)
  6300. return;
  6301. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6302. };
  6303. // States
  6304. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6305. if (zOffset === void 0) { zOffset = 0; }
  6306. if (reverseSide === void 0) { reverseSide = false; }
  6307. // Culling
  6308. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6309. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6310. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6311. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace != cullFace) {
  6312. if (culling) {
  6313. this._depthCullingState.cullFace = cullFace;
  6314. this._depthCullingState.cull = true;
  6315. }
  6316. else {
  6317. this._depthCullingState.cull = false;
  6318. }
  6319. }
  6320. // Z offset
  6321. this._depthCullingState.zOffset = zOffset;
  6322. };
  6323. Engine.prototype.setDepthBuffer = function (enable) {
  6324. this._depthCullingState.depthTest = enable;
  6325. };
  6326. Engine.prototype.getDepthWrite = function () {
  6327. return this._depthCullingState.depthMask;
  6328. };
  6329. Engine.prototype.setDepthWrite = function (enable) {
  6330. this._depthCullingState.depthMask = enable;
  6331. };
  6332. Engine.prototype.setColorWrite = function (enable) {
  6333. this._gl.colorMask(enable, enable, enable, enable);
  6334. };
  6335. Engine.prototype.setAlphaMode = function (mode) {
  6336. if (this._alphaMode == mode) {
  6337. return;
  6338. }
  6339. switch (mode) {
  6340. case Engine.ALPHA_DISABLE:
  6341. this.setDepthWrite(true);
  6342. this._alphaState.alphaBlend = false;
  6343. break;
  6344. case Engine.ALPHA_COMBINE:
  6345. this.setDepthWrite(false);
  6346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6347. this._alphaState.alphaBlend = true;
  6348. break;
  6349. case Engine.ALPHA_ONEONE:
  6350. this.setDepthWrite(false);
  6351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6352. this._alphaState.alphaBlend = true;
  6353. break;
  6354. case Engine.ALPHA_ADD:
  6355. this.setDepthWrite(false);
  6356. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6357. this._alphaState.alphaBlend = true;
  6358. break;
  6359. case Engine.ALPHA_SUBTRACT:
  6360. this.setDepthWrite(false);
  6361. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6362. this._alphaState.alphaBlend = true;
  6363. break;
  6364. case Engine.ALPHA_MULTIPLY:
  6365. this.setDepthWrite(false);
  6366. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6367. this._alphaState.alphaBlend = true;
  6368. break;
  6369. case Engine.ALPHA_MAXIMIZED:
  6370. this.setDepthWrite(false);
  6371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6372. this._alphaState.alphaBlend = true;
  6373. break;
  6374. }
  6375. this._alphaMode = mode;
  6376. };
  6377. Engine.prototype.getAlphaMode = function () {
  6378. return this._alphaMode;
  6379. };
  6380. Engine.prototype.setAlphaTesting = function (enable) {
  6381. this._alphaTest = enable;
  6382. };
  6383. Engine.prototype.getAlphaTesting = function () {
  6384. return this._alphaTest;
  6385. };
  6386. // Textures
  6387. Engine.prototype.wipeCaches = function () {
  6388. this._activeTexturesCache = [];
  6389. this._currentEffect = null;
  6390. this._depthCullingState.reset();
  6391. this._alphaState.reset();
  6392. this._cachedVertexBuffers = null;
  6393. this._cachedIndexBuffer = null;
  6394. this._cachedEffectForVertexBuffers = null;
  6395. };
  6396. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6397. var gl = this._gl;
  6398. gl.bindTexture(gl.TEXTURE_2D, texture);
  6399. var magFilter = gl.NEAREST;
  6400. var minFilter = gl.NEAREST;
  6401. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6402. magFilter = gl.LINEAR;
  6403. minFilter = gl.LINEAR;
  6404. }
  6405. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6406. magFilter = gl.LINEAR;
  6407. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6408. }
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6411. gl.bindTexture(gl.TEXTURE_2D, null);
  6412. texture.samplingMode = samplingMode;
  6413. };
  6414. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6415. var _this = this;
  6416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6417. if (onLoad === void 0) { onLoad = null; }
  6418. if (onError === void 0) { onError = null; }
  6419. if (buffer === void 0) { buffer = null; }
  6420. var texture = this._gl.createTexture();
  6421. var extension;
  6422. var fromData = false;
  6423. if (url.substr(0, 5) === "data:") {
  6424. fromData = true;
  6425. }
  6426. if (!fromData)
  6427. extension = url.substr(url.length - 4, 4).toLowerCase();
  6428. else {
  6429. var oldUrl = url;
  6430. fromData = oldUrl.split(':');
  6431. url = oldUrl;
  6432. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6433. }
  6434. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6435. var isTGA = (extension === ".tga");
  6436. scene._addPendingData(texture);
  6437. texture.url = url;
  6438. texture.noMipmap = noMipmap;
  6439. texture.references = 1;
  6440. texture.samplingMode = samplingMode;
  6441. this._loadedTexturesCache.push(texture);
  6442. var onerror = function () {
  6443. scene._removePendingData(texture);
  6444. if (onError) {
  6445. onError();
  6446. }
  6447. };
  6448. if (isTGA) {
  6449. var callback = function (arrayBuffer) {
  6450. var data = new Uint8Array(arrayBuffer);
  6451. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6452. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6453. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6454. if (onLoad) {
  6455. onLoad();
  6456. }
  6457. }, samplingMode);
  6458. };
  6459. if (!(fromData instanceof Array))
  6460. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6461. callback(arrayBuffer);
  6462. }, onerror, scene.database, true);
  6463. else
  6464. callback(buffer);
  6465. }
  6466. else if (isDDS) {
  6467. callback = function (data) {
  6468. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6469. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6470. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6471. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6472. if (onLoad) {
  6473. onLoad();
  6474. }
  6475. }, samplingMode);
  6476. };
  6477. if (!(fromData instanceof Array))
  6478. BABYLON.Tools.LoadFile(url, function (data) {
  6479. callback(data);
  6480. }, onerror, scene.database, true);
  6481. else
  6482. callback(buffer);
  6483. }
  6484. else {
  6485. var onload = function (img) {
  6486. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6487. var isPot = (img.width === potWidth && img.height === potHeight);
  6488. if (!isPot) {
  6489. _this._prepareWorkingCanvas();
  6490. _this._workingCanvas.width = potWidth;
  6491. _this._workingCanvas.height = potHeight;
  6492. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6493. _this._workingContext.imageSmoothingEnabled = false;
  6494. _this._workingContext.mozImageSmoothingEnabled = false;
  6495. _this._workingContext.oImageSmoothingEnabled = false;
  6496. _this._workingContext.webkitImageSmoothingEnabled = false;
  6497. _this._workingContext.msImageSmoothingEnabled = false;
  6498. }
  6499. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6500. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6501. _this._workingContext.imageSmoothingEnabled = true;
  6502. _this._workingContext.mozImageSmoothingEnabled = true;
  6503. _this._workingContext.oImageSmoothingEnabled = true;
  6504. _this._workingContext.webkitImageSmoothingEnabled = true;
  6505. _this._workingContext.msImageSmoothingEnabled = true;
  6506. }
  6507. }
  6508. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6509. if (onLoad) {
  6510. onLoad();
  6511. }
  6512. }, samplingMode);
  6513. };
  6514. if (!(fromData instanceof Array))
  6515. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6516. else
  6517. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6518. }
  6519. return texture;
  6520. };
  6521. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6522. if (compression === void 0) { compression = null; }
  6523. var internalFormat = this._gl.RGBA;
  6524. switch (format) {
  6525. case Engine.TEXTUREFORMAT_ALPHA:
  6526. internalFormat = this._gl.ALPHA;
  6527. break;
  6528. case Engine.TEXTUREFORMAT_LUMINANCE:
  6529. internalFormat = this._gl.LUMINANCE;
  6530. break;
  6531. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6532. internalFormat = this._gl.LUMINANCE_ALPHA;
  6533. break;
  6534. case Engine.TEXTUREFORMAT_RGB:
  6535. internalFormat = this._gl.RGB;
  6536. break;
  6537. case Engine.TEXTUREFORMAT_RGBA:
  6538. internalFormat = this._gl.RGBA;
  6539. break;
  6540. }
  6541. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6542. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6543. if (compression) {
  6544. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6545. }
  6546. else {
  6547. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6548. }
  6549. if (texture.generateMipMaps) {
  6550. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6551. }
  6552. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6553. this._activeTexturesCache = [];
  6554. texture.isReady = true;
  6555. };
  6556. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6557. if (compression === void 0) { compression = null; }
  6558. var texture = this._gl.createTexture();
  6559. texture._baseWidth = width;
  6560. texture._baseHeight = height;
  6561. texture._width = width;
  6562. texture._height = height;
  6563. texture.references = 1;
  6564. this.updateRawTexture(texture, data, format, invertY, compression);
  6565. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6566. // Filters
  6567. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6569. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6570. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6571. texture.samplingMode = samplingMode;
  6572. this._loadedTexturesCache.push(texture);
  6573. return texture;
  6574. };
  6575. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6576. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6577. var texture = this._gl.createTexture();
  6578. texture._baseWidth = width;
  6579. texture._baseHeight = height;
  6580. if (forceExponantOfTwo) {
  6581. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6582. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6583. }
  6584. this._activeTexturesCache = [];
  6585. texture._width = width;
  6586. texture._height = height;
  6587. texture.isReady = false;
  6588. texture.generateMipMaps = generateMipMaps;
  6589. texture.references = 1;
  6590. texture.samplingMode = samplingMode;
  6591. this.updateTextureSamplingMode(samplingMode, texture);
  6592. this._loadedTexturesCache.push(texture);
  6593. return texture;
  6594. };
  6595. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6596. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6597. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6599. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6600. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6601. };
  6602. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6603. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6604. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6605. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6606. if (texture.generateMipMaps) {
  6607. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6608. }
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6610. this._activeTexturesCache = [];
  6611. texture.isReady = true;
  6612. };
  6613. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6614. if (texture._isDisabled) {
  6615. return;
  6616. }
  6617. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6618. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6619. try {
  6620. // Testing video texture support
  6621. if (this._videoTextureSupported === undefined) {
  6622. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6623. if (this._gl.getError() !== 0) {
  6624. this._videoTextureSupported = false;
  6625. }
  6626. else {
  6627. this._videoTextureSupported = true;
  6628. }
  6629. }
  6630. // Copy video through the current working canvas if video texture is not supported
  6631. if (!this._videoTextureSupported) {
  6632. if (!texture._workingCanvas) {
  6633. texture._workingCanvas = document.createElement("canvas");
  6634. texture._workingContext = texture._workingCanvas.getContext("2d");
  6635. texture._workingCanvas.width = texture._width;
  6636. texture._workingCanvas.height = texture._height;
  6637. }
  6638. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6639. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6640. }
  6641. else {
  6642. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6643. }
  6644. if (texture.generateMipMaps) {
  6645. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6646. }
  6647. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6648. this._activeTexturesCache = [];
  6649. texture.isReady = true;
  6650. }
  6651. catch (ex) {
  6652. // Something unexpected
  6653. // Let's disable the texture
  6654. texture._isDisabled = true;
  6655. }
  6656. };
  6657. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6658. // old version had a "generateMipMaps" arg instead of options.
  6659. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6660. // in the same way, generateDepthBuffer is defaulted to true
  6661. var generateMipMaps = false;
  6662. var generateDepthBuffer = true;
  6663. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6664. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6665. if (options !== undefined) {
  6666. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6667. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6668. type = options.type === undefined ? type : options.type;
  6669. if (options.samplingMode !== undefined) {
  6670. samplingMode = options.samplingMode;
  6671. }
  6672. if (type === Engine.TEXTURETYPE_FLOAT) {
  6673. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6674. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6675. }
  6676. }
  6677. var gl = this._gl;
  6678. var texture = gl.createTexture();
  6679. gl.bindTexture(gl.TEXTURE_2D, texture);
  6680. var width = size.width || size;
  6681. var height = size.height || size;
  6682. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6683. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6684. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6685. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6686. }
  6687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6688. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6691. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6692. var depthBuffer;
  6693. // Create the depth buffer
  6694. if (generateDepthBuffer) {
  6695. depthBuffer = gl.createRenderbuffer();
  6696. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6697. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6698. }
  6699. // Create the framebuffer
  6700. var framebuffer = gl.createFramebuffer();
  6701. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6702. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6703. if (generateDepthBuffer) {
  6704. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6705. }
  6706. if (generateMipMaps) {
  6707. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6708. }
  6709. // Unbind
  6710. gl.bindTexture(gl.TEXTURE_2D, null);
  6711. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6712. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6713. texture._framebuffer = framebuffer;
  6714. if (generateDepthBuffer) {
  6715. texture._depthBuffer = depthBuffer;
  6716. }
  6717. texture._width = width;
  6718. texture._height = height;
  6719. texture.isReady = true;
  6720. texture.generateMipMaps = generateMipMaps;
  6721. texture.references = 1;
  6722. texture.samplingMode = samplingMode;
  6723. this._activeTexturesCache = [];
  6724. this._loadedTexturesCache.push(texture);
  6725. return texture;
  6726. };
  6727. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6728. var _this = this;
  6729. var gl = this._gl;
  6730. var texture = gl.createTexture();
  6731. texture.isCube = true;
  6732. texture.url = rootUrl;
  6733. texture.references = 1;
  6734. this._loadedTexturesCache.push(texture);
  6735. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6736. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6737. if (isDDS) {
  6738. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6739. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6740. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6741. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6742. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6743. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6744. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6745. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6746. }
  6747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6751. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6752. _this._activeTexturesCache = [];
  6753. texture._width = info.width;
  6754. texture._height = info.height;
  6755. texture.isReady = true;
  6756. }, null, null, true);
  6757. }
  6758. else {
  6759. cascadeLoad(rootUrl, scene, function (imgs) {
  6760. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6761. var height = width;
  6762. _this._prepareWorkingCanvas();
  6763. _this._workingCanvas.width = width;
  6764. _this._workingCanvas.height = height;
  6765. var faces = [
  6766. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6767. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6768. ];
  6769. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6770. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6771. for (var index = 0; index < faces.length; index++) {
  6772. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6773. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6774. }
  6775. if (!noMipmap) {
  6776. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6777. }
  6778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6782. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6783. _this._activeTexturesCache = [];
  6784. texture._width = width;
  6785. texture._height = height;
  6786. texture.isReady = true;
  6787. }, extensions);
  6788. }
  6789. return texture;
  6790. };
  6791. Engine.prototype._releaseTexture = function (texture) {
  6792. var gl = this._gl;
  6793. if (texture._framebuffer) {
  6794. gl.deleteFramebuffer(texture._framebuffer);
  6795. }
  6796. if (texture._depthBuffer) {
  6797. gl.deleteRenderbuffer(texture._depthBuffer);
  6798. }
  6799. gl.deleteTexture(texture);
  6800. // Unbind channels
  6801. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6802. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6803. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6804. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6805. this._activeTexturesCache[channel] = null;
  6806. }
  6807. var index = this._loadedTexturesCache.indexOf(texture);
  6808. if (index !== -1) {
  6809. this._loadedTexturesCache.splice(index, 1);
  6810. }
  6811. };
  6812. Engine.prototype.bindSamplers = function (effect) {
  6813. this._gl.useProgram(effect.getProgram());
  6814. var samplers = effect.getSamplers();
  6815. for (var index = 0; index < samplers.length; index++) {
  6816. var uniform = effect.getUniform(samplers[index]);
  6817. this._gl.uniform1i(uniform, index);
  6818. }
  6819. this._currentEffect = null;
  6820. };
  6821. Engine.prototype._bindTexture = function (channel, texture) {
  6822. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6823. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6824. this._activeTexturesCache[channel] = null;
  6825. };
  6826. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6827. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6828. };
  6829. Engine.prototype.setTexture = function (channel, texture) {
  6830. if (channel < 0) {
  6831. return;
  6832. }
  6833. // Not ready?
  6834. if (!texture || !texture.isReady()) {
  6835. if (this._activeTexturesCache[channel] != null) {
  6836. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6837. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6838. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6839. this._activeTexturesCache[channel] = null;
  6840. }
  6841. return;
  6842. }
  6843. // Video
  6844. if (texture instanceof BABYLON.VideoTexture) {
  6845. if (texture.update()) {
  6846. this._activeTexturesCache[channel] = null;
  6847. }
  6848. }
  6849. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6850. texture.delayLoad();
  6851. return;
  6852. }
  6853. if (this._activeTexturesCache[channel] === texture) {
  6854. return;
  6855. }
  6856. this._activeTexturesCache[channel] = texture;
  6857. var internalTexture = texture.getInternalTexture();
  6858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6859. if (internalTexture.isCube) {
  6860. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6861. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6862. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6863. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6864. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6865. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6866. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6867. }
  6868. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6869. }
  6870. else {
  6871. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6872. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6873. internalTexture._cachedWrapU = texture.wrapU;
  6874. switch (texture.wrapU) {
  6875. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6877. break;
  6878. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6879. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6880. break;
  6881. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6882. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6883. break;
  6884. }
  6885. }
  6886. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6887. internalTexture._cachedWrapV = texture.wrapV;
  6888. switch (texture.wrapV) {
  6889. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6890. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6891. break;
  6892. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6893. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6894. break;
  6895. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6897. break;
  6898. }
  6899. }
  6900. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6901. }
  6902. };
  6903. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6904. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6905. var value = texture.anisotropicFilteringLevel;
  6906. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6907. value = 1;
  6908. }
  6909. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6910. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6911. texture._cachedAnisotropicFilteringLevel = value;
  6912. }
  6913. };
  6914. Engine.prototype.readPixels = function (x, y, width, height) {
  6915. var data = new Uint8Array(height * width * 4);
  6916. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6917. return data;
  6918. };
  6919. // Dispose
  6920. Engine.prototype.dispose = function () {
  6921. this.hideLoadingUI();
  6922. this.stopRenderLoop();
  6923. // Release scenes
  6924. while (this.scenes.length) {
  6925. this.scenes[0].dispose();
  6926. }
  6927. // Release audio engine
  6928. Engine.audioEngine.dispose();
  6929. // Release effects
  6930. for (var name in this._compiledEffects) {
  6931. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6932. }
  6933. // Unbind
  6934. for (var i in this._vertexAttribArrays) {
  6935. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6936. continue;
  6937. }
  6938. this._gl.disableVertexAttribArray(i);
  6939. }
  6940. this._gl = null;
  6941. // Events
  6942. window.removeEventListener("blur", this._onBlur);
  6943. window.removeEventListener("focus", this._onFocus);
  6944. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6945. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6946. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6947. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6948. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6949. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6950. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6951. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6952. };
  6953. // Loading screen
  6954. Engine.prototype.displayLoadingUI = function () {
  6955. this._loadingScreen.displayLoadingUI();
  6956. };
  6957. Engine.prototype.hideLoadingUI = function () {
  6958. this._loadingScreen.hideLoadingUI();
  6959. };
  6960. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6961. get: function () {
  6962. return this._loadingScreen;
  6963. },
  6964. set: function (loadingScreen) {
  6965. this._loadingScreen = loadingScreen;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6971. set: function (text) {
  6972. this._loadingScreen.loadingUIText = text;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6978. set: function (color) {
  6979. this._loadingScreen.loadingUIBackgroundColor = color;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. // FPS
  6985. Engine.prototype.getFps = function () {
  6986. return this.fps;
  6987. };
  6988. Engine.prototype.getDeltaTime = function () {
  6989. return this.deltaTime;
  6990. };
  6991. Engine.prototype._measureFps = function () {
  6992. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6993. var length = this.previousFramesDuration.length;
  6994. if (length >= 2) {
  6995. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6996. }
  6997. if (length >= this.fpsRange) {
  6998. if (length > this.fpsRange) {
  6999. this.previousFramesDuration.splice(0, 1);
  7000. length = this.previousFramesDuration.length;
  7001. }
  7002. var sum = 0;
  7003. for (var id = 0; id < length - 1; id++) {
  7004. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7005. }
  7006. this.fps = 1000.0 / (sum / (length - 1));
  7007. }
  7008. };
  7009. // Statics
  7010. Engine.isSupported = function () {
  7011. try {
  7012. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7013. if (navigator.isCocoonJS) {
  7014. return true;
  7015. }
  7016. var tempcanvas = document.createElement("canvas");
  7017. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7018. return gl != null && !!window.WebGLRenderingContext;
  7019. }
  7020. catch (e) {
  7021. return false;
  7022. }
  7023. };
  7024. // Const statics
  7025. Engine._ALPHA_DISABLE = 0;
  7026. Engine._ALPHA_ADD = 1;
  7027. Engine._ALPHA_COMBINE = 2;
  7028. Engine._ALPHA_SUBTRACT = 3;
  7029. Engine._ALPHA_MULTIPLY = 4;
  7030. Engine._ALPHA_MAXIMIZED = 5;
  7031. Engine._ALPHA_ONEONE = 6;
  7032. Engine._DELAYLOADSTATE_NONE = 0;
  7033. Engine._DELAYLOADSTATE_LOADED = 1;
  7034. Engine._DELAYLOADSTATE_LOADING = 2;
  7035. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7036. Engine._TEXTUREFORMAT_ALPHA = 0;
  7037. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7038. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7039. Engine._TEXTUREFORMAT_RGB = 4;
  7040. Engine._TEXTUREFORMAT_RGBA = 5;
  7041. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7042. Engine._TEXTURETYPE_FLOAT = 1;
  7043. // Updatable statics so stick with vars here
  7044. Engine.Epsilon = 0.001;
  7045. Engine.CollisionsEpsilon = 0.001;
  7046. Engine.CodeRepository = "src/";
  7047. Engine.ShadersRepository = "src/Shaders/";
  7048. return Engine;
  7049. })();
  7050. BABYLON.Engine = Engine;
  7051. })(BABYLON || (BABYLON = {}));
  7052. var BABYLON;
  7053. (function (BABYLON) {
  7054. /**
  7055. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7056. */
  7057. var Node = (function () {
  7058. /**
  7059. * @constructor
  7060. * @param {string} name - the name and id to be given to this node
  7061. * @param {BABYLON.Scene} the scene this node will be added to
  7062. */
  7063. function Node(name, scene) {
  7064. this.state = "";
  7065. this.animations = new Array();
  7066. this._childrenFlag = -1;
  7067. this._isEnabled = true;
  7068. this._isReady = true;
  7069. this._currentRenderId = -1;
  7070. this._parentRenderId = -1;
  7071. this.name = name;
  7072. this.id = name;
  7073. this._scene = scene;
  7074. this._initCache();
  7075. }
  7076. Node.prototype.getScene = function () {
  7077. return this._scene;
  7078. };
  7079. Node.prototype.getEngine = function () {
  7080. return this._scene.getEngine();
  7081. };
  7082. // override it in derived class
  7083. Node.prototype.getWorldMatrix = function () {
  7084. return BABYLON.Matrix.Identity();
  7085. };
  7086. // override it in derived class if you add new variables to the cache
  7087. // and call the parent class method
  7088. Node.prototype._initCache = function () {
  7089. this._cache = {};
  7090. this._cache.parent = undefined;
  7091. };
  7092. Node.prototype.updateCache = function (force) {
  7093. if (!force && this.isSynchronized())
  7094. return;
  7095. this._cache.parent = this.parent;
  7096. this._updateCache();
  7097. };
  7098. // override it in derived class if you add new variables to the cache
  7099. // and call the parent class method if !ignoreParentClass
  7100. Node.prototype._updateCache = function (ignoreParentClass) {
  7101. };
  7102. // override it in derived class if you add new variables to the cache
  7103. Node.prototype._isSynchronized = function () {
  7104. return true;
  7105. };
  7106. Node.prototype._markSyncedWithParent = function () {
  7107. this._parentRenderId = this.parent._currentRenderId;
  7108. };
  7109. Node.prototype.isSynchronizedWithParent = function () {
  7110. if (!this.parent) {
  7111. return true;
  7112. }
  7113. if (this._parentRenderId !== this.parent._currentRenderId) {
  7114. return false;
  7115. }
  7116. return this.parent.isSynchronized();
  7117. };
  7118. Node.prototype.isSynchronized = function (updateCache) {
  7119. var check = this.hasNewParent();
  7120. check = check || !this.isSynchronizedWithParent();
  7121. check = check || !this._isSynchronized();
  7122. if (updateCache)
  7123. this.updateCache(true);
  7124. return !check;
  7125. };
  7126. Node.prototype.hasNewParent = function (update) {
  7127. if (this._cache.parent === this.parent)
  7128. return false;
  7129. if (update)
  7130. this._cache.parent = this.parent;
  7131. return true;
  7132. };
  7133. /**
  7134. * Is this node ready to be used/rendered
  7135. * @return {boolean} is it ready
  7136. */
  7137. Node.prototype.isReady = function () {
  7138. return this._isReady;
  7139. };
  7140. /**
  7141. * Is this node enabled.
  7142. * If the node has a parent and is enabled, the parent will be inspected as well.
  7143. * @return {boolean} whether this node (and its parent) is enabled.
  7144. * @see setEnabled
  7145. */
  7146. Node.prototype.isEnabled = function () {
  7147. if (!this._isEnabled) {
  7148. return false;
  7149. }
  7150. if (this.parent) {
  7151. return this.parent.isEnabled();
  7152. }
  7153. return true;
  7154. };
  7155. /**
  7156. * Set the enabled state of this node.
  7157. * @param {boolean} value - the new enabled state
  7158. * @see isEnabled
  7159. */
  7160. Node.prototype.setEnabled = function (value) {
  7161. this._isEnabled = value;
  7162. };
  7163. /**
  7164. * Is this node a descendant of the given node.
  7165. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7166. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7167. * @see parent
  7168. */
  7169. Node.prototype.isDescendantOf = function (ancestor) {
  7170. if (this.parent) {
  7171. if (this.parent === ancestor) {
  7172. return true;
  7173. }
  7174. return this.parent.isDescendantOf(ancestor);
  7175. }
  7176. return false;
  7177. };
  7178. Node.prototype._getDescendants = function (list, results) {
  7179. for (var index = 0; index < list.length; index++) {
  7180. var item = list[index];
  7181. if (item.isDescendantOf(this)) {
  7182. results.push(item);
  7183. }
  7184. }
  7185. };
  7186. /**
  7187. * Will return all nodes that have this node as parent.
  7188. * @return {BABYLON.Node[]} all children nodes of all types.
  7189. */
  7190. Node.prototype.getDescendants = function () {
  7191. var results = [];
  7192. this._getDescendants(this._scene.meshes, results);
  7193. this._getDescendants(this._scene.lights, results);
  7194. this._getDescendants(this._scene.cameras, results);
  7195. return results;
  7196. };
  7197. Node.prototype._setReady = function (state) {
  7198. if (state == this._isReady) {
  7199. return;
  7200. }
  7201. if (!state) {
  7202. this._isReady = false;
  7203. return;
  7204. }
  7205. this._isReady = true;
  7206. if (this.onReady) {
  7207. this.onReady(this);
  7208. }
  7209. };
  7210. return Node;
  7211. })();
  7212. BABYLON.Node = Node;
  7213. })(BABYLON || (BABYLON = {}));
  7214. var BABYLON;
  7215. (function (BABYLON) {
  7216. var FilesInput = (function () {
  7217. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7218. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7219. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7220. this._engine = p_engine;
  7221. this._canvas = p_canvas;
  7222. this._currentScene = p_scene;
  7223. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7224. this._progressCallback = p_progressCallback;
  7225. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7226. this._textureLoadingCallback = p_textureLoadingCallback;
  7227. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7228. }
  7229. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7230. var _this = this;
  7231. if (p_elementToMonitor) {
  7232. this._elementToMonitor = p_elementToMonitor;
  7233. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7234. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7235. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7236. }
  7237. };
  7238. FilesInput.prototype.renderFunction = function () {
  7239. if (this._additionnalRenderLoopLogicCallback) {
  7240. this._additionnalRenderLoopLogicCallback();
  7241. }
  7242. if (this._currentScene) {
  7243. if (this._textureLoadingCallback) {
  7244. var remaining = this._currentScene.getWaitingItemsCount();
  7245. if (remaining > 0) {
  7246. this._textureLoadingCallback(remaining);
  7247. }
  7248. }
  7249. this._currentScene.render();
  7250. }
  7251. };
  7252. FilesInput.prototype.drag = function (e) {
  7253. e.stopPropagation();
  7254. e.preventDefault();
  7255. };
  7256. FilesInput.prototype.drop = function (eventDrop) {
  7257. eventDrop.stopPropagation();
  7258. eventDrop.preventDefault();
  7259. this.loadFiles(eventDrop);
  7260. };
  7261. FilesInput.prototype.loadFiles = function (event) {
  7262. if (this._startingProcessingFilesCallback)
  7263. this._startingProcessingFilesCallback();
  7264. // Handling data transfer via drag'n'drop
  7265. if (event && event.dataTransfer && event.dataTransfer.files) {
  7266. this._filesToLoad = event.dataTransfer.files;
  7267. }
  7268. // Handling files from input files
  7269. if (event && event.target && event.target.files) {
  7270. this._filesToLoad = event.target.files;
  7271. }
  7272. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7273. for (var i = 0; i < this._filesToLoad.length; i++) {
  7274. switch (this._filesToLoad[i].type) {
  7275. case "image/jpeg":
  7276. case "image/png":
  7277. case "image/bmp":
  7278. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7279. break;
  7280. case "image/targa":
  7281. case "image/vnd.ms-dds":
  7282. case "audio/wav":
  7283. case "audio/x-wav":
  7284. case "audio/mp3":
  7285. case "audio/mpeg":
  7286. case "audio/mpeg3":
  7287. case "audio/x-mpeg-3":
  7288. case "audio/ogg":
  7289. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7290. break;
  7291. default:
  7292. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7293. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7294. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7295. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7296. this._sceneFileToLoad = this._filesToLoad[i];
  7297. }
  7298. break;
  7299. }
  7300. }
  7301. this.reload();
  7302. }
  7303. };
  7304. FilesInput.prototype.reload = function () {
  7305. var _this = this;
  7306. var that = this;
  7307. // If a ".babylon" file has been provided
  7308. if (this._sceneFileToLoad) {
  7309. if (this._currentScene) {
  7310. if (BABYLON.Tools.errorsCount > 0) {
  7311. BABYLON.Tools.ClearLogCache();
  7312. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7313. }
  7314. this._engine.stopRenderLoop();
  7315. this._currentScene.dispose();
  7316. }
  7317. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7318. that._currentScene = newScene;
  7319. // Wait for textures and shaders to be ready
  7320. that._currentScene.executeWhenReady(function () {
  7321. // Attach camera to canvas inputs
  7322. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7323. that._currentScene.createDefaultCameraOrLight();
  7324. }
  7325. that._currentScene.activeCamera.attachControl(that._canvas);
  7326. if (that._sceneLoadedCallback) {
  7327. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7328. }
  7329. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7330. });
  7331. }, function (progress) {
  7332. if (_this._progressCallback) {
  7333. _this._progressCallback(progress);
  7334. }
  7335. });
  7336. }
  7337. else {
  7338. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7339. }
  7340. };
  7341. FilesInput.FilesTextures = new Array();
  7342. FilesInput.FilesToLoad = new Array();
  7343. return FilesInput;
  7344. })();
  7345. BABYLON.FilesInput = FilesInput;
  7346. })(BABYLON || (BABYLON = {}));
  7347. var BABYLON;
  7348. (function (BABYLON) {
  7349. var IntersectionInfo = (function () {
  7350. function IntersectionInfo(bu, bv, distance) {
  7351. this.bu = bu;
  7352. this.bv = bv;
  7353. this.distance = distance;
  7354. this.faceId = 0;
  7355. this.subMeshId = 0;
  7356. }
  7357. return IntersectionInfo;
  7358. })();
  7359. BABYLON.IntersectionInfo = IntersectionInfo;
  7360. var PickingInfo = (function () {
  7361. function PickingInfo() {
  7362. this.hit = false;
  7363. this.distance = 0;
  7364. this.pickedPoint = null;
  7365. this.pickedMesh = null;
  7366. this.bu = 0;
  7367. this.bv = 0;
  7368. this.faceId = -1;
  7369. this.subMeshId = 0;
  7370. }
  7371. // Methods
  7372. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7373. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7374. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7375. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7376. return null;
  7377. }
  7378. var indices = this.pickedMesh.getIndices();
  7379. var result;
  7380. if (useVerticesNormals) {
  7381. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7382. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7383. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7384. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7385. normal0 = normal0.scale(this.bu);
  7386. normal1 = normal1.scale(this.bv);
  7387. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7388. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7389. }
  7390. else {
  7391. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7392. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7393. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7394. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7395. var p1p2 = vertex1.subtract(vertex2);
  7396. var p3p2 = vertex3.subtract(vertex2);
  7397. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7398. }
  7399. if (useWorldCoordinates) {
  7400. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7401. }
  7402. return BABYLON.Vector3.Normalize(result);
  7403. };
  7404. PickingInfo.prototype.getTextureCoordinates = function () {
  7405. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7406. return null;
  7407. }
  7408. var indices = this.pickedMesh.getIndices();
  7409. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7410. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7411. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7412. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7413. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7414. uv1 = uv1.scale(this.bu);
  7415. uv2 = uv2.scale(this.bv);
  7416. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7417. };
  7418. return PickingInfo;
  7419. })();
  7420. BABYLON.PickingInfo = PickingInfo;
  7421. })(BABYLON || (BABYLON = {}));
  7422. var BABYLON;
  7423. (function (BABYLON) {
  7424. var BoundingSphere = (function () {
  7425. function BoundingSphere(minimum, maximum) {
  7426. this.minimum = minimum;
  7427. this.maximum = maximum;
  7428. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7429. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7430. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7431. this.radius = distance * 0.5;
  7432. this.centerWorld = BABYLON.Vector3.Zero();
  7433. this._update(BABYLON.Matrix.Identity());
  7434. }
  7435. // Methods
  7436. BoundingSphere.prototype._update = function (world) {
  7437. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7438. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7439. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7440. };
  7441. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7442. for (var i = 0; i < 6; i++) {
  7443. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7444. return false;
  7445. }
  7446. return true;
  7447. };
  7448. BoundingSphere.prototype.intersectsPoint = function (point) {
  7449. var x = this.centerWorld.x - point.x;
  7450. var y = this.centerWorld.y - point.y;
  7451. var z = this.centerWorld.z - point.z;
  7452. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7453. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7454. return false;
  7455. return true;
  7456. };
  7457. // Statics
  7458. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7459. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7460. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7461. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7462. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7463. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7464. return false;
  7465. return true;
  7466. };
  7467. return BoundingSphere;
  7468. })();
  7469. BABYLON.BoundingSphere = BoundingSphere;
  7470. })(BABYLON || (BABYLON = {}));
  7471. var BABYLON;
  7472. (function (BABYLON) {
  7473. var BoundingBox = (function () {
  7474. function BoundingBox(minimum, maximum) {
  7475. this.minimum = minimum;
  7476. this.maximum = maximum;
  7477. this.vectors = new Array();
  7478. this.vectorsWorld = new Array();
  7479. // Bounding vectors
  7480. this.vectors.push(this.minimum.clone());
  7481. this.vectors.push(this.maximum.clone());
  7482. this.vectors.push(this.minimum.clone());
  7483. this.vectors[2].x = this.maximum.x;
  7484. this.vectors.push(this.minimum.clone());
  7485. this.vectors[3].y = this.maximum.y;
  7486. this.vectors.push(this.minimum.clone());
  7487. this.vectors[4].z = this.maximum.z;
  7488. this.vectors.push(this.maximum.clone());
  7489. this.vectors[5].z = this.minimum.z;
  7490. this.vectors.push(this.maximum.clone());
  7491. this.vectors[6].x = this.minimum.x;
  7492. this.vectors.push(this.maximum.clone());
  7493. this.vectors[7].y = this.minimum.y;
  7494. // OBB
  7495. this.center = this.maximum.add(this.minimum).scale(0.5);
  7496. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7497. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7498. // World
  7499. for (var index = 0; index < this.vectors.length; index++) {
  7500. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7501. }
  7502. this.minimumWorld = BABYLON.Vector3.Zero();
  7503. this.maximumWorld = BABYLON.Vector3.Zero();
  7504. this._update(BABYLON.Matrix.Identity());
  7505. }
  7506. // Methods
  7507. BoundingBox.prototype.getWorldMatrix = function () {
  7508. return this._worldMatrix;
  7509. };
  7510. BoundingBox.prototype._update = function (world) {
  7511. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7512. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7513. for (var index = 0; index < this.vectors.length; index++) {
  7514. var v = this.vectorsWorld[index];
  7515. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7516. if (v.x < this.minimumWorld.x)
  7517. this.minimumWorld.x = v.x;
  7518. if (v.y < this.minimumWorld.y)
  7519. this.minimumWorld.y = v.y;
  7520. if (v.z < this.minimumWorld.z)
  7521. this.minimumWorld.z = v.z;
  7522. if (v.x > this.maximumWorld.x)
  7523. this.maximumWorld.x = v.x;
  7524. if (v.y > this.maximumWorld.y)
  7525. this.maximumWorld.y = v.y;
  7526. if (v.z > this.maximumWorld.z)
  7527. this.maximumWorld.z = v.z;
  7528. }
  7529. // OBB
  7530. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7531. this.center.scaleInPlace(0.5);
  7532. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7533. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7534. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7535. this._worldMatrix = world;
  7536. };
  7537. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7538. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7539. };
  7540. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7541. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7542. };
  7543. BoundingBox.prototype.intersectsPoint = function (point) {
  7544. var delta = -BABYLON.Engine.Epsilon;
  7545. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7546. return false;
  7547. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7548. return false;
  7549. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7550. return false;
  7551. return true;
  7552. };
  7553. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7554. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7555. };
  7556. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7557. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7558. return false;
  7559. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7560. return false;
  7561. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7562. return false;
  7563. return true;
  7564. };
  7565. // Statics
  7566. BoundingBox.Intersects = function (box0, box1) {
  7567. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7568. return false;
  7569. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7570. return false;
  7571. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7572. return false;
  7573. return true;
  7574. };
  7575. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7576. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7577. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7578. return (num <= (sphereRadius * sphereRadius));
  7579. };
  7580. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7581. for (var p = 0; p < 6; p++) {
  7582. for (var i = 0; i < 8; i++) {
  7583. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7584. return false;
  7585. }
  7586. }
  7587. }
  7588. return true;
  7589. };
  7590. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7591. for (var p = 0; p < 6; p++) {
  7592. var inCount = 8;
  7593. for (var i = 0; i < 8; i++) {
  7594. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7595. --inCount;
  7596. }
  7597. else {
  7598. break;
  7599. }
  7600. }
  7601. if (inCount === 0)
  7602. return false;
  7603. }
  7604. return true;
  7605. };
  7606. return BoundingBox;
  7607. })();
  7608. BABYLON.BoundingBox = BoundingBox;
  7609. })(BABYLON || (BABYLON = {}));
  7610. var BABYLON;
  7611. (function (BABYLON) {
  7612. var computeBoxExtents = function (axis, box) {
  7613. var p = BABYLON.Vector3.Dot(box.center, axis);
  7614. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7615. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7616. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7617. var r = r0 + r1 + r2;
  7618. return {
  7619. min: p - r,
  7620. max: p + r
  7621. };
  7622. };
  7623. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7624. var axisOverlap = function (axis, box0, box1) {
  7625. var result0 = computeBoxExtents(axis, box0);
  7626. var result1 = computeBoxExtents(axis, box1);
  7627. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7628. };
  7629. var BoundingInfo = (function () {
  7630. function BoundingInfo(minimum, maximum) {
  7631. this.minimum = minimum;
  7632. this.maximum = maximum;
  7633. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7634. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7635. }
  7636. // Methods
  7637. BoundingInfo.prototype._update = function (world) {
  7638. this.boundingBox._update(world);
  7639. this.boundingSphere._update(world);
  7640. };
  7641. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7642. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7643. return false;
  7644. return this.boundingBox.isInFrustum(frustumPlanes);
  7645. };
  7646. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7647. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7648. };
  7649. BoundingInfo.prototype._checkCollision = function (collider) {
  7650. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7651. };
  7652. BoundingInfo.prototype.intersectsPoint = function (point) {
  7653. if (!this.boundingSphere.centerWorld) {
  7654. return false;
  7655. }
  7656. if (!this.boundingSphere.intersectsPoint(point)) {
  7657. return false;
  7658. }
  7659. if (!this.boundingBox.intersectsPoint(point)) {
  7660. return false;
  7661. }
  7662. return true;
  7663. };
  7664. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7665. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7666. return false;
  7667. }
  7668. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7669. return false;
  7670. }
  7671. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7672. return false;
  7673. }
  7674. if (!precise) {
  7675. return true;
  7676. }
  7677. var box0 = this.boundingBox;
  7678. var box1 = boundingInfo.boundingBox;
  7679. if (!axisOverlap(box0.directions[0], box0, box1))
  7680. return false;
  7681. if (!axisOverlap(box0.directions[1], box0, box1))
  7682. return false;
  7683. if (!axisOverlap(box0.directions[2], box0, box1))
  7684. return false;
  7685. if (!axisOverlap(box1.directions[0], box0, box1))
  7686. return false;
  7687. if (!axisOverlap(box1.directions[1], box0, box1))
  7688. return false;
  7689. if (!axisOverlap(box1.directions[2], box0, box1))
  7690. return false;
  7691. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7692. return false;
  7693. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7694. return false;
  7695. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7696. return false;
  7697. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7698. return false;
  7699. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7700. return false;
  7701. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7702. return false;
  7703. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7704. return false;
  7705. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7706. return false;
  7707. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7708. return false;
  7709. return true;
  7710. };
  7711. return BoundingInfo;
  7712. })();
  7713. BABYLON.BoundingInfo = BoundingInfo;
  7714. })(BABYLON || (BABYLON = {}));
  7715. var BABYLON;
  7716. (function (BABYLON) {
  7717. var AbstractMesh = (function (_super) {
  7718. __extends(AbstractMesh, _super);
  7719. function AbstractMesh(name, scene) {
  7720. var _this = this;
  7721. _super.call(this, name, scene);
  7722. // Properties
  7723. this.definedFacingForward = true; // orientation for POV movement & rotation
  7724. this.position = new BABYLON.Vector3(0, 0, 0);
  7725. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7726. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7727. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7728. this.visibility = 1.0;
  7729. this.alphaIndex = Number.MAX_VALUE;
  7730. this.infiniteDistance = false;
  7731. this.isVisible = true;
  7732. this.isPickable = true;
  7733. this.showBoundingBox = false;
  7734. this.showSubMeshesBoundingBox = false;
  7735. this.onDispose = null;
  7736. this.isBlocker = false;
  7737. this.renderingGroupId = 0;
  7738. this.receiveShadows = false;
  7739. this.renderOutline = false;
  7740. this.outlineColor = BABYLON.Color3.Red();
  7741. this.outlineWidth = 0.02;
  7742. this.renderOverlay = false;
  7743. this.overlayColor = BABYLON.Color3.Red();
  7744. this.overlayAlpha = 0.5;
  7745. this.hasVertexAlpha = false;
  7746. this.useVertexColors = true;
  7747. this.applyFog = true;
  7748. this.computeBonesUsingShaders = true;
  7749. this.scalingDeterminant = 1;
  7750. this.useOctreeForRenderingSelection = true;
  7751. this.useOctreeForPicking = true;
  7752. this.useOctreeForCollisions = true;
  7753. this.layerMask = 0x0FFFFFFF;
  7754. this.alwaysSelectAsActiveMesh = false;
  7755. // Physics
  7756. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7757. // Collisions
  7758. this._checkCollisions = false;
  7759. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7760. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7761. this._collider = new BABYLON.Collider();
  7762. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7763. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7764. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7765. // Edges
  7766. this.edgesWidth = 1;
  7767. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7768. // Cache
  7769. this._localScaling = BABYLON.Matrix.Zero();
  7770. this._localRotation = BABYLON.Matrix.Zero();
  7771. this._localTranslation = BABYLON.Matrix.Zero();
  7772. this._localBillboard = BABYLON.Matrix.Zero();
  7773. this._localPivotScaling = BABYLON.Matrix.Zero();
  7774. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7775. this._localWorld = BABYLON.Matrix.Zero();
  7776. this._worldMatrix = BABYLON.Matrix.Zero();
  7777. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7778. this._absolutePosition = BABYLON.Vector3.Zero();
  7779. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7780. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7781. this._isDirty = false;
  7782. this._pivotMatrix = BABYLON.Matrix.Identity();
  7783. this._isDisposed = false;
  7784. this._renderId = 0;
  7785. this._intersectionsInProgress = new Array();
  7786. this._onAfterWorldMatrixUpdate = new Array();
  7787. this._isWorldMatrixFrozen = false;
  7788. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7789. if (collidedMesh === void 0) { collidedMesh = null; }
  7790. //TODO move this to the collision coordinator!
  7791. if (_this.getScene().workerCollisions)
  7792. newPosition.multiplyInPlace(_this._collider.radius);
  7793. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7794. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7795. _this.position.addInPlace(_this._diffPositionForCollisions);
  7796. }
  7797. if (_this.onCollide && collidedMesh) {
  7798. _this.onCollide(collidedMesh);
  7799. }
  7800. };
  7801. scene.addMesh(this);
  7802. }
  7803. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7804. get: function () {
  7805. return AbstractMesh._BILLBOARDMODE_NONE;
  7806. },
  7807. enumerable: true,
  7808. configurable: true
  7809. });
  7810. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7811. get: function () {
  7812. return AbstractMesh._BILLBOARDMODE_X;
  7813. },
  7814. enumerable: true,
  7815. configurable: true
  7816. });
  7817. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7818. get: function () {
  7819. return AbstractMesh._BILLBOARDMODE_Y;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7825. get: function () {
  7826. return AbstractMesh._BILLBOARDMODE_Z;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7832. get: function () {
  7833. return AbstractMesh._BILLBOARDMODE_ALL;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. // Methods
  7839. AbstractMesh.prototype.disableEdgesRendering = function () {
  7840. if (this._edgesRenderer !== undefined) {
  7841. this._edgesRenderer.dispose();
  7842. this._edgesRenderer = undefined;
  7843. }
  7844. };
  7845. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7846. if (epsilon === void 0) { epsilon = 0.95; }
  7847. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7848. this.disableEdgesRendering();
  7849. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7850. };
  7851. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7852. get: function () {
  7853. return false;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. AbstractMesh.prototype.getLOD = function (camera) {
  7859. return this;
  7860. };
  7861. AbstractMesh.prototype.getTotalVertices = function () {
  7862. return 0;
  7863. };
  7864. AbstractMesh.prototype.getIndices = function () {
  7865. return null;
  7866. };
  7867. AbstractMesh.prototype.getVerticesData = function (kind) {
  7868. return null;
  7869. };
  7870. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7871. return false;
  7872. };
  7873. AbstractMesh.prototype.getBoundingInfo = function () {
  7874. if (this._masterMesh) {
  7875. return this._masterMesh.getBoundingInfo();
  7876. }
  7877. if (!this._boundingInfo) {
  7878. this._updateBoundingInfo();
  7879. }
  7880. return this._boundingInfo;
  7881. };
  7882. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7883. get: function () {
  7884. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7885. },
  7886. enumerable: true,
  7887. configurable: true
  7888. });
  7889. AbstractMesh.prototype._preActivate = function () {
  7890. };
  7891. AbstractMesh.prototype._activate = function (renderId) {
  7892. this._renderId = renderId;
  7893. };
  7894. AbstractMesh.prototype.getWorldMatrix = function () {
  7895. if (this._masterMesh) {
  7896. return this._masterMesh.getWorldMatrix();
  7897. }
  7898. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7899. this.computeWorldMatrix();
  7900. }
  7901. return this._worldMatrix;
  7902. };
  7903. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7904. get: function () {
  7905. return this._worldMatrix;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7911. get: function () {
  7912. return this._absolutePosition;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7918. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7919. this.computeWorldMatrix(true);
  7920. this._isWorldMatrixFrozen = true;
  7921. };
  7922. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7923. this._isWorldMatrixFrozen = false;
  7924. this.computeWorldMatrix(true);
  7925. };
  7926. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7927. get: function () {
  7928. return this._isWorldMatrixFrozen;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7934. axis.normalize();
  7935. if (!this.rotationQuaternion) {
  7936. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7937. this.rotation = BABYLON.Vector3.Zero();
  7938. }
  7939. var rotationQuaternion;
  7940. if (!space || space === BABYLON.Space.LOCAL) {
  7941. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7942. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7943. }
  7944. else {
  7945. if (this.parent) {
  7946. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7947. invertParentWorldMatrix.invert();
  7948. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7949. }
  7950. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7951. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7952. }
  7953. };
  7954. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7955. var displacementVector = axis.scale(distance);
  7956. if (!space || space === BABYLON.Space.LOCAL) {
  7957. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7958. this.setPositionWithLocalVector(tempV3);
  7959. }
  7960. else {
  7961. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7962. }
  7963. };
  7964. AbstractMesh.prototype.getAbsolutePosition = function () {
  7965. this.computeWorldMatrix();
  7966. return this._absolutePosition;
  7967. };
  7968. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7969. if (!absolutePosition) {
  7970. return;
  7971. }
  7972. var absolutePositionX;
  7973. var absolutePositionY;
  7974. var absolutePositionZ;
  7975. if (absolutePosition.x === undefined) {
  7976. if (arguments.length < 3) {
  7977. return;
  7978. }
  7979. absolutePositionX = arguments[0];
  7980. absolutePositionY = arguments[1];
  7981. absolutePositionZ = arguments[2];
  7982. }
  7983. else {
  7984. absolutePositionX = absolutePosition.x;
  7985. absolutePositionY = absolutePosition.y;
  7986. absolutePositionZ = absolutePosition.z;
  7987. }
  7988. if (this.parent) {
  7989. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7990. invertParentWorldMatrix.invert();
  7991. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7992. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7993. }
  7994. else {
  7995. this.position.x = absolutePositionX;
  7996. this.position.y = absolutePositionY;
  7997. this.position.z = absolutePositionZ;
  7998. }
  7999. };
  8000. // ================================== Point of View Movement =================================
  8001. /**
  8002. * Perform relative position change from the point of view of behind the front of the mesh.
  8003. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8004. * Supports definition of mesh facing forward or backward.
  8005. * @param {number} amountRight
  8006. * @param {number} amountUp
  8007. * @param {number} amountForward
  8008. */
  8009. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8010. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8011. };
  8012. /**
  8013. * Calculate relative position change from the point of view of behind the front of the mesh.
  8014. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8015. * Supports definition of mesh facing forward or backward.
  8016. * @param {number} amountRight
  8017. * @param {number} amountUp
  8018. * @param {number} amountForward
  8019. */
  8020. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8021. var rotMatrix = new BABYLON.Matrix();
  8022. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8023. rotQuaternion.toRotationMatrix(rotMatrix);
  8024. var translationDelta = BABYLON.Vector3.Zero();
  8025. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8027. return translationDelta;
  8028. };
  8029. // ================================== Point of View Rotation =================================
  8030. /**
  8031. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8032. * Supports definition of mesh facing forward or backward.
  8033. * @param {number} flipBack
  8034. * @param {number} twirlClockwise
  8035. * @param {number} tiltRight
  8036. */
  8037. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8038. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8039. };
  8040. /**
  8041. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8042. * Supports definition of mesh facing forward or backward.
  8043. * @param {number} flipBack
  8044. * @param {number} twirlClockwise
  8045. * @param {number} tiltRight
  8046. */
  8047. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8048. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8049. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8050. };
  8051. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8052. this._pivotMatrix = matrix;
  8053. this._cache.pivotMatrixUpdated = true;
  8054. };
  8055. AbstractMesh.prototype.getPivotMatrix = function () {
  8056. return this._pivotMatrix;
  8057. };
  8058. AbstractMesh.prototype._isSynchronized = function () {
  8059. if (this._isDirty) {
  8060. return false;
  8061. }
  8062. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8063. return false;
  8064. if (this._cache.pivotMatrixUpdated) {
  8065. return false;
  8066. }
  8067. if (this.infiniteDistance) {
  8068. return false;
  8069. }
  8070. if (!this._cache.position.equals(this.position))
  8071. return false;
  8072. if (this.rotationQuaternion) {
  8073. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8074. return false;
  8075. }
  8076. else {
  8077. if (!this._cache.rotation.equals(this.rotation))
  8078. return false;
  8079. }
  8080. if (!this._cache.scaling.equals(this.scaling))
  8081. return false;
  8082. return true;
  8083. };
  8084. AbstractMesh.prototype._initCache = function () {
  8085. _super.prototype._initCache.call(this);
  8086. this._cache.localMatrixUpdated = false;
  8087. this._cache.position = BABYLON.Vector3.Zero();
  8088. this._cache.scaling = BABYLON.Vector3.Zero();
  8089. this._cache.rotation = BABYLON.Vector3.Zero();
  8090. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8091. };
  8092. AbstractMesh.prototype.markAsDirty = function (property) {
  8093. if (property === "rotation") {
  8094. this.rotationQuaternion = null;
  8095. }
  8096. this._currentRenderId = Number.MAX_VALUE;
  8097. this._isDirty = true;
  8098. };
  8099. AbstractMesh.prototype._updateBoundingInfo = function () {
  8100. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8101. this._boundingInfo._update(this.worldMatrixFromCache);
  8102. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8103. };
  8104. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8105. if (!this.subMeshes) {
  8106. return;
  8107. }
  8108. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8109. var subMesh = this.subMeshes[subIndex];
  8110. subMesh.updateBoundingInfo(matrix);
  8111. }
  8112. };
  8113. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8114. if (this._isWorldMatrixFrozen) {
  8115. return this._worldMatrix;
  8116. }
  8117. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8118. return this._worldMatrix;
  8119. }
  8120. this._cache.position.copyFrom(this.position);
  8121. this._cache.scaling.copyFrom(this.scaling);
  8122. this._cache.pivotMatrixUpdated = false;
  8123. this._currentRenderId = this.getScene().getRenderId();
  8124. this._isDirty = false;
  8125. // Scaling
  8126. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8127. // Rotation
  8128. if (this.rotationQuaternion) {
  8129. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8130. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8131. }
  8132. else {
  8133. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8134. this._cache.rotation.copyFrom(this.rotation);
  8135. }
  8136. // Translation
  8137. if (this.infiniteDistance && !this.parent) {
  8138. var camera = this.getScene().activeCamera;
  8139. if (camera) {
  8140. var cameraWorldMatrix = camera.getWorldMatrix();
  8141. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8142. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8143. }
  8144. }
  8145. else {
  8146. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8147. }
  8148. // Composing transformations
  8149. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8150. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8151. // Billboarding
  8152. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8153. var localPosition = this.position.clone();
  8154. var zero = this.getScene().activeCamera.globalPosition.clone();
  8155. if (this.parent && this.parent.position) {
  8156. localPosition.addInPlace(this.parent.position);
  8157. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8158. }
  8159. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8160. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8161. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8162. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8163. zero.y = localPosition.y + 0.001;
  8164. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8165. zero.z = localPosition.z + 0.001;
  8166. }
  8167. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8168. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8169. this._localBillboard.invert();
  8170. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8171. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8172. }
  8173. // Local world
  8174. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8175. // Parent
  8176. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8177. this._markSyncedWithParent();
  8178. if (this._meshToBoneReferal) {
  8179. if (!this._localMeshReferalTransform) {
  8180. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8181. }
  8182. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8183. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8184. }
  8185. else {
  8186. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8187. }
  8188. }
  8189. else {
  8190. this._worldMatrix.copyFrom(this._localWorld);
  8191. }
  8192. // Bounding info
  8193. this._updateBoundingInfo();
  8194. // Absolute position
  8195. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8196. // Callbacks
  8197. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8198. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8199. }
  8200. return this._worldMatrix;
  8201. };
  8202. /**
  8203. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8204. * @param func: callback function to add
  8205. */
  8206. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8207. this._onAfterWorldMatrixUpdate.push(func);
  8208. };
  8209. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8210. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8211. if (index > -1) {
  8212. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8213. }
  8214. };
  8215. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8216. this.computeWorldMatrix();
  8217. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8218. };
  8219. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8220. this.computeWorldMatrix();
  8221. var invLocalWorldMatrix = this._localWorld.clone();
  8222. invLocalWorldMatrix.invert();
  8223. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8224. };
  8225. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8226. this.computeWorldMatrix(true);
  8227. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8228. };
  8229. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8230. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8231. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8232. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8233. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8234. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8235. /// <returns>Mesh oriented towards targetMesh</returns>
  8236. yawCor = yawCor || 0; // default to zero if undefined
  8237. pitchCor = pitchCor || 0;
  8238. rollCor = rollCor || 0;
  8239. var dv = targetPoint.subtract(this.position);
  8240. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8241. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8242. var pitch = Math.atan2(dv.y, len);
  8243. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8244. };
  8245. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8246. this._meshToBoneReferal = affectedMesh;
  8247. this.parent = bone;
  8248. if (bone.getWorldMatrix().determinant() < 0) {
  8249. this.scalingDeterminant *= -1;
  8250. }
  8251. };
  8252. AbstractMesh.prototype.detachFromBone = function () {
  8253. if (this.parent.getWorldMatrix().determinant() < 0) {
  8254. this.scalingDeterminant *= -1;
  8255. }
  8256. this._meshToBoneReferal = null;
  8257. this.parent = null;
  8258. };
  8259. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8260. return this._boundingInfo.isInFrustum(frustumPlanes);
  8261. };
  8262. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8263. if (!camera) {
  8264. camera = this.getScene().activeCamera;
  8265. }
  8266. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8267. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8268. return false;
  8269. }
  8270. return true;
  8271. };
  8272. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8273. if (!this._boundingInfo || !mesh._boundingInfo) {
  8274. return false;
  8275. }
  8276. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8277. };
  8278. AbstractMesh.prototype.intersectsPoint = function (point) {
  8279. if (!this._boundingInfo) {
  8280. return false;
  8281. }
  8282. return this._boundingInfo.intersectsPoint(point);
  8283. };
  8284. // Physics
  8285. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8286. var physicsEngine = this.getScene().getPhysicsEngine();
  8287. if (!physicsEngine) {
  8288. return null;
  8289. }
  8290. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8291. if (impostor.impostor) {
  8292. // Old API
  8293. options = impostor;
  8294. impostor = impostor.impostor;
  8295. }
  8296. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8297. physicsEngine._unregisterMesh(this);
  8298. return null;
  8299. }
  8300. if (!options) {
  8301. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8302. }
  8303. else {
  8304. if (!options.mass && options.mass !== 0)
  8305. options.mass = 0;
  8306. if (!options.friction && options.friction !== 0)
  8307. options.friction = 0.2;
  8308. if (!options.restitution && options.restitution !== 0)
  8309. options.restitution = 0.2;
  8310. }
  8311. this._physicImpostor = impostor;
  8312. this._physicsMass = options.mass;
  8313. this._physicsFriction = options.friction;
  8314. this._physicRestitution = options.restitution;
  8315. return physicsEngine._registerMesh(this, impostor, options);
  8316. };
  8317. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8318. if (!this._physicImpostor) {
  8319. return BABYLON.PhysicsEngine.NoImpostor;
  8320. }
  8321. return this._physicImpostor;
  8322. };
  8323. AbstractMesh.prototype.getPhysicsMass = function () {
  8324. if (!this._physicsMass) {
  8325. return 0;
  8326. }
  8327. return this._physicsMass;
  8328. };
  8329. AbstractMesh.prototype.getPhysicsFriction = function () {
  8330. if (!this._physicsFriction) {
  8331. return 0;
  8332. }
  8333. return this._physicsFriction;
  8334. };
  8335. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8336. if (!this._physicRestitution) {
  8337. return 0;
  8338. }
  8339. return this._physicRestitution;
  8340. };
  8341. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8342. if (!camera) {
  8343. camera = this.getScene().activeCamera;
  8344. }
  8345. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8346. };
  8347. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8348. if (!camera) {
  8349. camera = this.getScene().activeCamera;
  8350. }
  8351. return this.absolutePosition.subtract(camera.position).length();
  8352. };
  8353. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8354. if (!this._physicImpostor) {
  8355. return;
  8356. }
  8357. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8358. };
  8359. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8360. if (!this._physicImpostor) {
  8361. return;
  8362. }
  8363. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8364. };
  8365. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8366. if (!this._physicImpostor) {
  8367. return;
  8368. }
  8369. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8370. };
  8371. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8372. // Collisions
  8373. get: function () {
  8374. return this._checkCollisions;
  8375. },
  8376. set: function (collisionEnabled) {
  8377. this._checkCollisions = collisionEnabled;
  8378. if (this.getScene().workerCollisions) {
  8379. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8380. }
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8386. var globalPosition = this.getAbsolutePosition();
  8387. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8388. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8389. this._collider.radius = this.ellipsoid;
  8390. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8391. };
  8392. // Submeshes octree
  8393. /**
  8394. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8395. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8396. */
  8397. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8398. if (maxCapacity === void 0) { maxCapacity = 64; }
  8399. if (maxDepth === void 0) { maxDepth = 2; }
  8400. if (!this._submeshesOctree) {
  8401. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8402. }
  8403. this.computeWorldMatrix(true);
  8404. // Update octree
  8405. var bbox = this.getBoundingInfo().boundingBox;
  8406. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8407. return this._submeshesOctree;
  8408. };
  8409. // Collisions
  8410. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8411. this._generatePointsArray();
  8412. // Transformation
  8413. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8414. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8415. subMesh._lastColliderWorldVertices = [];
  8416. subMesh._trianglePlanes = [];
  8417. var start = subMesh.verticesStart;
  8418. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8419. for (var i = start; i < end; i++) {
  8420. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8421. }
  8422. }
  8423. // Collide
  8424. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8425. if (collider.collisionFound) {
  8426. collider.collidedMesh = this;
  8427. }
  8428. };
  8429. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8430. var subMeshes;
  8431. var len;
  8432. // Octrees
  8433. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8434. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8435. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8436. len = intersections.length;
  8437. subMeshes = intersections.data;
  8438. }
  8439. else {
  8440. subMeshes = this.subMeshes;
  8441. len = subMeshes.length;
  8442. }
  8443. for (var index = 0; index < len; index++) {
  8444. var subMesh = subMeshes[index];
  8445. // Bounding test
  8446. if (len > 1 && !subMesh._checkCollision(collider))
  8447. continue;
  8448. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8449. }
  8450. };
  8451. AbstractMesh.prototype._checkCollision = function (collider) {
  8452. // Bounding box test
  8453. if (!this._boundingInfo._checkCollision(collider))
  8454. return;
  8455. // Transformation matrix
  8456. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8457. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8458. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8459. };
  8460. // Picking
  8461. AbstractMesh.prototype._generatePointsArray = function () {
  8462. return false;
  8463. };
  8464. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8465. var pickingInfo = new BABYLON.PickingInfo();
  8466. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8467. return pickingInfo;
  8468. }
  8469. if (!this._generatePointsArray()) {
  8470. return pickingInfo;
  8471. }
  8472. var intersectInfo = null;
  8473. // Octrees
  8474. var subMeshes;
  8475. var len;
  8476. if (this._submeshesOctree && this.useOctreeForPicking) {
  8477. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8478. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8479. len = intersections.length;
  8480. subMeshes = intersections.data;
  8481. }
  8482. else {
  8483. subMeshes = this.subMeshes;
  8484. len = subMeshes.length;
  8485. }
  8486. for (var index = 0; index < len; index++) {
  8487. var subMesh = subMeshes[index];
  8488. // Bounding test
  8489. if (len > 1 && !subMesh.canIntersects(ray))
  8490. continue;
  8491. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8492. if (currentIntersectInfo) {
  8493. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8494. intersectInfo = currentIntersectInfo;
  8495. intersectInfo.subMeshId = index;
  8496. if (fastCheck) {
  8497. break;
  8498. }
  8499. }
  8500. }
  8501. }
  8502. if (intersectInfo) {
  8503. // Get picked point
  8504. var world = this.getWorldMatrix();
  8505. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8506. var direction = ray.direction.clone();
  8507. direction = direction.scale(intersectInfo.distance);
  8508. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8509. var pickedPoint = worldOrigin.add(worldDirection);
  8510. // Return result
  8511. pickingInfo.hit = true;
  8512. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8513. pickingInfo.pickedPoint = pickedPoint;
  8514. pickingInfo.pickedMesh = this;
  8515. pickingInfo.bu = intersectInfo.bu;
  8516. pickingInfo.bv = intersectInfo.bv;
  8517. pickingInfo.faceId = intersectInfo.faceId;
  8518. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8519. return pickingInfo;
  8520. }
  8521. return pickingInfo;
  8522. };
  8523. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8524. return null;
  8525. };
  8526. AbstractMesh.prototype.releaseSubMeshes = function () {
  8527. if (this.subMeshes) {
  8528. while (this.subMeshes.length) {
  8529. this.subMeshes[0].dispose();
  8530. }
  8531. }
  8532. else {
  8533. this.subMeshes = new Array();
  8534. }
  8535. };
  8536. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8537. var index;
  8538. // Physics
  8539. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8540. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8541. }
  8542. // Intersections in progress
  8543. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8544. var other = this._intersectionsInProgress[index];
  8545. var pos = other._intersectionsInProgress.indexOf(this);
  8546. other._intersectionsInProgress.splice(pos, 1);
  8547. }
  8548. this._intersectionsInProgress = [];
  8549. // Edges
  8550. if (this._edgesRenderer) {
  8551. this._edgesRenderer.dispose();
  8552. this._edgesRenderer = null;
  8553. }
  8554. // SubMeshes
  8555. this.releaseSubMeshes();
  8556. // Remove from scene
  8557. this.getScene().removeMesh(this);
  8558. if (!doNotRecurse) {
  8559. // Particles
  8560. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8561. if (this.getScene().particleSystems[index].emitter === this) {
  8562. this.getScene().particleSystems[index].dispose();
  8563. index--;
  8564. }
  8565. }
  8566. // Children
  8567. var objects = this.getScene().meshes.slice(0);
  8568. for (index = 0; index < objects.length; index++) {
  8569. if (objects[index].parent === this) {
  8570. objects[index].dispose();
  8571. }
  8572. }
  8573. }
  8574. else {
  8575. for (index = 0; index < this.getScene().meshes.length; index++) {
  8576. var obj = this.getScene().meshes[index];
  8577. if (obj.parent === this) {
  8578. obj.parent = null;
  8579. obj.computeWorldMatrix(true);
  8580. }
  8581. }
  8582. }
  8583. this._onAfterWorldMatrixUpdate = [];
  8584. this._isDisposed = true;
  8585. // Callback
  8586. if (this.onDispose) {
  8587. this.onDispose();
  8588. }
  8589. };
  8590. // Statics
  8591. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8592. AbstractMesh._BILLBOARDMODE_X = 1;
  8593. AbstractMesh._BILLBOARDMODE_Y = 2;
  8594. AbstractMesh._BILLBOARDMODE_Z = 4;
  8595. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8596. return AbstractMesh;
  8597. })(BABYLON.Node);
  8598. BABYLON.AbstractMesh = AbstractMesh;
  8599. })(BABYLON || (BABYLON = {}));
  8600. var BABYLON;
  8601. (function (BABYLON) {
  8602. var Light = (function (_super) {
  8603. __extends(Light, _super);
  8604. function Light(name, scene) {
  8605. _super.call(this, name, scene);
  8606. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8607. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8608. this.intensity = 1.0;
  8609. this.range = Number.MAX_VALUE;
  8610. this.includeOnlyWithLayerMask = 0;
  8611. this.includedOnlyMeshes = new Array();
  8612. this.excludedMeshes = new Array();
  8613. this.excludeWithLayerMask = 0;
  8614. this._excludedMeshesIds = new Array();
  8615. this._includedOnlyMeshesIds = new Array();
  8616. scene.addLight(this);
  8617. }
  8618. Light.prototype.getShadowGenerator = function () {
  8619. return this._shadowGenerator;
  8620. };
  8621. Light.prototype.getAbsolutePosition = function () {
  8622. return BABYLON.Vector3.Zero();
  8623. };
  8624. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8625. };
  8626. Light.prototype._getWorldMatrix = function () {
  8627. return BABYLON.Matrix.Identity();
  8628. };
  8629. Light.prototype.canAffectMesh = function (mesh) {
  8630. if (!mesh) {
  8631. return true;
  8632. }
  8633. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8634. return false;
  8635. }
  8636. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8637. return false;
  8638. }
  8639. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8640. return false;
  8641. }
  8642. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8643. return false;
  8644. }
  8645. return true;
  8646. };
  8647. Light.prototype.getWorldMatrix = function () {
  8648. this._currentRenderId = this.getScene().getRenderId();
  8649. var worldMatrix = this._getWorldMatrix();
  8650. if (this.parent && this.parent.getWorldMatrix) {
  8651. if (!this._parentedWorldMatrix) {
  8652. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8653. }
  8654. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8655. this._markSyncedWithParent();
  8656. return this._parentedWorldMatrix;
  8657. }
  8658. return worldMatrix;
  8659. };
  8660. Light.prototype.dispose = function () {
  8661. if (this._shadowGenerator) {
  8662. this._shadowGenerator.dispose();
  8663. this._shadowGenerator = null;
  8664. }
  8665. // Remove from scene
  8666. this.getScene().removeLight(this);
  8667. };
  8668. return Light;
  8669. })(BABYLON.Node);
  8670. BABYLON.Light = Light;
  8671. })(BABYLON || (BABYLON = {}));
  8672. var BABYLON;
  8673. (function (BABYLON) {
  8674. var PointLight = (function (_super) {
  8675. __extends(PointLight, _super);
  8676. function PointLight(name, position, scene) {
  8677. _super.call(this, name, scene);
  8678. this.position = position;
  8679. }
  8680. PointLight.prototype.getAbsolutePosition = function () {
  8681. return this._transformedPosition ? this._transformedPosition : this.position;
  8682. };
  8683. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8684. if (this.parent && this.parent.getWorldMatrix) {
  8685. if (!this._transformedPosition) {
  8686. this._transformedPosition = BABYLON.Vector3.Zero();
  8687. }
  8688. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8689. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8690. return;
  8691. }
  8692. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8693. };
  8694. PointLight.prototype.getShadowGenerator = function () {
  8695. return null;
  8696. };
  8697. PointLight.prototype._getWorldMatrix = function () {
  8698. if (!this._worldMatrix) {
  8699. this._worldMatrix = BABYLON.Matrix.Identity();
  8700. }
  8701. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8702. return this._worldMatrix;
  8703. };
  8704. return PointLight;
  8705. })(BABYLON.Light);
  8706. BABYLON.PointLight = PointLight;
  8707. })(BABYLON || (BABYLON = {}));
  8708. var BABYLON;
  8709. (function (BABYLON) {
  8710. var SpotLight = (function (_super) {
  8711. __extends(SpotLight, _super);
  8712. function SpotLight(name, position, direction, angle, exponent, scene) {
  8713. _super.call(this, name, scene);
  8714. this.position = position;
  8715. this.direction = direction;
  8716. this.angle = angle;
  8717. this.exponent = exponent;
  8718. }
  8719. SpotLight.prototype.getAbsolutePosition = function () {
  8720. return this.transformedPosition ? this.transformedPosition : this.position;
  8721. };
  8722. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8723. var activeCamera = this.getScene().activeCamera;
  8724. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8725. };
  8726. SpotLight.prototype.supportsVSM = function () {
  8727. return true;
  8728. };
  8729. SpotLight.prototype.needRefreshPerFrame = function () {
  8730. return false;
  8731. };
  8732. SpotLight.prototype.setDirectionToTarget = function (target) {
  8733. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8734. return this.direction;
  8735. };
  8736. SpotLight.prototype.computeTransformedPosition = function () {
  8737. if (this.parent && this.parent.getWorldMatrix) {
  8738. if (!this.transformedPosition) {
  8739. this.transformedPosition = BABYLON.Vector3.Zero();
  8740. }
  8741. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8742. return true;
  8743. }
  8744. return false;
  8745. };
  8746. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8747. var normalizeDirection;
  8748. if (this.parent && this.parent.getWorldMatrix) {
  8749. if (!this._transformedDirection) {
  8750. this._transformedDirection = BABYLON.Vector3.Zero();
  8751. }
  8752. this.computeTransformedPosition();
  8753. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8754. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8755. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8756. }
  8757. else {
  8758. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8759. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8760. }
  8761. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8762. };
  8763. SpotLight.prototype._getWorldMatrix = function () {
  8764. if (!this._worldMatrix) {
  8765. this._worldMatrix = BABYLON.Matrix.Identity();
  8766. }
  8767. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8768. return this._worldMatrix;
  8769. };
  8770. return SpotLight;
  8771. })(BABYLON.Light);
  8772. BABYLON.SpotLight = SpotLight;
  8773. })(BABYLON || (BABYLON = {}));
  8774. var BABYLON;
  8775. (function (BABYLON) {
  8776. var HemisphericLight = (function (_super) {
  8777. __extends(HemisphericLight, _super);
  8778. function HemisphericLight(name, direction, scene) {
  8779. _super.call(this, name, scene);
  8780. this.direction = direction;
  8781. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8782. }
  8783. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8784. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8785. return this.direction;
  8786. };
  8787. HemisphericLight.prototype.getShadowGenerator = function () {
  8788. return null;
  8789. };
  8790. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8791. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8792. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8793. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8794. };
  8795. HemisphericLight.prototype._getWorldMatrix = function () {
  8796. if (!this._worldMatrix) {
  8797. this._worldMatrix = BABYLON.Matrix.Identity();
  8798. }
  8799. return this._worldMatrix;
  8800. };
  8801. return HemisphericLight;
  8802. })(BABYLON.Light);
  8803. BABYLON.HemisphericLight = HemisphericLight;
  8804. })(BABYLON || (BABYLON = {}));
  8805. var BABYLON;
  8806. (function (BABYLON) {
  8807. var DirectionalLight = (function (_super) {
  8808. __extends(DirectionalLight, _super);
  8809. function DirectionalLight(name, direction, scene) {
  8810. _super.call(this, name, scene);
  8811. this.direction = direction;
  8812. this.shadowOrthoScale = 0.5;
  8813. this.position = direction.scale(-1);
  8814. }
  8815. DirectionalLight.prototype.getAbsolutePosition = function () {
  8816. return this.transformedPosition ? this.transformedPosition : this.position;
  8817. };
  8818. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8819. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8820. return this.direction;
  8821. };
  8822. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8823. var orthoLeft = Number.MAX_VALUE;
  8824. var orthoRight = Number.MIN_VALUE;
  8825. var orthoTop = Number.MIN_VALUE;
  8826. var orthoBottom = Number.MAX_VALUE;
  8827. var tempVector3 = BABYLON.Vector3.Zero();
  8828. var activeCamera = this.getScene().activeCamera;
  8829. // Check extends
  8830. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8831. var mesh = renderList[meshIndex];
  8832. if (!mesh) {
  8833. continue;
  8834. }
  8835. var boundingInfo = mesh.getBoundingInfo();
  8836. if (!boundingInfo) {
  8837. continue;
  8838. }
  8839. var boundingBox = boundingInfo.boundingBox;
  8840. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8841. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8842. if (tempVector3.x < orthoLeft)
  8843. orthoLeft = tempVector3.x;
  8844. if (tempVector3.y < orthoBottom)
  8845. orthoBottom = tempVector3.y;
  8846. if (tempVector3.x > orthoRight)
  8847. orthoRight = tempVector3.x;
  8848. if (tempVector3.y > orthoTop)
  8849. orthoTop = tempVector3.y;
  8850. }
  8851. }
  8852. var xOffset = orthoRight - orthoLeft;
  8853. var yOffset = orthoTop - orthoBottom;
  8854. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8855. };
  8856. DirectionalLight.prototype.supportsVSM = function () {
  8857. return true;
  8858. };
  8859. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8860. return true;
  8861. };
  8862. DirectionalLight.prototype.computeTransformedPosition = function () {
  8863. if (this.parent && this.parent.getWorldMatrix) {
  8864. if (!this.transformedPosition) {
  8865. this.transformedPosition = BABYLON.Vector3.Zero();
  8866. }
  8867. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8868. return true;
  8869. }
  8870. return false;
  8871. };
  8872. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8873. if (this.parent && this.parent.getWorldMatrix) {
  8874. if (!this._transformedDirection) {
  8875. this._transformedDirection = BABYLON.Vector3.Zero();
  8876. }
  8877. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8878. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8879. return;
  8880. }
  8881. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8882. };
  8883. DirectionalLight.prototype._getWorldMatrix = function () {
  8884. if (!this._worldMatrix) {
  8885. this._worldMatrix = BABYLON.Matrix.Identity();
  8886. }
  8887. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8888. return this._worldMatrix;
  8889. };
  8890. return DirectionalLight;
  8891. })(BABYLON.Light);
  8892. BABYLON.DirectionalLight = DirectionalLight;
  8893. })(BABYLON || (BABYLON = {}));
  8894. var BABYLON;
  8895. (function (BABYLON) {
  8896. var ShadowGenerator = (function () {
  8897. function ShadowGenerator(mapSize, light) {
  8898. var _this = this;
  8899. // Members
  8900. this._filter = ShadowGenerator.FILTER_NONE;
  8901. this.blurScale = 2;
  8902. this._blurBoxOffset = 0;
  8903. this._bias = 0.00005;
  8904. this._lightDirection = BABYLON.Vector3.Zero();
  8905. this._darkness = 0;
  8906. this._transparencyShadow = false;
  8907. this._viewMatrix = BABYLON.Matrix.Zero();
  8908. this._projectionMatrix = BABYLON.Matrix.Zero();
  8909. this._transformMatrix = BABYLON.Matrix.Zero();
  8910. this._worldViewProjection = BABYLON.Matrix.Zero();
  8911. this._light = light;
  8912. this._scene = light.getScene();
  8913. this._mapSize = mapSize;
  8914. light._shadowGenerator = this;
  8915. // Render target
  8916. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8917. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8918. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8919. this._shadowMap.anisotropicFilteringLevel = 1;
  8920. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8921. this._shadowMap.renderParticles = false;
  8922. this._shadowMap.onAfterUnbind = function () {
  8923. if (!_this.useBlurVarianceShadowMap) {
  8924. return;
  8925. }
  8926. if (!_this._shadowMap2) {
  8927. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8928. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8929. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8930. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8931. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8932. _this._downSamplePostprocess.onApply = function (effect) {
  8933. effect.setTexture("textureSampler", _this._shadowMap);
  8934. };
  8935. _this.blurBoxOffset = 1;
  8936. }
  8937. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8938. };
  8939. // Custom render function
  8940. var renderSubMesh = function (subMesh) {
  8941. var mesh = subMesh.getRenderingMesh();
  8942. var scene = _this._scene;
  8943. var engine = scene.getEngine();
  8944. // Culling
  8945. engine.setState(subMesh.getMaterial().backFaceCulling);
  8946. // Managing instances
  8947. var batch = mesh._getInstancesRenderList(subMesh._id);
  8948. if (batch.mustReturn) {
  8949. return;
  8950. }
  8951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8952. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8953. engine.enableEffect(_this._effect);
  8954. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8955. var material = subMesh.getMaterial();
  8956. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8957. // Alpha test
  8958. if (material && material.needAlphaTesting()) {
  8959. var alphaTexture = material.getAlphaTestTexture();
  8960. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8961. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8962. }
  8963. // Bones
  8964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8965. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8966. }
  8967. // Draw
  8968. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8969. }
  8970. else {
  8971. // Need to reset refresh rate of the shadowMap
  8972. _this._shadowMap.resetRefreshCounter();
  8973. }
  8974. };
  8975. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8976. var index;
  8977. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8978. renderSubMesh(opaqueSubMeshes.data[index]);
  8979. }
  8980. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8981. renderSubMesh(alphaTestSubMeshes.data[index]);
  8982. }
  8983. if (_this._transparencyShadow) {
  8984. for (index = 0; index < transparentSubMeshes.length; index++) {
  8985. renderSubMesh(transparentSubMeshes.data[index]);
  8986. }
  8987. }
  8988. };
  8989. this._shadowMap.onClear = function (engine) {
  8990. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8991. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8992. }
  8993. else {
  8994. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8995. }
  8996. };
  8997. }
  8998. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8999. // Static
  9000. get: function () {
  9001. return ShadowGenerator._FILTER_NONE;
  9002. },
  9003. enumerable: true,
  9004. configurable: true
  9005. });
  9006. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9007. get: function () {
  9008. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9014. get: function () {
  9015. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9016. },
  9017. enumerable: true,
  9018. configurable: true
  9019. });
  9020. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9021. get: function () {
  9022. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9023. },
  9024. enumerable: true,
  9025. configurable: true
  9026. });
  9027. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9028. get: function () {
  9029. return this._bias;
  9030. },
  9031. set: function (bias) {
  9032. this._bias = bias;
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9038. get: function () {
  9039. return this._blurBoxOffset;
  9040. },
  9041. set: function (value) {
  9042. var _this = this;
  9043. if (this._blurBoxOffset === value) {
  9044. return;
  9045. }
  9046. this._blurBoxOffset = value;
  9047. if (this._boxBlurPostprocess) {
  9048. this._boxBlurPostprocess.dispose();
  9049. }
  9050. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9051. this._boxBlurPostprocess.onApply = function (effect) {
  9052. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9053. };
  9054. },
  9055. enumerable: true,
  9056. configurable: true
  9057. });
  9058. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9059. get: function () {
  9060. return this._filter;
  9061. },
  9062. set: function (value) {
  9063. if (this._filter === value) {
  9064. return;
  9065. }
  9066. this._filter = value;
  9067. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9068. this._shadowMap.anisotropicFilteringLevel = 16;
  9069. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9070. }
  9071. else {
  9072. this._shadowMap.anisotropicFilteringLevel = 1;
  9073. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9074. }
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9080. get: function () {
  9081. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9082. },
  9083. set: function (value) {
  9084. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9085. },
  9086. enumerable: true,
  9087. configurable: true
  9088. });
  9089. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9090. get: function () {
  9091. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9092. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9093. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9094. },
  9095. set: function (value) {
  9096. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9102. get: function () {
  9103. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9104. },
  9105. set: function (value) {
  9106. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9112. var defines = [];
  9113. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9114. defines.push("#define VSM");
  9115. }
  9116. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9117. var mesh = subMesh.getMesh();
  9118. var material = subMesh.getMaterial();
  9119. // Alpha test
  9120. if (material && material.needAlphaTesting()) {
  9121. defines.push("#define ALPHATEST");
  9122. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9123. attribs.push(BABYLON.VertexBuffer.UVKind);
  9124. defines.push("#define UV1");
  9125. }
  9126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9127. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9128. defines.push("#define UV2");
  9129. }
  9130. }
  9131. // Bones
  9132. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9133. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9134. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9135. defines.push("#define BONES");
  9136. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9137. }
  9138. // Instances
  9139. if (useInstances) {
  9140. defines.push("#define INSTANCES");
  9141. attribs.push("world0");
  9142. attribs.push("world1");
  9143. attribs.push("world2");
  9144. attribs.push("world3");
  9145. }
  9146. // Get correct effect
  9147. var join = defines.join("\n");
  9148. if (this._cachedDefines !== join) {
  9149. this._cachedDefines = join;
  9150. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9151. }
  9152. return this._effect.isReady();
  9153. };
  9154. ShadowGenerator.prototype.getShadowMap = function () {
  9155. return this._shadowMap;
  9156. };
  9157. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9158. if (this._shadowMap2) {
  9159. return this._shadowMap2;
  9160. }
  9161. return this._shadowMap;
  9162. };
  9163. ShadowGenerator.prototype.getLight = function () {
  9164. return this._light;
  9165. };
  9166. // Methods
  9167. ShadowGenerator.prototype.getTransformMatrix = function () {
  9168. var scene = this._scene;
  9169. if (this._currentRenderID === scene.getRenderId()) {
  9170. return this._transformMatrix;
  9171. }
  9172. this._currentRenderID = scene.getRenderId();
  9173. var lightPosition = this._light.position;
  9174. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9175. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9176. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9177. }
  9178. if (this._light.computeTransformedPosition()) {
  9179. lightPosition = this._light.transformedPosition;
  9180. }
  9181. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9182. this._cachedPosition = lightPosition.clone();
  9183. this._cachedDirection = this._lightDirection.clone();
  9184. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9185. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9186. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9187. }
  9188. return this._transformMatrix;
  9189. };
  9190. ShadowGenerator.prototype.getDarkness = function () {
  9191. return this._darkness;
  9192. };
  9193. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9194. if (darkness >= 1.0)
  9195. this._darkness = 1.0;
  9196. else if (darkness <= 0.0)
  9197. this._darkness = 0.0;
  9198. else
  9199. this._darkness = darkness;
  9200. };
  9201. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9202. this._transparencyShadow = hasShadow;
  9203. };
  9204. ShadowGenerator.prototype._packHalf = function (depth) {
  9205. var scale = depth * 255.0;
  9206. var fract = scale - Math.floor(scale);
  9207. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9208. };
  9209. ShadowGenerator.prototype.dispose = function () {
  9210. this._shadowMap.dispose();
  9211. if (this._shadowMap2) {
  9212. this._shadowMap2.dispose();
  9213. }
  9214. if (this._downSamplePostprocess) {
  9215. this._downSamplePostprocess.dispose();
  9216. }
  9217. if (this._boxBlurPostprocess) {
  9218. this._boxBlurPostprocess.dispose();
  9219. }
  9220. };
  9221. ShadowGenerator._FILTER_NONE = 0;
  9222. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9223. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9224. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9225. return ShadowGenerator;
  9226. })();
  9227. BABYLON.ShadowGenerator = ShadowGenerator;
  9228. })(BABYLON || (BABYLON = {}));
  9229. var BABYLON;
  9230. (function (BABYLON) {
  9231. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9232. if (boxMin.x > sphereCenter.x + sphereRadius)
  9233. return false;
  9234. if (sphereCenter.x - sphereRadius > boxMax.x)
  9235. return false;
  9236. if (boxMin.y > sphereCenter.y + sphereRadius)
  9237. return false;
  9238. if (sphereCenter.y - sphereRadius > boxMax.y)
  9239. return false;
  9240. if (boxMin.z > sphereCenter.z + sphereRadius)
  9241. return false;
  9242. if (sphereCenter.z - sphereRadius > boxMax.z)
  9243. return false;
  9244. return true;
  9245. };
  9246. var getLowestRoot = function (a, b, c, maxR) {
  9247. var determinant = b * b - 4.0 * a * c;
  9248. var result = { root: 0, found: false };
  9249. if (determinant < 0)
  9250. return result;
  9251. var sqrtD = Math.sqrt(determinant);
  9252. var r1 = (-b - sqrtD) / (2.0 * a);
  9253. var r2 = (-b + sqrtD) / (2.0 * a);
  9254. if (r1 > r2) {
  9255. var temp = r2;
  9256. r2 = r1;
  9257. r1 = temp;
  9258. }
  9259. if (r1 > 0 && r1 < maxR) {
  9260. result.root = r1;
  9261. result.found = true;
  9262. return result;
  9263. }
  9264. if (r2 > 0 && r2 < maxR) {
  9265. result.root = r2;
  9266. result.found = true;
  9267. return result;
  9268. }
  9269. return result;
  9270. };
  9271. var Collider = (function () {
  9272. function Collider() {
  9273. this.radius = new BABYLON.Vector3(1, 1, 1);
  9274. this.retry = 0;
  9275. this.basePointWorld = BABYLON.Vector3.Zero();
  9276. this.velocityWorld = BABYLON.Vector3.Zero();
  9277. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9278. this._collisionPoint = BABYLON.Vector3.Zero();
  9279. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9280. this._tempVector = BABYLON.Vector3.Zero();
  9281. this._tempVector2 = BABYLON.Vector3.Zero();
  9282. this._tempVector3 = BABYLON.Vector3.Zero();
  9283. this._tempVector4 = BABYLON.Vector3.Zero();
  9284. this._edge = BABYLON.Vector3.Zero();
  9285. this._baseToVertex = BABYLON.Vector3.Zero();
  9286. this._destinationPoint = BABYLON.Vector3.Zero();
  9287. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9288. this._displacementVector = BABYLON.Vector3.Zero();
  9289. }
  9290. // Methods
  9291. Collider.prototype._initialize = function (source, dir, e) {
  9292. this.velocity = dir;
  9293. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9294. this.basePoint = source;
  9295. source.multiplyToRef(this.radius, this.basePointWorld);
  9296. dir.multiplyToRef(this.radius, this.velocityWorld);
  9297. this.velocityWorldLength = this.velocityWorld.length();
  9298. this.epsilon = e;
  9299. this.collisionFound = false;
  9300. };
  9301. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9302. pa.subtractToRef(point, this._tempVector);
  9303. pb.subtractToRef(point, this._tempVector2);
  9304. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9305. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9306. if (d < 0)
  9307. return false;
  9308. pc.subtractToRef(point, this._tempVector3);
  9309. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9310. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9311. if (d < 0)
  9312. return false;
  9313. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9314. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9315. return d >= 0;
  9316. };
  9317. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9318. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9319. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9320. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9321. return false;
  9322. }
  9323. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9324. return false;
  9325. return true;
  9326. };
  9327. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9328. var t0;
  9329. var embeddedInPlane = false;
  9330. //defensive programming, actually not needed.
  9331. if (!trianglePlaneArray) {
  9332. trianglePlaneArray = [];
  9333. }
  9334. if (!trianglePlaneArray[faceIndex]) {
  9335. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9336. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9337. }
  9338. var trianglePlane = trianglePlaneArray[faceIndex];
  9339. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9340. return;
  9341. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9342. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9343. if (normalDotVelocity == 0) {
  9344. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9345. return;
  9346. embeddedInPlane = true;
  9347. t0 = 0;
  9348. }
  9349. else {
  9350. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9351. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9352. if (t0 > t1) {
  9353. var temp = t1;
  9354. t1 = t0;
  9355. t0 = temp;
  9356. }
  9357. if (t0 > 1.0 || t1 < 0.0)
  9358. return;
  9359. if (t0 < 0)
  9360. t0 = 0;
  9361. if (t0 > 1.0)
  9362. t0 = 1.0;
  9363. }
  9364. this._collisionPoint.copyFromFloats(0, 0, 0);
  9365. var found = false;
  9366. var t = 1.0;
  9367. if (!embeddedInPlane) {
  9368. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9369. this.velocity.scaleToRef(t0, this._tempVector);
  9370. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9371. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9372. found = true;
  9373. t = t0;
  9374. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9375. }
  9376. }
  9377. if (!found) {
  9378. var velocitySquaredLength = this.velocity.lengthSquared();
  9379. var a = velocitySquaredLength;
  9380. this.basePoint.subtractToRef(p1, this._tempVector);
  9381. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9382. var c = this._tempVector.lengthSquared() - 1.0;
  9383. var lowestRoot = getLowestRoot(a, b, c, t);
  9384. if (lowestRoot.found) {
  9385. t = lowestRoot.root;
  9386. found = true;
  9387. this._collisionPoint.copyFrom(p1);
  9388. }
  9389. this.basePoint.subtractToRef(p2, this._tempVector);
  9390. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9391. c = this._tempVector.lengthSquared() - 1.0;
  9392. lowestRoot = getLowestRoot(a, b, c, t);
  9393. if (lowestRoot.found) {
  9394. t = lowestRoot.root;
  9395. found = true;
  9396. this._collisionPoint.copyFrom(p2);
  9397. }
  9398. this.basePoint.subtractToRef(p3, this._tempVector);
  9399. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9400. c = this._tempVector.lengthSquared() - 1.0;
  9401. lowestRoot = getLowestRoot(a, b, c, t);
  9402. if (lowestRoot.found) {
  9403. t = lowestRoot.root;
  9404. found = true;
  9405. this._collisionPoint.copyFrom(p3);
  9406. }
  9407. p2.subtractToRef(p1, this._edge);
  9408. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9409. var edgeSquaredLength = this._edge.lengthSquared();
  9410. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9411. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9412. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9413. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9414. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9415. lowestRoot = getLowestRoot(a, b, c, t);
  9416. if (lowestRoot.found) {
  9417. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9418. if (f >= 0.0 && f <= 1.0) {
  9419. t = lowestRoot.root;
  9420. found = true;
  9421. this._edge.scaleInPlace(f);
  9422. p1.addToRef(this._edge, this._collisionPoint);
  9423. }
  9424. }
  9425. p3.subtractToRef(p2, this._edge);
  9426. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9427. edgeSquaredLength = this._edge.lengthSquared();
  9428. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9429. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9430. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9431. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9432. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9433. lowestRoot = getLowestRoot(a, b, c, t);
  9434. if (lowestRoot.found) {
  9435. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9436. if (f >= 0.0 && f <= 1.0) {
  9437. t = lowestRoot.root;
  9438. found = true;
  9439. this._edge.scaleInPlace(f);
  9440. p2.addToRef(this._edge, this._collisionPoint);
  9441. }
  9442. }
  9443. p1.subtractToRef(p3, this._edge);
  9444. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9445. edgeSquaredLength = this._edge.lengthSquared();
  9446. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9447. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9448. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9449. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9450. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9451. lowestRoot = getLowestRoot(a, b, c, t);
  9452. if (lowestRoot.found) {
  9453. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9454. if (f >= 0.0 && f <= 1.0) {
  9455. t = lowestRoot.root;
  9456. found = true;
  9457. this._edge.scaleInPlace(f);
  9458. p3.addToRef(this._edge, this._collisionPoint);
  9459. }
  9460. }
  9461. }
  9462. if (found) {
  9463. var distToCollision = t * this.velocity.length();
  9464. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9465. if (!this.intersectionPoint) {
  9466. this.intersectionPoint = this._collisionPoint.clone();
  9467. }
  9468. else {
  9469. this.intersectionPoint.copyFrom(this._collisionPoint);
  9470. }
  9471. this.nearestDistance = distToCollision;
  9472. this.collisionFound = true;
  9473. }
  9474. }
  9475. };
  9476. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9477. for (var i = indexStart; i < indexEnd; i += 3) {
  9478. var p1 = pts[indices[i] - decal];
  9479. var p2 = pts[indices[i + 1] - decal];
  9480. var p3 = pts[indices[i + 2] - decal];
  9481. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9482. }
  9483. };
  9484. Collider.prototype._getResponse = function (pos, vel) {
  9485. pos.addToRef(vel, this._destinationPoint);
  9486. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9487. this.basePoint.addToRef(vel, pos);
  9488. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9489. this._slidePlaneNormal.normalize();
  9490. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9491. pos.addInPlace(this._displacementVector);
  9492. this.intersectionPoint.addInPlace(this._displacementVector);
  9493. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9494. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9495. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9496. };
  9497. return Collider;
  9498. })();
  9499. BABYLON.Collider = Collider;
  9500. })(BABYLON || (BABYLON = {}));
  9501. var BABYLON;
  9502. (function (BABYLON) {
  9503. //WebWorker code will be inserted to this variable.
  9504. BABYLON.CollisionWorker = "";
  9505. (function (WorkerTaskType) {
  9506. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9507. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9508. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9509. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9510. var WorkerTaskType = BABYLON.WorkerTaskType;
  9511. (function (WorkerReplyType) {
  9512. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9513. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9514. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9515. var WorkerReplyType = BABYLON.WorkerReplyType;
  9516. var CollisionCoordinatorWorker = (function () {
  9517. function CollisionCoordinatorWorker() {
  9518. var _this = this;
  9519. this._scaledPosition = BABYLON.Vector3.Zero();
  9520. this._scaledVelocity = BABYLON.Vector3.Zero();
  9521. this.onMeshUpdated = function (mesh) {
  9522. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9523. };
  9524. this.onGeometryUpdated = function (geometry) {
  9525. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9526. };
  9527. this._afterRender = function () {
  9528. if (!_this._init)
  9529. return;
  9530. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9531. return;
  9532. }
  9533. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9534. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9535. if (_this._runningUpdated > 4) {
  9536. return;
  9537. }
  9538. ++_this._runningUpdated;
  9539. var payload = {
  9540. updatedMeshes: _this._addUpdateMeshesList,
  9541. updatedGeometries: _this._addUpdateGeometriesList,
  9542. removedGeometries: _this._toRemoveGeometryArray,
  9543. removedMeshes: _this._toRemoveMeshesArray
  9544. };
  9545. var message = {
  9546. payload: payload,
  9547. taskType: WorkerTaskType.UPDATE
  9548. };
  9549. var serializable = [];
  9550. for (var id in payload.updatedGeometries) {
  9551. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9552. //prepare transferables
  9553. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9554. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9555. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9556. }
  9557. }
  9558. _this._worker.postMessage(message, serializable);
  9559. _this._addUpdateMeshesList = {};
  9560. _this._addUpdateGeometriesList = {};
  9561. _this._toRemoveGeometryArray = [];
  9562. _this._toRemoveMeshesArray = [];
  9563. };
  9564. this._onMessageFromWorker = function (e) {
  9565. var returnData = e.data;
  9566. if (returnData.error != WorkerReplyType.SUCCESS) {
  9567. //TODO what errors can be returned from the worker?
  9568. BABYLON.Tools.Warn("error returned from worker!");
  9569. return;
  9570. }
  9571. switch (returnData.taskType) {
  9572. case WorkerTaskType.INIT:
  9573. _this._init = true;
  9574. //Update the worked with ALL of the scene's current state
  9575. _this._scene.meshes.forEach(function (mesh) {
  9576. _this.onMeshAdded(mesh);
  9577. });
  9578. _this._scene.getGeometries().forEach(function (geometry) {
  9579. _this.onGeometryAdded(geometry);
  9580. });
  9581. break;
  9582. case WorkerTaskType.UPDATE:
  9583. _this._runningUpdated--;
  9584. break;
  9585. case WorkerTaskType.COLLIDE:
  9586. _this._runningCollisionTask = false;
  9587. var returnPayload = returnData.payload;
  9588. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9589. return;
  9590. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9591. //cleanup
  9592. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9593. break;
  9594. }
  9595. };
  9596. this._collisionsCallbackArray = [];
  9597. this._init = false;
  9598. this._runningUpdated = 0;
  9599. this._runningCollisionTask = false;
  9600. this._addUpdateMeshesList = {};
  9601. this._addUpdateGeometriesList = {};
  9602. this._toRemoveGeometryArray = [];
  9603. this._toRemoveMeshesArray = [];
  9604. }
  9605. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9606. if (!this._init)
  9607. return;
  9608. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9609. return;
  9610. position.divideToRef(collider.radius, this._scaledPosition);
  9611. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9612. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9613. var payload = {
  9614. collider: {
  9615. position: this._scaledPosition.asArray(),
  9616. velocity: this._scaledVelocity.asArray(),
  9617. radius: collider.radius.asArray()
  9618. },
  9619. collisionId: collisionIndex,
  9620. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9621. maximumRetry: maximumRetry
  9622. };
  9623. var message = {
  9624. payload: payload,
  9625. taskType: WorkerTaskType.COLLIDE
  9626. };
  9627. this._worker.postMessage(message);
  9628. };
  9629. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9630. this._scene = scene;
  9631. this._scene.registerAfterRender(this._afterRender);
  9632. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9633. this._worker = new Worker(workerUrl);
  9634. this._worker.onmessage = this._onMessageFromWorker;
  9635. var message = {
  9636. payload: {},
  9637. taskType: WorkerTaskType.INIT
  9638. };
  9639. this._worker.postMessage(message);
  9640. };
  9641. CollisionCoordinatorWorker.prototype.destroy = function () {
  9642. this._scene.unregisterAfterRender(this._afterRender);
  9643. this._worker.terminate();
  9644. };
  9645. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9646. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9647. this.onMeshUpdated(mesh);
  9648. };
  9649. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9650. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9651. };
  9652. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9653. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9654. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9655. this.onGeometryUpdated(geometry);
  9656. };
  9657. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9658. this._toRemoveGeometryArray.push(geometry.id);
  9659. };
  9660. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9661. var submeshes = [];
  9662. if (mesh.subMeshes) {
  9663. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9664. return {
  9665. position: idx,
  9666. verticesStart: sm.verticesStart,
  9667. verticesCount: sm.verticesCount,
  9668. indexStart: sm.indexStart,
  9669. indexCount: sm.indexCount,
  9670. hasMaterial: !!sm.getMaterial(),
  9671. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9672. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9673. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9674. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9675. };
  9676. });
  9677. }
  9678. var geometryId = null;
  9679. if (mesh instanceof BABYLON.Mesh) {
  9680. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9681. }
  9682. else if (mesh instanceof BABYLON.InstancedMesh) {
  9683. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9684. }
  9685. return {
  9686. uniqueId: mesh.uniqueId,
  9687. id: mesh.id,
  9688. name: mesh.name,
  9689. geometryId: geometryId,
  9690. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9691. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9692. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9693. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9694. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9695. subMeshes: submeshes,
  9696. checkCollisions: mesh.checkCollisions
  9697. };
  9698. };
  9699. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9700. return {
  9701. id: geometry.id,
  9702. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9703. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9704. indices: new Int32Array(geometry.getIndices() || []),
  9705. };
  9706. };
  9707. return CollisionCoordinatorWorker;
  9708. })();
  9709. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9710. var CollisionCoordinatorLegacy = (function () {
  9711. function CollisionCoordinatorLegacy() {
  9712. this._scaledPosition = BABYLON.Vector3.Zero();
  9713. this._scaledVelocity = BABYLON.Vector3.Zero();
  9714. this._finalPosition = BABYLON.Vector3.Zero();
  9715. }
  9716. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9717. position.divideToRef(collider.radius, this._scaledPosition);
  9718. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9719. collider.collidedMesh = null;
  9720. collider.retry = 0;
  9721. collider.initialVelocity = this._scaledVelocity;
  9722. collider.initialPosition = this._scaledPosition;
  9723. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9724. this._finalPosition.multiplyInPlace(collider.radius);
  9725. //run the callback
  9726. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9727. };
  9728. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9729. this._scene = scene;
  9730. };
  9731. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9732. //Legacy need no destruction method.
  9733. };
  9734. //No update in legacy mode
  9735. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9736. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9737. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9738. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9739. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9740. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9741. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9742. if (excludedMesh === void 0) { excludedMesh = null; }
  9743. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9744. if (collider.retry >= maximumRetry) {
  9745. finalPosition.copyFrom(position);
  9746. return;
  9747. }
  9748. collider._initialize(position, velocity, closeDistance);
  9749. // Check all meshes
  9750. for (var index = 0; index < this._scene.meshes.length; index++) {
  9751. var mesh = this._scene.meshes[index];
  9752. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9753. mesh._checkCollision(collider);
  9754. }
  9755. }
  9756. if (!collider.collisionFound) {
  9757. position.addToRef(velocity, finalPosition);
  9758. return;
  9759. }
  9760. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9761. collider._getResponse(position, velocity);
  9762. }
  9763. if (velocity.length() <= closeDistance) {
  9764. finalPosition.copyFrom(position);
  9765. return;
  9766. }
  9767. collider.retry++;
  9768. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9769. };
  9770. return CollisionCoordinatorLegacy;
  9771. })();
  9772. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9773. })(BABYLON || (BABYLON = {}));
  9774. var BABYLON;
  9775. (function (BABYLON) {
  9776. var VRCameraMetrics = (function () {
  9777. function VRCameraMetrics() {
  9778. this.compensateDistorsion = true;
  9779. }
  9780. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9781. get: function () {
  9782. return this.hResolution / (2 * this.vResolution);
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9788. get: function () {
  9789. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9790. },
  9791. enumerable: true,
  9792. configurable: true
  9793. });
  9794. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9795. get: function () {
  9796. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9797. var h = (4 * meters) / this.hScreenSize;
  9798. return BABYLON.Matrix.Translation(h, 0, 0);
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9804. get: function () {
  9805. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9806. var h = (4 * meters) / this.hScreenSize;
  9807. return BABYLON.Matrix.Translation(-h, 0, 0);
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9813. get: function () {
  9814. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9820. get: function () {
  9821. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. VRCameraMetrics.GetDefault = function () {
  9827. var result = new VRCameraMetrics();
  9828. result.hResolution = 1280;
  9829. result.vResolution = 800;
  9830. result.hScreenSize = 0.149759993;
  9831. result.vScreenSize = 0.0935999975;
  9832. result.vScreenCenter = 0.0467999987,
  9833. result.eyeToScreenDistance = 0.0410000011;
  9834. result.lensSeparationDistance = 0.0635000020;
  9835. result.interpupillaryDistance = 0.0640000030;
  9836. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9837. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9838. result.postProcessScaleFactor = 1.714605507808412;
  9839. result.lensCenterOffset = 0.151976421;
  9840. return result;
  9841. };
  9842. return VRCameraMetrics;
  9843. })();
  9844. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9845. var Camera = (function (_super) {
  9846. __extends(Camera, _super);
  9847. function Camera(name, position, scene) {
  9848. _super.call(this, name, scene);
  9849. this.position = position;
  9850. // Members
  9851. this.upVector = BABYLON.Vector3.Up();
  9852. this.orthoLeft = null;
  9853. this.orthoRight = null;
  9854. this.orthoBottom = null;
  9855. this.orthoTop = null;
  9856. this.fov = 0.8;
  9857. this.minZ = 1.0;
  9858. this.maxZ = 10000.0;
  9859. this.inertia = 0.9;
  9860. this.mode = Camera.PERSPECTIVE_CAMERA;
  9861. this.isIntermediate = false;
  9862. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9863. this.layerMask = 0x0FFFFFFF;
  9864. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9865. // Camera rig members
  9866. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9867. this._rigCameras = new Array();
  9868. // Cache
  9869. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9870. this._projectionMatrix = new BABYLON.Matrix();
  9871. this._postProcesses = new Array();
  9872. this._postProcessesTakenIndices = [];
  9873. this._activeMeshes = new BABYLON.SmartArray(256);
  9874. this._globalPosition = BABYLON.Vector3.Zero();
  9875. scene.addCamera(this);
  9876. if (!scene.activeCamera) {
  9877. scene.activeCamera = this;
  9878. }
  9879. }
  9880. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9881. get: function () {
  9882. return Camera._PERSPECTIVE_CAMERA;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9888. get: function () {
  9889. return Camera._ORTHOGRAPHIC_CAMERA;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9895. get: function () {
  9896. return Camera._FOVMODE_VERTICAL_FIXED;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9902. get: function () {
  9903. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9904. },
  9905. enumerable: true,
  9906. configurable: true
  9907. });
  9908. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9909. get: function () {
  9910. return Camera._RIG_MODE_NONE;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9916. get: function () {
  9917. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9923. get: function () {
  9924. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9930. get: function () {
  9931. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9932. },
  9933. enumerable: true,
  9934. configurable: true
  9935. });
  9936. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9937. get: function () {
  9938. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9944. get: function () {
  9945. return Camera._RIG_MODE_VR;
  9946. },
  9947. enumerable: true,
  9948. configurable: true
  9949. });
  9950. Object.defineProperty(Camera.prototype, "globalPosition", {
  9951. get: function () {
  9952. return this._globalPosition;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Camera.prototype.getActiveMeshes = function () {
  9958. return this._activeMeshes;
  9959. };
  9960. Camera.prototype.isActiveMesh = function (mesh) {
  9961. return (this._activeMeshes.indexOf(mesh) !== -1);
  9962. };
  9963. //Cache
  9964. Camera.prototype._initCache = function () {
  9965. _super.prototype._initCache.call(this);
  9966. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9967. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9968. this._cache.mode = undefined;
  9969. this._cache.minZ = undefined;
  9970. this._cache.maxZ = undefined;
  9971. this._cache.fov = undefined;
  9972. this._cache.aspectRatio = undefined;
  9973. this._cache.orthoLeft = undefined;
  9974. this._cache.orthoRight = undefined;
  9975. this._cache.orthoBottom = undefined;
  9976. this._cache.orthoTop = undefined;
  9977. this._cache.renderWidth = undefined;
  9978. this._cache.renderHeight = undefined;
  9979. };
  9980. Camera.prototype._updateCache = function (ignoreParentClass) {
  9981. if (!ignoreParentClass) {
  9982. _super.prototype._updateCache.call(this);
  9983. }
  9984. var engine = this.getEngine();
  9985. this._cache.position.copyFrom(this.position);
  9986. this._cache.upVector.copyFrom(this.upVector);
  9987. this._cache.mode = this.mode;
  9988. this._cache.minZ = this.minZ;
  9989. this._cache.maxZ = this.maxZ;
  9990. this._cache.fov = this.fov;
  9991. this._cache.aspectRatio = engine.getAspectRatio(this);
  9992. this._cache.orthoLeft = this.orthoLeft;
  9993. this._cache.orthoRight = this.orthoRight;
  9994. this._cache.orthoBottom = this.orthoBottom;
  9995. this._cache.orthoTop = this.orthoTop;
  9996. this._cache.renderWidth = engine.getRenderWidth();
  9997. this._cache.renderHeight = engine.getRenderHeight();
  9998. };
  9999. Camera.prototype._updateFromScene = function () {
  10000. this.updateCache();
  10001. this._update();
  10002. };
  10003. // Synchronized
  10004. Camera.prototype._isSynchronized = function () {
  10005. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10006. };
  10007. Camera.prototype._isSynchronizedViewMatrix = function () {
  10008. if (!_super.prototype._isSynchronized.call(this))
  10009. return false;
  10010. return this._cache.position.equals(this.position)
  10011. && this._cache.upVector.equals(this.upVector)
  10012. && this.isSynchronizedWithParent();
  10013. };
  10014. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10015. var check = this._cache.mode === this.mode
  10016. && this._cache.minZ === this.minZ
  10017. && this._cache.maxZ === this.maxZ;
  10018. if (!check) {
  10019. return false;
  10020. }
  10021. var engine = this.getEngine();
  10022. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10023. check = this._cache.fov === this.fov
  10024. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10025. }
  10026. else {
  10027. check = this._cache.orthoLeft === this.orthoLeft
  10028. && this._cache.orthoRight === this.orthoRight
  10029. && this._cache.orthoBottom === this.orthoBottom
  10030. && this._cache.orthoTop === this.orthoTop
  10031. && this._cache.renderWidth === engine.getRenderWidth()
  10032. && this._cache.renderHeight === engine.getRenderHeight();
  10033. }
  10034. return check;
  10035. };
  10036. // Controls
  10037. Camera.prototype.attachControl = function (element) {
  10038. };
  10039. Camera.prototype.detachControl = function (element) {
  10040. };
  10041. Camera.prototype._update = function () {
  10042. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10043. this._updateRigCameras();
  10044. }
  10045. this._checkInputs();
  10046. };
  10047. Camera.prototype._checkInputs = function () {
  10048. };
  10049. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10050. if (insertAt === void 0) { insertAt = null; }
  10051. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10052. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10053. return 0;
  10054. }
  10055. if (insertAt == null || insertAt < 0) {
  10056. this._postProcesses.push(postProcess);
  10057. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10058. return this._postProcesses.length - 1;
  10059. }
  10060. var add = 0;
  10061. if (this._postProcesses[insertAt]) {
  10062. var start = this._postProcesses.length - 1;
  10063. for (var i = start; i >= insertAt + 1; --i) {
  10064. this._postProcesses[i + 1] = this._postProcesses[i];
  10065. }
  10066. add = 1;
  10067. }
  10068. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10069. if (this._postProcessesTakenIndices[i] < insertAt) {
  10070. continue;
  10071. }
  10072. start = this._postProcessesTakenIndices.length - 1;
  10073. for (var j = start; j >= i; --j) {
  10074. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10075. }
  10076. this._postProcessesTakenIndices[i] = insertAt;
  10077. break;
  10078. }
  10079. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10080. this._postProcessesTakenIndices.push(insertAt);
  10081. }
  10082. var result = insertAt + add;
  10083. this._postProcesses[result] = postProcess;
  10084. return result;
  10085. };
  10086. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10087. if (atIndices === void 0) { atIndices = null; }
  10088. var result = [];
  10089. if (!atIndices) {
  10090. var length = this._postProcesses.length;
  10091. for (var i = 0; i < length; i++) {
  10092. if (this._postProcesses[i] !== postProcess) {
  10093. continue;
  10094. }
  10095. delete this._postProcesses[i];
  10096. var index = this._postProcessesTakenIndices.indexOf(i);
  10097. this._postProcessesTakenIndices.splice(index, 1);
  10098. }
  10099. }
  10100. else {
  10101. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10102. for (i = 0; i < atIndices.length; i++) {
  10103. var foundPostProcess = this._postProcesses[atIndices[i]];
  10104. if (foundPostProcess !== postProcess) {
  10105. result.push(i);
  10106. continue;
  10107. }
  10108. delete this._postProcesses[atIndices[i]];
  10109. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10110. this._postProcessesTakenIndices.splice(index, 1);
  10111. }
  10112. }
  10113. return result;
  10114. };
  10115. Camera.prototype.getWorldMatrix = function () {
  10116. if (!this._worldMatrix) {
  10117. this._worldMatrix = BABYLON.Matrix.Identity();
  10118. }
  10119. var viewMatrix = this.getViewMatrix();
  10120. viewMatrix.invertToRef(this._worldMatrix);
  10121. return this._worldMatrix;
  10122. };
  10123. Camera.prototype._getViewMatrix = function () {
  10124. return BABYLON.Matrix.Identity();
  10125. };
  10126. Camera.prototype.getViewMatrix = function (force) {
  10127. this._computedViewMatrix = this._computeViewMatrix(force);
  10128. if (!force && this._isSynchronizedViewMatrix()) {
  10129. return this._computedViewMatrix;
  10130. }
  10131. if (!this.parent || !this.parent.getWorldMatrix) {
  10132. this._globalPosition.copyFrom(this.position);
  10133. }
  10134. else {
  10135. if (!this._worldMatrix) {
  10136. this._worldMatrix = BABYLON.Matrix.Identity();
  10137. }
  10138. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10139. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10140. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10141. this._computedViewMatrix.invert();
  10142. this._markSyncedWithParent();
  10143. }
  10144. this._currentRenderId = this.getScene().getRenderId();
  10145. return this._computedViewMatrix;
  10146. };
  10147. Camera.prototype._computeViewMatrix = function (force) {
  10148. if (!force && this._isSynchronizedViewMatrix()) {
  10149. return this._computedViewMatrix;
  10150. }
  10151. this._computedViewMatrix = this._getViewMatrix();
  10152. this._currentRenderId = this.getScene().getRenderId();
  10153. return this._computedViewMatrix;
  10154. };
  10155. Camera.prototype.getProjectionMatrix = function (force) {
  10156. if (!force && this._isSynchronizedProjectionMatrix()) {
  10157. return this._projectionMatrix;
  10158. }
  10159. var engine = this.getEngine();
  10160. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10161. if (this.minZ <= 0) {
  10162. this.minZ = 0.1;
  10163. }
  10164. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10165. return this._projectionMatrix;
  10166. }
  10167. var halfWidth = engine.getRenderWidth() / 2.0;
  10168. var halfHeight = engine.getRenderHeight() / 2.0;
  10169. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10170. return this._projectionMatrix;
  10171. };
  10172. Camera.prototype.dispose = function () {
  10173. // Remove from scene
  10174. this.getScene().removeCamera(this);
  10175. while (this._rigCameras.length > 0) {
  10176. this._rigCameras.pop().dispose();
  10177. }
  10178. // Postprocesses
  10179. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10180. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10181. }
  10182. };
  10183. // ---- Camera rigs section ----
  10184. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10185. while (this._rigCameras.length > 0) {
  10186. this._rigCameras.pop().dispose();
  10187. }
  10188. this.cameraRigMode = mode;
  10189. this._cameraRigParams = {};
  10190. switch (this.cameraRigMode) {
  10191. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10192. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10193. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10194. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10195. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10196. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10197. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10198. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10199. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10200. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10201. break;
  10202. }
  10203. var postProcesses = new Array();
  10204. switch (this.cameraRigMode) {
  10205. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10206. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10207. this._rigCameras[0].isIntermediate = true;
  10208. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10209. postProcesses[1].onApply = function (effect) {
  10210. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10211. };
  10212. break;
  10213. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10214. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10215. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10216. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10217. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10218. var secondCamIndex = 1 - firstCamIndex;
  10219. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10220. this._rigCameras[firstCamIndex].isIntermediate = true;
  10221. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10222. break;
  10223. case Camera.RIG_MODE_VR:
  10224. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10225. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10226. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10227. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10228. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10229. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10230. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10231. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10232. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10233. if (metrics.compensateDistorsion) {
  10234. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10235. }
  10236. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10237. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10238. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10239. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10240. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10241. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10242. if (metrics.compensateDistorsion) {
  10243. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10244. }
  10245. break;
  10246. }
  10247. this._update();
  10248. };
  10249. Camera.prototype._getVRProjectionMatrix = function () {
  10250. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10251. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10252. return this._projectionMatrix;
  10253. };
  10254. Camera.prototype.setCameraRigParameter = function (name, value) {
  10255. this._cameraRigParams[name] = value;
  10256. //provisionnally:
  10257. if (name === "interaxialDistance") {
  10258. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10259. }
  10260. };
  10261. /**
  10262. * May needs to be overridden by children so sub has required properties to be copied
  10263. */
  10264. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10265. return null;
  10266. };
  10267. /**
  10268. * May needs to be overridden by children
  10269. */
  10270. Camera.prototype._updateRigCameras = function () {
  10271. for (var i = 0; i < this._rigCameras.length; i++) {
  10272. this._rigCameras[i].minZ = this.minZ;
  10273. this._rigCameras[i].maxZ = this.maxZ;
  10274. this._rigCameras[i].fov = this.fov;
  10275. }
  10276. // only update viewport when ANAGLYPH
  10277. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10278. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10279. }
  10280. };
  10281. // Statics
  10282. Camera._PERSPECTIVE_CAMERA = 0;
  10283. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10284. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10285. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10286. Camera._RIG_MODE_NONE = 0;
  10287. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10288. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10289. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10290. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10291. Camera._RIG_MODE_VR = 20;
  10292. return Camera;
  10293. })(BABYLON.Node);
  10294. BABYLON.Camera = Camera;
  10295. })(BABYLON || (BABYLON = {}));
  10296. var BABYLON;
  10297. (function (BABYLON) {
  10298. var TargetCamera = (function (_super) {
  10299. __extends(TargetCamera, _super);
  10300. function TargetCamera(name, position, scene) {
  10301. _super.call(this, name, position, scene);
  10302. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10303. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10304. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10305. this.speed = 2.0;
  10306. this.noRotationConstraint = false;
  10307. this.lockedTarget = null;
  10308. this._currentTarget = BABYLON.Vector3.Zero();
  10309. this._viewMatrix = BABYLON.Matrix.Zero();
  10310. this._camMatrix = BABYLON.Matrix.Zero();
  10311. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10312. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10313. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10314. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10315. this._lookAtTemp = BABYLON.Matrix.Zero();
  10316. this._tempMatrix = BABYLON.Matrix.Zero();
  10317. }
  10318. TargetCamera.prototype.getFrontPosition = function (distance) {
  10319. var direction = this.getTarget().subtract(this.position);
  10320. direction.normalize();
  10321. direction.scaleInPlace(distance);
  10322. return this.globalPosition.add(direction);
  10323. };
  10324. TargetCamera.prototype._getLockedTargetPosition = function () {
  10325. if (!this.lockedTarget) {
  10326. return null;
  10327. }
  10328. return this.lockedTarget.position || this.lockedTarget;
  10329. };
  10330. // Cache
  10331. TargetCamera.prototype._initCache = function () {
  10332. _super.prototype._initCache.call(this);
  10333. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10334. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10335. };
  10336. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10337. if (!ignoreParentClass) {
  10338. _super.prototype._updateCache.call(this);
  10339. }
  10340. var lockedTargetPosition = this._getLockedTargetPosition();
  10341. if (!lockedTargetPosition) {
  10342. this._cache.lockedTarget = null;
  10343. }
  10344. else {
  10345. if (!this._cache.lockedTarget) {
  10346. this._cache.lockedTarget = lockedTargetPosition.clone();
  10347. }
  10348. else {
  10349. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10350. }
  10351. }
  10352. this._cache.rotation.copyFrom(this.rotation);
  10353. };
  10354. // Synchronized
  10355. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10356. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10357. return false;
  10358. }
  10359. var lockedTargetPosition = this._getLockedTargetPosition();
  10360. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10361. && this._cache.rotation.equals(this.rotation);
  10362. };
  10363. // Methods
  10364. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10365. var engine = this.getEngine();
  10366. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10367. };
  10368. // Target
  10369. TargetCamera.prototype.setTarget = function (target) {
  10370. this.upVector.normalize();
  10371. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10372. this._camMatrix.invert();
  10373. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10374. var vDir = target.subtract(this.position);
  10375. if (vDir.x >= 0.0) {
  10376. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10377. }
  10378. else {
  10379. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10380. }
  10381. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10382. if (isNaN(this.rotation.x)) {
  10383. this.rotation.x = 0;
  10384. }
  10385. if (isNaN(this.rotation.y)) {
  10386. this.rotation.y = 0;
  10387. }
  10388. if (isNaN(this.rotation.z)) {
  10389. this.rotation.z = 0;
  10390. }
  10391. };
  10392. TargetCamera.prototype.getTarget = function () {
  10393. return this._currentTarget;
  10394. };
  10395. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10396. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10397. };
  10398. TargetCamera.prototype._updatePosition = function () {
  10399. this.position.addInPlace(this.cameraDirection);
  10400. };
  10401. TargetCamera.prototype._checkInputs = function () {
  10402. var needToMove = this._decideIfNeedsToMove();
  10403. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10404. // Move
  10405. if (needToMove) {
  10406. this._updatePosition();
  10407. }
  10408. // Rotate
  10409. if (needToRotate) {
  10410. this.rotation.x += this.cameraRotation.x;
  10411. this.rotation.y += this.cameraRotation.y;
  10412. if (!this.noRotationConstraint) {
  10413. var limit = (Math.PI / 2) * 0.95;
  10414. if (this.rotation.x > limit)
  10415. this.rotation.x = limit;
  10416. if (this.rotation.x < -limit)
  10417. this.rotation.x = -limit;
  10418. }
  10419. }
  10420. // Inertia
  10421. if (needToMove) {
  10422. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10423. this.cameraDirection.x = 0;
  10424. }
  10425. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10426. this.cameraDirection.y = 0;
  10427. }
  10428. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10429. this.cameraDirection.z = 0;
  10430. }
  10431. this.cameraDirection.scaleInPlace(this.inertia);
  10432. }
  10433. if (needToRotate) {
  10434. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10435. this.cameraRotation.x = 0;
  10436. }
  10437. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10438. this.cameraRotation.y = 0;
  10439. }
  10440. this.cameraRotation.scaleInPlace(this.inertia);
  10441. }
  10442. _super.prototype._checkInputs.call(this);
  10443. };
  10444. TargetCamera.prototype._getViewMatrix = function () {
  10445. if (!this.lockedTarget) {
  10446. // Compute
  10447. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10448. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10449. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10450. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10451. this._lookAtTemp.invert();
  10452. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10453. }
  10454. else {
  10455. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10456. }
  10457. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10458. // Computing target and final matrix
  10459. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10460. }
  10461. else {
  10462. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10463. }
  10464. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10465. return this._viewMatrix;
  10466. };
  10467. TargetCamera.prototype._getVRViewMatrix = function () {
  10468. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10469. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10470. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10471. // Computing target and final matrix
  10472. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10473. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10474. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10475. return this._viewMatrix;
  10476. };
  10477. /**
  10478. * @override
  10479. * Override Camera.createRigCamera
  10480. */
  10481. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10482. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10483. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10484. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10485. rigCamera._cameraRigParams = {};
  10486. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10487. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10488. }
  10489. return rigCamera;
  10490. }
  10491. return null;
  10492. };
  10493. /**
  10494. * @override
  10495. * Override Camera._updateRigCameras
  10496. */
  10497. TargetCamera.prototype._updateRigCameras = function () {
  10498. switch (this.cameraRigMode) {
  10499. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10500. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10501. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10503. case BABYLON.Camera.RIG_MODE_VR:
  10504. var camLeft = this._rigCameras[0];
  10505. var camRight = this._rigCameras[1];
  10506. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10507. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10508. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10509. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10510. camLeft.position.copyFrom(this.position);
  10511. camRight.position.copyFrom(this.position);
  10512. }
  10513. else {
  10514. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10515. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10516. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10517. camLeft.setTarget(this.getTarget());
  10518. camRight.setTarget(this.getTarget());
  10519. }
  10520. break;
  10521. }
  10522. _super.prototype._updateRigCameras.call(this);
  10523. };
  10524. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10525. if (!this._rigCamTransformMatrix) {
  10526. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10527. }
  10528. var target = this.getTarget();
  10529. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10530. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10531. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10532. };
  10533. return TargetCamera;
  10534. })(BABYLON.Camera);
  10535. BABYLON.TargetCamera = TargetCamera;
  10536. })(BABYLON || (BABYLON = {}));
  10537. var BABYLON;
  10538. (function (BABYLON) {
  10539. var FreeCamera = (function (_super) {
  10540. __extends(FreeCamera, _super);
  10541. function FreeCamera(name, position, scene) {
  10542. var _this = this;
  10543. _super.call(this, name, position, scene);
  10544. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10545. this.keysUp = [38];
  10546. this.keysDown = [40];
  10547. this.keysLeft = [37];
  10548. this.keysRight = [39];
  10549. this.checkCollisions = false;
  10550. this.applyGravity = false;
  10551. this.angularSensibility = 2000.0;
  10552. this._keys = [];
  10553. this._collider = new BABYLON.Collider();
  10554. this._needMoveForGravity = false;
  10555. this._oldPosition = BABYLON.Vector3.Zero();
  10556. this._diffPosition = BABYLON.Vector3.Zero();
  10557. this._newPosition = BABYLON.Vector3.Zero();
  10558. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10559. if (collidedMesh === void 0) { collidedMesh = null; }
  10560. //TODO move this to the collision coordinator!
  10561. if (_this.getScene().workerCollisions)
  10562. newPosition.multiplyInPlace(_this._collider.radius);
  10563. var updatePosition = function (newPos) {
  10564. _this._newPosition.copyFrom(newPos);
  10565. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10566. var oldPosition = _this.position.clone();
  10567. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10568. _this.position.addInPlace(_this._diffPosition);
  10569. if (_this.onCollide && collidedMesh) {
  10570. _this.onCollide(collidedMesh);
  10571. }
  10572. }
  10573. };
  10574. updatePosition(newPosition);
  10575. };
  10576. }
  10577. // Controls
  10578. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10579. var _this = this;
  10580. var previousPosition;
  10581. var engine = this.getEngine();
  10582. if (this._attachedElement) {
  10583. return;
  10584. }
  10585. this._attachedElement = element;
  10586. if (this._onMouseDown === undefined) {
  10587. this._onMouseDown = function (evt) {
  10588. previousPosition = {
  10589. x: evt.clientX,
  10590. y: evt.clientY
  10591. };
  10592. if (!noPreventDefault) {
  10593. evt.preventDefault();
  10594. }
  10595. };
  10596. this._onMouseUp = function (evt) {
  10597. previousPosition = null;
  10598. if (!noPreventDefault) {
  10599. evt.preventDefault();
  10600. }
  10601. };
  10602. this._onMouseOut = function (evt) {
  10603. previousPosition = null;
  10604. _this._keys = [];
  10605. if (!noPreventDefault) {
  10606. evt.preventDefault();
  10607. }
  10608. };
  10609. this._onMouseMove = function (evt) {
  10610. if (!previousPosition && !engine.isPointerLock) {
  10611. return;
  10612. }
  10613. var offsetX;
  10614. var offsetY;
  10615. if (!engine.isPointerLock) {
  10616. offsetX = evt.clientX - previousPosition.x;
  10617. offsetY = evt.clientY - previousPosition.y;
  10618. }
  10619. else {
  10620. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10621. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10622. }
  10623. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10624. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10625. previousPosition = {
  10626. x: evt.clientX,
  10627. y: evt.clientY
  10628. };
  10629. if (!noPreventDefault) {
  10630. evt.preventDefault();
  10631. }
  10632. };
  10633. this._onKeyDown = function (evt) {
  10634. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10635. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10636. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10637. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10638. var index = _this._keys.indexOf(evt.keyCode);
  10639. if (index === -1) {
  10640. _this._keys.push(evt.keyCode);
  10641. }
  10642. if (!noPreventDefault) {
  10643. evt.preventDefault();
  10644. }
  10645. }
  10646. };
  10647. this._onKeyUp = function (evt) {
  10648. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10649. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10650. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10651. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10652. var index = _this._keys.indexOf(evt.keyCode);
  10653. if (index >= 0) {
  10654. _this._keys.splice(index, 1);
  10655. }
  10656. if (!noPreventDefault) {
  10657. evt.preventDefault();
  10658. }
  10659. }
  10660. };
  10661. this._onLostFocus = function () {
  10662. _this._keys = [];
  10663. };
  10664. this._reset = function () {
  10665. _this._keys = [];
  10666. previousPosition = null;
  10667. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10668. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10669. };
  10670. }
  10671. element.addEventListener("mousedown", this._onMouseDown, false);
  10672. element.addEventListener("mouseup", this._onMouseUp, false);
  10673. element.addEventListener("mouseout", this._onMouseOut, false);
  10674. element.addEventListener("mousemove", this._onMouseMove, false);
  10675. BABYLON.Tools.RegisterTopRootEvents([
  10676. { name: "keydown", handler: this._onKeyDown },
  10677. { name: "keyup", handler: this._onKeyUp },
  10678. { name: "blur", handler: this._onLostFocus }
  10679. ]);
  10680. };
  10681. FreeCamera.prototype.detachControl = function (element) {
  10682. if (this._attachedElement != element) {
  10683. return;
  10684. }
  10685. element.removeEventListener("mousedown", this._onMouseDown);
  10686. element.removeEventListener("mouseup", this._onMouseUp);
  10687. element.removeEventListener("mouseout", this._onMouseOut);
  10688. element.removeEventListener("mousemove", this._onMouseMove);
  10689. BABYLON.Tools.UnregisterTopRootEvents([
  10690. { name: "keydown", handler: this._onKeyDown },
  10691. { name: "keyup", handler: this._onKeyUp },
  10692. { name: "blur", handler: this._onLostFocus }
  10693. ]);
  10694. this._attachedElement = null;
  10695. if (this._reset) {
  10696. this._reset();
  10697. }
  10698. };
  10699. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10700. var globalPosition;
  10701. if (this.parent) {
  10702. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10703. }
  10704. else {
  10705. globalPosition = this.position;
  10706. }
  10707. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10708. this._collider.radius = this.ellipsoid;
  10709. //add gravity to the velocity to prevent the dual-collision checking
  10710. if (this.applyGravity) {
  10711. velocity.addInPlace(this.getScene().gravity);
  10712. }
  10713. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10714. };
  10715. FreeCamera.prototype._checkInputs = function () {
  10716. if (!this._localDirection) {
  10717. this._localDirection = BABYLON.Vector3.Zero();
  10718. this._transformedDirection = BABYLON.Vector3.Zero();
  10719. }
  10720. // Keyboard
  10721. for (var index = 0; index < this._keys.length; index++) {
  10722. var keyCode = this._keys[index];
  10723. var speed = this._computeLocalCameraSpeed();
  10724. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10725. this._localDirection.copyFromFloats(-speed, 0, 0);
  10726. }
  10727. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10728. this._localDirection.copyFromFloats(0, 0, speed);
  10729. }
  10730. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10731. this._localDirection.copyFromFloats(speed, 0, 0);
  10732. }
  10733. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10734. this._localDirection.copyFromFloats(0, 0, -speed);
  10735. }
  10736. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10737. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10738. this.cameraDirection.addInPlace(this._transformedDirection);
  10739. }
  10740. _super.prototype._checkInputs.call(this);
  10741. };
  10742. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10743. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10744. };
  10745. FreeCamera.prototype._updatePosition = function () {
  10746. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10747. this._collideWithWorld(this.cameraDirection);
  10748. }
  10749. else {
  10750. this.position.addInPlace(this.cameraDirection);
  10751. }
  10752. };
  10753. return FreeCamera;
  10754. })(BABYLON.TargetCamera);
  10755. BABYLON.FreeCamera = FreeCamera;
  10756. })(BABYLON || (BABYLON = {}));
  10757. var BABYLON;
  10758. (function (BABYLON) {
  10759. var FollowCamera = (function (_super) {
  10760. __extends(FollowCamera, _super);
  10761. function FollowCamera(name, position, scene) {
  10762. _super.call(this, name, position, scene);
  10763. this.radius = 12;
  10764. this.rotationOffset = 0;
  10765. this.heightOffset = 4;
  10766. this.cameraAcceleration = 0.05;
  10767. this.maxCameraSpeed = 20;
  10768. }
  10769. FollowCamera.prototype.getRadians = function (degrees) {
  10770. return degrees * Math.PI / 180;
  10771. };
  10772. FollowCamera.prototype.follow = function (cameraTarget) {
  10773. if (!cameraTarget)
  10774. return;
  10775. var yRotation;
  10776. if (cameraTarget.rotationQuaternion) {
  10777. var rotMatrix = new BABYLON.Matrix();
  10778. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10779. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10780. }
  10781. else {
  10782. yRotation = cameraTarget.rotation.y;
  10783. }
  10784. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10785. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10786. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10787. var dx = targetX - this.position.x;
  10788. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10789. var dz = (targetZ) - this.position.z;
  10790. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10791. var vy = dy * this.cameraAcceleration;
  10792. var vz = dz * this.cameraAcceleration * 2;
  10793. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10794. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10795. }
  10796. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10797. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10798. }
  10799. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10800. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10801. }
  10802. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10803. this.setTarget(cameraTarget.position);
  10804. };
  10805. FollowCamera.prototype._checkInputs = function () {
  10806. _super.prototype._checkInputs.call(this);
  10807. this.follow(this.target);
  10808. };
  10809. return FollowCamera;
  10810. })(BABYLON.TargetCamera);
  10811. BABYLON.FollowCamera = FollowCamera;
  10812. var ArcFollowCamera = (function (_super) {
  10813. __extends(ArcFollowCamera, _super);
  10814. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10815. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10816. this.alpha = alpha;
  10817. this.beta = beta;
  10818. this.radius = radius;
  10819. this.target = target;
  10820. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10821. this.follow();
  10822. }
  10823. ArcFollowCamera.prototype.follow = function () {
  10824. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10825. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10826. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10827. this.position = this.target.position.add(this._cartesianCoordinates);
  10828. this.setTarget(this.target.position);
  10829. };
  10830. ArcFollowCamera.prototype._checkInputs = function () {
  10831. _super.prototype._checkInputs.call(this);
  10832. this.follow();
  10833. };
  10834. return ArcFollowCamera;
  10835. })(BABYLON.TargetCamera);
  10836. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10837. })(BABYLON || (BABYLON = {}));
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. // We're mainly based on the logic defined into the FreeCamera code
  10841. var TouchCamera = (function (_super) {
  10842. __extends(TouchCamera, _super);
  10843. function TouchCamera(name, position, scene) {
  10844. _super.call(this, name, position, scene);
  10845. this._offsetX = null;
  10846. this._offsetY = null;
  10847. this._pointerCount = 0;
  10848. this._pointerPressed = [];
  10849. this.angularSensibility = 200000.0;
  10850. this.moveSensibility = 500.0;
  10851. }
  10852. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10853. var _this = this;
  10854. var previousPosition;
  10855. if (this._attachedCanvas) {
  10856. return;
  10857. }
  10858. this._attachedCanvas = canvas;
  10859. if (this._onPointerDown === undefined) {
  10860. this._onPointerDown = function (evt) {
  10861. if (!noPreventDefault) {
  10862. evt.preventDefault();
  10863. }
  10864. _this._pointerPressed.push(evt.pointerId);
  10865. if (_this._pointerPressed.length !== 1) {
  10866. return;
  10867. }
  10868. previousPosition = {
  10869. x: evt.clientX,
  10870. y: evt.clientY
  10871. };
  10872. };
  10873. this._onPointerUp = function (evt) {
  10874. if (!noPreventDefault) {
  10875. evt.preventDefault();
  10876. }
  10877. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10878. if (index === -1) {
  10879. return;
  10880. }
  10881. _this._pointerPressed.splice(index, 1);
  10882. if (index != 0) {
  10883. return;
  10884. }
  10885. previousPosition = null;
  10886. _this._offsetX = null;
  10887. _this._offsetY = null;
  10888. };
  10889. this._onPointerMove = function (evt) {
  10890. if (!noPreventDefault) {
  10891. evt.preventDefault();
  10892. }
  10893. if (!previousPosition) {
  10894. return;
  10895. }
  10896. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10897. if (index != 0) {
  10898. return;
  10899. }
  10900. _this._offsetX = evt.clientX - previousPosition.x;
  10901. _this._offsetY = -(evt.clientY - previousPosition.y);
  10902. };
  10903. this._onLostFocus = function () {
  10904. _this._offsetX = null;
  10905. _this._offsetY = null;
  10906. };
  10907. }
  10908. canvas.addEventListener("pointerdown", this._onPointerDown);
  10909. canvas.addEventListener("pointerup", this._onPointerUp);
  10910. canvas.addEventListener("pointerout", this._onPointerUp);
  10911. canvas.addEventListener("pointermove", this._onPointerMove);
  10912. BABYLON.Tools.RegisterTopRootEvents([
  10913. { name: "blur", handler: this._onLostFocus }
  10914. ]);
  10915. };
  10916. TouchCamera.prototype.detachControl = function (canvas) {
  10917. if (this._attachedCanvas != canvas) {
  10918. return;
  10919. }
  10920. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10921. canvas.removeEventListener("pointerup", this._onPointerUp);
  10922. canvas.removeEventListener("pointerout", this._onPointerUp);
  10923. canvas.removeEventListener("pointermove", this._onPointerMove);
  10924. BABYLON.Tools.UnregisterTopRootEvents([
  10925. { name: "blur", handler: this._onLostFocus }
  10926. ]);
  10927. this._attachedCanvas = null;
  10928. };
  10929. TouchCamera.prototype._checkInputs = function () {
  10930. if (this._offsetX) {
  10931. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10932. if (this._pointerPressed.length > 1) {
  10933. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10934. }
  10935. else {
  10936. var speed = this._computeLocalCameraSpeed();
  10937. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10938. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10939. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10940. }
  10941. }
  10942. _super.prototype._checkInputs.call(this);
  10943. };
  10944. return TouchCamera;
  10945. })(BABYLON.FreeCamera);
  10946. BABYLON.TouchCamera = TouchCamera;
  10947. })(BABYLON || (BABYLON = {}));
  10948. var BABYLON;
  10949. (function (BABYLON) {
  10950. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10951. var ArcRotateCamera = (function (_super) {
  10952. __extends(ArcRotateCamera, _super);
  10953. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10954. var _this = this;
  10955. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10956. this.alpha = alpha;
  10957. this.beta = beta;
  10958. this.radius = radius;
  10959. this.target = target;
  10960. this.inertialAlphaOffset = 0;
  10961. this.inertialBetaOffset = 0;
  10962. this.inertialRadiusOffset = 0;
  10963. this.lowerAlphaLimit = null;
  10964. this.upperAlphaLimit = null;
  10965. this.lowerBetaLimit = 0.01;
  10966. this.upperBetaLimit = Math.PI;
  10967. this.lowerRadiusLimit = null;
  10968. this.upperRadiusLimit = null;
  10969. this.angularSensibilityX = 1000.0;
  10970. this.angularSensibilityY = 1000.0;
  10971. this.wheelPrecision = 3.0;
  10972. this.pinchPrecision = 2.0;
  10973. this.panningSensibility = 50.0;
  10974. this.inertialPanningX = 0;
  10975. this.inertialPanningY = 0;
  10976. this.keysUp = [38];
  10977. this.keysDown = [40];
  10978. this.keysLeft = [37];
  10979. this.keysRight = [39];
  10980. this.zoomOnFactor = 1;
  10981. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10982. this.pinchInwards = true;
  10983. this.allowUpsideDown = true;
  10984. this._keys = [];
  10985. this._viewMatrix = new BABYLON.Matrix();
  10986. this._isRightClick = false;
  10987. this._isCtrlPushed = false;
  10988. this.checkCollisions = false;
  10989. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10990. this._collider = new BABYLON.Collider();
  10991. this._previousPosition = BABYLON.Vector3.Zero();
  10992. this._collisionVelocity = BABYLON.Vector3.Zero();
  10993. this._newPosition = BABYLON.Vector3.Zero();
  10994. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10995. if (collidedMesh === void 0) { collidedMesh = null; }
  10996. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10997. newPosition.multiplyInPlace(_this._collider.radius);
  10998. }
  10999. if (!collidedMesh) {
  11000. _this._previousPosition.copyFrom(_this.position);
  11001. }
  11002. else {
  11003. _this.setPosition(_this.position);
  11004. if (_this.onCollide) {
  11005. _this.onCollide(collidedMesh);
  11006. }
  11007. }
  11008. // Recompute because of constraints
  11009. var cosa = Math.cos(_this.alpha);
  11010. var sina = Math.sin(_this.alpha);
  11011. var cosb = Math.cos(_this.beta);
  11012. var sinb = Math.sin(_this.beta);
  11013. var target = _this._getTargetPosition();
  11014. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11015. _this.position.copyFrom(_this._newPosition);
  11016. var up = _this.upVector;
  11017. if (_this.allowUpsideDown && _this.beta < 0) {
  11018. var up = up.clone();
  11019. up = up.negate();
  11020. }
  11021. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11022. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11023. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11024. _this._collisionTriggered = false;
  11025. };
  11026. if (!this.target) {
  11027. this.target = BABYLON.Vector3.Zero();
  11028. }
  11029. this.getViewMatrix();
  11030. }
  11031. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11032. //deprecated angularSensibility support
  11033. get: function () {
  11034. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11035. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11036. },
  11037. //deprecated angularSensibility support
  11038. set: function (value) {
  11039. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11040. this.angularSensibilityX = value;
  11041. this.angularSensibilityY = value;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. ArcRotateCamera.prototype._getTargetPosition = function () {
  11047. return this.target.position || this.target;
  11048. };
  11049. // Cache
  11050. ArcRotateCamera.prototype._initCache = function () {
  11051. _super.prototype._initCache.call(this);
  11052. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11053. this._cache.alpha = undefined;
  11054. this._cache.beta = undefined;
  11055. this._cache.radius = undefined;
  11056. this._cache.targetScreenOffset = undefined;
  11057. };
  11058. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11059. if (!ignoreParentClass) {
  11060. _super.prototype._updateCache.call(this);
  11061. }
  11062. this._cache.target.copyFrom(this._getTargetPosition());
  11063. this._cache.alpha = this.alpha;
  11064. this._cache.beta = this.beta;
  11065. this._cache.radius = this.radius;
  11066. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11067. };
  11068. // Synchronized
  11069. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11070. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11071. return false;
  11072. return this._cache.target.equals(this._getTargetPosition())
  11073. && this._cache.alpha === this.alpha
  11074. && this._cache.beta === this.beta
  11075. && this._cache.radius === this.radius
  11076. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11077. };
  11078. // Methods
  11079. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11080. var _this = this;
  11081. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11082. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11083. var previousPinchDistance = 0;
  11084. var pointers = new BABYLON.SmartCollection();
  11085. if (this._attachedElement) {
  11086. return;
  11087. }
  11088. this._attachedElement = element;
  11089. var engine = this.getEngine();
  11090. if (this._onPointerDown === undefined) {
  11091. this._onPointerDown = function (evt) {
  11092. // Manage panning with right click
  11093. _this._isRightClick = evt.button === 2 ? true : false;
  11094. // manage pointers
  11095. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11096. cacheSoloPointer = pointers.item(evt.pointerId);
  11097. if (!noPreventDefault) {
  11098. evt.preventDefault();
  11099. }
  11100. };
  11101. this._onPointerUp = function (evt) {
  11102. cacheSoloPointer = null;
  11103. previousPinchDistance = 0;
  11104. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11105. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11106. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11107. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11108. pointers.empty();
  11109. if (!noPreventDefault) {
  11110. evt.preventDefault();
  11111. }
  11112. };
  11113. this._onContextMenu = function (evt) {
  11114. evt.preventDefault();
  11115. };
  11116. this._onPointerMove = function (evt) {
  11117. if (!noPreventDefault) {
  11118. evt.preventDefault();
  11119. }
  11120. switch (pointers.count) {
  11121. case 1:
  11122. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11123. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11124. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11125. }
  11126. else {
  11127. var offsetX = evt.clientX - cacheSoloPointer.x;
  11128. var offsetY = evt.clientY - cacheSoloPointer.y;
  11129. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11130. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11131. }
  11132. cacheSoloPointer.x = evt.clientX;
  11133. cacheSoloPointer.y = evt.clientY;
  11134. break;
  11135. case 2:
  11136. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11137. pointers.item(evt.pointerId).x = evt.clientX;
  11138. pointers.item(evt.pointerId).y = evt.clientY;
  11139. var direction = _this.pinchInwards ? 1 : -1;
  11140. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11141. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11142. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11143. if (previousPinchDistance === 0) {
  11144. previousPinchDistance = pinchSquaredDistance;
  11145. return;
  11146. }
  11147. if (pinchSquaredDistance !== previousPinchDistance) {
  11148. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11149. previousPinchDistance = pinchSquaredDistance;
  11150. }
  11151. break;
  11152. default:
  11153. if (pointers.item(evt.pointerId)) {
  11154. pointers.item(evt.pointerId).x = evt.clientX;
  11155. pointers.item(evt.pointerId).y = evt.clientY;
  11156. }
  11157. }
  11158. };
  11159. this._onMouseMove = function (evt) {
  11160. if (!engine.isPointerLock) {
  11161. return;
  11162. }
  11163. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11164. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11165. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11166. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11167. if (!noPreventDefault) {
  11168. evt.preventDefault();
  11169. }
  11170. };
  11171. this._wheel = function (event) {
  11172. var delta = 0;
  11173. if (event.wheelDelta) {
  11174. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11175. }
  11176. else if (event.detail) {
  11177. delta = -event.detail / _this.wheelPrecision;
  11178. }
  11179. if (delta)
  11180. _this.inertialRadiusOffset += delta;
  11181. if (event.preventDefault) {
  11182. if (!noPreventDefault) {
  11183. event.preventDefault();
  11184. }
  11185. }
  11186. };
  11187. this._onKeyDown = function (evt) {
  11188. _this._isCtrlPushed = evt.ctrlKey;
  11189. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11190. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11191. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11192. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11193. var index = _this._keys.indexOf(evt.keyCode);
  11194. if (index === -1) {
  11195. _this._keys.push(evt.keyCode);
  11196. }
  11197. if (evt.preventDefault) {
  11198. if (!noPreventDefault) {
  11199. evt.preventDefault();
  11200. }
  11201. }
  11202. }
  11203. };
  11204. this._onKeyUp = function (evt) {
  11205. _this._isCtrlPushed = evt.ctrlKey;
  11206. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11207. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11208. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11209. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11210. var index = _this._keys.indexOf(evt.keyCode);
  11211. if (index >= 0) {
  11212. _this._keys.splice(index, 1);
  11213. }
  11214. if (evt.preventDefault) {
  11215. if (!noPreventDefault) {
  11216. evt.preventDefault();
  11217. }
  11218. }
  11219. }
  11220. };
  11221. this._onLostFocus = function () {
  11222. _this._keys = [];
  11223. pointers.empty();
  11224. previousPinchDistance = 0;
  11225. cacheSoloPointer = null;
  11226. };
  11227. this._onGestureStart = function (e) {
  11228. if (window.MSGesture === undefined) {
  11229. return;
  11230. }
  11231. if (!_this._MSGestureHandler) {
  11232. _this._MSGestureHandler = new MSGesture();
  11233. _this._MSGestureHandler.target = element;
  11234. }
  11235. _this._MSGestureHandler.addPointer(e.pointerId);
  11236. };
  11237. this._onGesture = function (e) {
  11238. _this.radius *= e.scale;
  11239. if (e.preventDefault) {
  11240. if (!noPreventDefault) {
  11241. e.stopPropagation();
  11242. e.preventDefault();
  11243. }
  11244. }
  11245. };
  11246. this._reset = function () {
  11247. _this._keys = [];
  11248. _this.inertialAlphaOffset = 0;
  11249. _this.inertialBetaOffset = 0;
  11250. _this.inertialRadiusOffset = 0;
  11251. pointers.empty();
  11252. previousPinchDistance = 0;
  11253. cacheSoloPointer = null;
  11254. };
  11255. }
  11256. if (!useCtrlForPanning) {
  11257. element.addEventListener("contextmenu", this._onContextMenu, false);
  11258. }
  11259. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11260. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11261. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11262. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11263. element.addEventListener("mousemove", this._onMouseMove, false);
  11264. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11265. element.addEventListener("MSGestureChange", this._onGesture, false);
  11266. element.addEventListener('mousewheel', this._wheel, false);
  11267. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11268. BABYLON.Tools.RegisterTopRootEvents([
  11269. { name: "keydown", handler: this._onKeyDown },
  11270. { name: "keyup", handler: this._onKeyUp },
  11271. { name: "blur", handler: this._onLostFocus }
  11272. ]);
  11273. };
  11274. ArcRotateCamera.prototype.detachControl = function (element) {
  11275. if (this._attachedElement !== element) {
  11276. return;
  11277. }
  11278. element.removeEventListener("contextmenu", this._onContextMenu);
  11279. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11280. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11281. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11282. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11283. element.removeEventListener("mousemove", this._onMouseMove);
  11284. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11285. element.removeEventListener("MSGestureChange", this._onGesture);
  11286. element.removeEventListener('mousewheel', this._wheel);
  11287. element.removeEventListener('DOMMouseScroll', this._wheel);
  11288. BABYLON.Tools.UnregisterTopRootEvents([
  11289. { name: "keydown", handler: this._onKeyDown },
  11290. { name: "keyup", handler: this._onKeyUp },
  11291. { name: "blur", handler: this._onLostFocus }
  11292. ]);
  11293. this._MSGestureHandler = null;
  11294. this._attachedElement = null;
  11295. if (this._reset) {
  11296. this._reset();
  11297. }
  11298. };
  11299. ArcRotateCamera.prototype._checkInputs = function () {
  11300. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11301. if (this._collisionTriggered) {
  11302. return;
  11303. }
  11304. // Keyboard
  11305. for (var index = 0; index < this._keys.length; index++) {
  11306. var keyCode = this._keys[index];
  11307. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11308. this.inertialAlphaOffset -= 0.01;
  11309. }
  11310. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11311. this.inertialBetaOffset -= 0.01;
  11312. }
  11313. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11314. this.inertialAlphaOffset += 0.01;
  11315. }
  11316. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11317. this.inertialBetaOffset += 0.01;
  11318. }
  11319. }
  11320. // Inertia
  11321. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11322. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11323. this.beta += this.inertialBetaOffset;
  11324. this.radius -= this.inertialRadiusOffset;
  11325. this.inertialAlphaOffset *= this.inertia;
  11326. this.inertialBetaOffset *= this.inertia;
  11327. this.inertialRadiusOffset *= this.inertia;
  11328. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11329. this.inertialAlphaOffset = 0;
  11330. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11331. this.inertialBetaOffset = 0;
  11332. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11333. this.inertialRadiusOffset = 0;
  11334. }
  11335. // Panning inertia
  11336. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11337. if (!this._localDirection) {
  11338. this._localDirection = BABYLON.Vector3.Zero();
  11339. this._transformedDirection = BABYLON.Vector3.Zero();
  11340. }
  11341. this.inertialPanningX *= this.inertia;
  11342. this.inertialPanningY *= this.inertia;
  11343. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11344. this.inertialPanningX = 0;
  11345. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11346. this.inertialPanningY = 0;
  11347. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11348. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11349. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11350. this.target.addInPlace(this._transformedDirection);
  11351. }
  11352. // Limits
  11353. this._checkLimits();
  11354. _super.prototype._checkInputs.call(this);
  11355. };
  11356. ArcRotateCamera.prototype._checkLimits = function () {
  11357. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11358. if (this.allowUpsideDown && this.beta > Math.PI) {
  11359. this.beta = this.beta - (2 * Math.PI);
  11360. }
  11361. }
  11362. else {
  11363. if (this.beta < this.lowerBetaLimit) {
  11364. this.beta = this.lowerBetaLimit;
  11365. }
  11366. }
  11367. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11368. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11369. this.beta = this.beta + (2 * Math.PI);
  11370. }
  11371. }
  11372. else {
  11373. if (this.beta > this.upperBetaLimit) {
  11374. this.beta = this.upperBetaLimit;
  11375. }
  11376. }
  11377. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11378. this.alpha = this.lowerAlphaLimit;
  11379. }
  11380. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11381. this.alpha = this.upperAlphaLimit;
  11382. }
  11383. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11384. this.radius = this.lowerRadiusLimit;
  11385. }
  11386. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11387. this.radius = this.upperRadiusLimit;
  11388. }
  11389. };
  11390. ArcRotateCamera.prototype.setPosition = function (position) {
  11391. var radiusv3 = position.subtract(this._getTargetPosition());
  11392. this.radius = radiusv3.length();
  11393. // Alpha
  11394. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11395. if (radiusv3.z < 0) {
  11396. this.alpha = 2 * Math.PI - this.alpha;
  11397. }
  11398. // Beta
  11399. this.beta = Math.acos(radiusv3.y / this.radius);
  11400. this._checkLimits();
  11401. };
  11402. ArcRotateCamera.prototype.setTarget = function (target) {
  11403. this.target = target;
  11404. };
  11405. ArcRotateCamera.prototype._getViewMatrix = function () {
  11406. // Compute
  11407. var cosa = Math.cos(this.alpha);
  11408. var sina = Math.sin(this.alpha);
  11409. var cosb = Math.cos(this.beta);
  11410. var sinb = Math.sin(this.beta);
  11411. var target = this._getTargetPosition();
  11412. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11413. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11414. this._collider.radius = this.collisionRadius;
  11415. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11416. this._collisionTriggered = true;
  11417. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11418. }
  11419. else {
  11420. this.position.copyFrom(this._newPosition);
  11421. var up = this.upVector;
  11422. if (this.allowUpsideDown && this.beta < 0) {
  11423. var up = up.clone();
  11424. up = up.negate();
  11425. }
  11426. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11427. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11428. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11429. }
  11430. return this._viewMatrix;
  11431. };
  11432. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11433. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11434. meshes = meshes || this.getScene().meshes;
  11435. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11436. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11437. this.radius = distance * this.zoomOnFactor;
  11438. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11439. };
  11440. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11441. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11442. var meshesOrMinMaxVector;
  11443. var distance;
  11444. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11445. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11446. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11447. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11448. }
  11449. else {
  11450. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11451. distance = meshesOrMinMaxVectorAndDistance.distance;
  11452. }
  11453. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11454. if (!doNotUpdateMaxZ) {
  11455. this.maxZ = distance * 2;
  11456. }
  11457. };
  11458. /**
  11459. * @override
  11460. * Override Camera.createRigCamera
  11461. */
  11462. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11463. switch (this.cameraRigMode) {
  11464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11468. case BABYLON.Camera.RIG_MODE_VR:
  11469. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11470. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11471. }
  11472. };
  11473. /**
  11474. * @override
  11475. * Override Camera._updateRigCameras
  11476. */
  11477. ArcRotateCamera.prototype._updateRigCameras = function () {
  11478. switch (this.cameraRigMode) {
  11479. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11480. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11481. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11482. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11483. case BABYLON.Camera.RIG_MODE_VR:
  11484. var camLeft = this._rigCameras[0];
  11485. var camRight = this._rigCameras[1];
  11486. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11487. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11488. camLeft.beta = camRight.beta = this.beta;
  11489. camLeft.radius = camRight.radius = this.radius;
  11490. break;
  11491. }
  11492. _super.prototype._updateRigCameras.call(this);
  11493. };
  11494. return ArcRotateCamera;
  11495. })(BABYLON.TargetCamera);
  11496. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11497. })(BABYLON || (BABYLON = {}));
  11498. var BABYLON;
  11499. (function (BABYLON) {
  11500. // We're mainly based on the logic defined into the FreeCamera code
  11501. var DeviceOrientationCamera = (function (_super) {
  11502. __extends(DeviceOrientationCamera, _super);
  11503. function DeviceOrientationCamera(name, position, scene) {
  11504. var _this = this;
  11505. _super.call(this, name, position, scene);
  11506. this._offsetX = null;
  11507. this._offsetY = null;
  11508. this._orientationGamma = 0;
  11509. this._orientationBeta = 0;
  11510. this._initialOrientationGamma = 0;
  11511. this._initialOrientationBeta = 0;
  11512. this.angularSensibility = 10000.0;
  11513. this.moveSensibility = 50.0;
  11514. window.addEventListener("resize", function () {
  11515. _this._initialOrientationGamma = null;
  11516. }, false);
  11517. }
  11518. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11519. var _this = this;
  11520. if (this._attachedCanvas) {
  11521. return;
  11522. }
  11523. this._attachedCanvas = canvas;
  11524. if (!this._orientationChanged) {
  11525. this._orientationChanged = function (evt) {
  11526. if (!_this._initialOrientationGamma) {
  11527. _this._initialOrientationGamma = evt.gamma;
  11528. _this._initialOrientationBeta = evt.beta;
  11529. }
  11530. _this._orientationGamma = evt.gamma;
  11531. _this._orientationBeta = evt.beta;
  11532. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11533. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11534. };
  11535. }
  11536. window.addEventListener("deviceorientation", this._orientationChanged);
  11537. };
  11538. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11539. if (this._attachedCanvas != canvas) {
  11540. return;
  11541. }
  11542. window.removeEventListener("deviceorientation", this._orientationChanged);
  11543. this._attachedCanvas = null;
  11544. this._orientationGamma = 0;
  11545. this._orientationBeta = 0;
  11546. this._initialOrientationGamma = 0;
  11547. this._initialOrientationBeta = 0;
  11548. };
  11549. DeviceOrientationCamera.prototype._checkInputs = function () {
  11550. if (!this._offsetX) {
  11551. return;
  11552. }
  11553. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11554. var speed = this._computeLocalCameraSpeed();
  11555. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11556. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11557. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11558. _super.prototype._checkInputs.call(this);
  11559. };
  11560. return DeviceOrientationCamera;
  11561. })(BABYLON.FreeCamera);
  11562. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11563. })(BABYLON || (BABYLON = {}));
  11564. var BABYLON;
  11565. (function (BABYLON) {
  11566. var Gamepads = (function () {
  11567. function Gamepads(ongamedpadconnected) {
  11568. var _this = this;
  11569. this.babylonGamepads = [];
  11570. this.oneGamepadConnected = false;
  11571. this.isMonitoring = false;
  11572. this.gamepadEventSupported = 'GamepadEvent' in window;
  11573. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11574. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11575. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  11576. this._callbackGamepadConnected = ongamedpadconnected;
  11577. if (this.gamepadSupportAvailable) {
  11578. // Checking if the gamepad connected event is supported (like in Firefox)
  11579. if (this.gamepadEventSupported) {
  11580. window.addEventListener('gamepadconnected', function (evt) {
  11581. _this._onGamepadConnected(evt);
  11582. }, false);
  11583. window.addEventListener('gamepaddisconnected', function (evt) {
  11584. _this._onGamepadDisconnected(evt);
  11585. }, false);
  11586. }
  11587. else {
  11588. this._startMonitoringGamepads();
  11589. }
  11590. if (!this.oneGamepadConnected) {
  11591. this._insertGamepadDOMInstructions();
  11592. }
  11593. }
  11594. else {
  11595. this._insertGamepadDOMNotSupported();
  11596. }
  11597. }
  11598. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11599. Gamepads.gamepadDOMInfo = document.createElement("div");
  11600. var buttonAImage = document.createElement("img");
  11601. buttonAImage.src = this.buttonADataURL;
  11602. var spanMessage = document.createElement("span");
  11603. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11604. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11605. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11606. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11607. Gamepads.gamepadDOMInfo.style.width = "100%";
  11608. Gamepads.gamepadDOMInfo.style.height = "48px";
  11609. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11610. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11611. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11612. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11613. buttonAImage.style.position = "relative";
  11614. buttonAImage.style.bottom = "8px";
  11615. spanMessage.style.position = "relative";
  11616. spanMessage.style.fontSize = "32px";
  11617. spanMessage.style.bottom = "32px";
  11618. spanMessage.style.color = "green";
  11619. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11620. };
  11621. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11622. Gamepads.gamepadDOMInfo = document.createElement("div");
  11623. var spanMessage = document.createElement("span");
  11624. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11625. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11626. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11627. Gamepads.gamepadDOMInfo.style.width = "100%";
  11628. Gamepads.gamepadDOMInfo.style.height = "40px";
  11629. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11630. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11631. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11632. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11633. spanMessage.style.position = "relative";
  11634. spanMessage.style.fontSize = "32px";
  11635. spanMessage.style.color = "red";
  11636. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11637. };
  11638. Gamepads.prototype.dispose = function () {
  11639. if (Gamepads.gamepadDOMInfo) {
  11640. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11641. }
  11642. };
  11643. Gamepads.prototype._onGamepadConnected = function (evt) {
  11644. var newGamepad = this._addNewGamepad(evt.gamepad);
  11645. if (this._callbackGamepadConnected)
  11646. this._callbackGamepadConnected(newGamepad);
  11647. this._startMonitoringGamepads();
  11648. };
  11649. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11650. if (!this.oneGamepadConnected) {
  11651. this.oneGamepadConnected = true;
  11652. if (Gamepads.gamepadDOMInfo) {
  11653. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11654. Gamepads.gamepadDOMInfo = null;
  11655. }
  11656. }
  11657. var newGamepad;
  11658. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11659. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11660. }
  11661. else {
  11662. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11663. }
  11664. this.babylonGamepads.push(newGamepad);
  11665. return newGamepad;
  11666. };
  11667. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11668. // Remove the gamepad from the list of gamepads to monitor.
  11669. for (var i in this.babylonGamepads) {
  11670. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11671. this.babylonGamepads.splice(i, 1);
  11672. break;
  11673. }
  11674. }
  11675. // If no gamepads are left, stop the polling loop.
  11676. if (this.babylonGamepads.length == 0) {
  11677. this._stopMonitoringGamepads();
  11678. }
  11679. };
  11680. Gamepads.prototype._startMonitoringGamepads = function () {
  11681. if (!this.isMonitoring) {
  11682. this.isMonitoring = true;
  11683. this._checkGamepadsStatus();
  11684. }
  11685. };
  11686. Gamepads.prototype._stopMonitoringGamepads = function () {
  11687. this.isMonitoring = false;
  11688. };
  11689. Gamepads.prototype._checkGamepadsStatus = function () {
  11690. var _this = this;
  11691. // updating gamepad objects
  11692. this._updateGamepadObjects();
  11693. for (var i in this.babylonGamepads) {
  11694. this.babylonGamepads[i].update();
  11695. }
  11696. if (this.isMonitoring) {
  11697. if (window.requestAnimationFrame) {
  11698. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11699. }
  11700. else if (window.mozRequestAnimationFrame) {
  11701. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11702. }
  11703. else if (window.webkitRequestAnimationFrame) {
  11704. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11705. }
  11706. }
  11707. };
  11708. // This function is called only on Chrome, which does not yet support
  11709. // connection/disconnection events, but requires you to monitor
  11710. // an array for changes.
  11711. Gamepads.prototype._updateGamepadObjects = function () {
  11712. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11713. for (var i = 0; i < gamepads.length; i++) {
  11714. if (gamepads[i]) {
  11715. if (!(gamepads[i].index in this.babylonGamepads)) {
  11716. var newGamepad = this._addNewGamepad(gamepads[i]);
  11717. if (this._callbackGamepadConnected) {
  11718. this._callbackGamepadConnected(newGamepad);
  11719. }
  11720. }
  11721. else {
  11722. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11723. }
  11724. }
  11725. }
  11726. };
  11727. return Gamepads;
  11728. })();
  11729. BABYLON.Gamepads = Gamepads;
  11730. var StickValues = (function () {
  11731. function StickValues(x, y) {
  11732. this.x = x;
  11733. this.y = y;
  11734. }
  11735. return StickValues;
  11736. })();
  11737. BABYLON.StickValues = StickValues;
  11738. var Gamepad = (function () {
  11739. function Gamepad(id, index, browserGamepad) {
  11740. this.id = id;
  11741. this.index = index;
  11742. this.browserGamepad = browserGamepad;
  11743. if (this.browserGamepad.axes.length >= 2) {
  11744. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11745. }
  11746. if (this.browserGamepad.axes.length >= 4) {
  11747. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11748. }
  11749. }
  11750. Gamepad.prototype.onleftstickchanged = function (callback) {
  11751. this._onleftstickchanged = callback;
  11752. };
  11753. Gamepad.prototype.onrightstickchanged = function (callback) {
  11754. this._onrightstickchanged = callback;
  11755. };
  11756. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11757. get: function () {
  11758. return this._leftStick;
  11759. },
  11760. set: function (newValues) {
  11761. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11762. this._onleftstickchanged(newValues);
  11763. }
  11764. this._leftStick = newValues;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11770. get: function () {
  11771. return this._rightStick;
  11772. },
  11773. set: function (newValues) {
  11774. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11775. this._onrightstickchanged(newValues);
  11776. }
  11777. this._rightStick = newValues;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Gamepad.prototype.update = function () {
  11783. if (this._leftStick) {
  11784. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11785. }
  11786. if (this._rightStick) {
  11787. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11788. }
  11789. };
  11790. return Gamepad;
  11791. })();
  11792. BABYLON.Gamepad = Gamepad;
  11793. var GenericPad = (function (_super) {
  11794. __extends(GenericPad, _super);
  11795. function GenericPad(id, index, gamepad) {
  11796. _super.call(this, id, index, gamepad);
  11797. this.id = id;
  11798. this.index = index;
  11799. this.gamepad = gamepad;
  11800. this._buttons = new Array(gamepad.buttons.length);
  11801. }
  11802. GenericPad.prototype.onbuttondown = function (callback) {
  11803. this._onbuttondown = callback;
  11804. };
  11805. GenericPad.prototype.onbuttonup = function (callback) {
  11806. this._onbuttonup = callback;
  11807. };
  11808. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11809. if (newValue !== currentValue) {
  11810. if (this._onbuttondown && newValue === 1) {
  11811. this._onbuttondown(buttonIndex);
  11812. }
  11813. if (this._onbuttonup && newValue === 0) {
  11814. this._onbuttonup(buttonIndex);
  11815. }
  11816. }
  11817. return newValue;
  11818. };
  11819. GenericPad.prototype.update = function () {
  11820. _super.prototype.update.call(this);
  11821. for (var index = 0; index < this._buttons.length; index++) {
  11822. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11823. }
  11824. };
  11825. return GenericPad;
  11826. })(Gamepad);
  11827. BABYLON.GenericPad = GenericPad;
  11828. (function (Xbox360Button) {
  11829. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11830. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11831. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11832. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11833. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11834. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11835. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11836. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11837. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11838. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11839. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11840. var Xbox360Button = BABYLON.Xbox360Button;
  11841. (function (Xbox360Dpad) {
  11842. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11843. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11844. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11845. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11846. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11847. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11848. var Xbox360Pad = (function (_super) {
  11849. __extends(Xbox360Pad, _super);
  11850. function Xbox360Pad() {
  11851. _super.apply(this, arguments);
  11852. this._leftTrigger = 0;
  11853. this._rightTrigger = 0;
  11854. this._buttonA = 0;
  11855. this._buttonB = 0;
  11856. this._buttonX = 0;
  11857. this._buttonY = 0;
  11858. this._buttonBack = 0;
  11859. this._buttonStart = 0;
  11860. this._buttonLB = 0;
  11861. this._buttonRB = 0;
  11862. this._buttonLeftStick = 0;
  11863. this._buttonRightStick = 0;
  11864. this._dPadUp = 0;
  11865. this._dPadDown = 0;
  11866. this._dPadLeft = 0;
  11867. this._dPadRight = 0;
  11868. }
  11869. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11870. this._onlefttriggerchanged = callback;
  11871. };
  11872. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11873. this._onrighttriggerchanged = callback;
  11874. };
  11875. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11876. get: function () {
  11877. return this._leftTrigger;
  11878. },
  11879. set: function (newValue) {
  11880. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11881. this._onlefttriggerchanged(newValue);
  11882. }
  11883. this._leftTrigger = newValue;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11889. get: function () {
  11890. return this._rightTrigger;
  11891. },
  11892. set: function (newValue) {
  11893. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11894. this._onrighttriggerchanged(newValue);
  11895. }
  11896. this._rightTrigger = newValue;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11902. this._onbuttondown = callback;
  11903. };
  11904. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11905. this._onbuttonup = callback;
  11906. };
  11907. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11908. this._ondpaddown = callback;
  11909. };
  11910. Xbox360Pad.prototype.ondpadup = function (callback) {
  11911. this._ondpadup = callback;
  11912. };
  11913. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11914. if (newValue !== currentValue) {
  11915. if (this._onbuttondown && newValue === 1) {
  11916. this._onbuttondown(buttonType);
  11917. }
  11918. if (this._onbuttonup && newValue === 0) {
  11919. this._onbuttonup(buttonType);
  11920. }
  11921. }
  11922. return newValue;
  11923. };
  11924. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11925. if (newValue !== currentValue) {
  11926. if (this._ondpaddown && newValue === 1) {
  11927. this._ondpaddown(buttonType);
  11928. }
  11929. if (this._ondpadup && newValue === 0) {
  11930. this._ondpadup(buttonType);
  11931. }
  11932. }
  11933. return newValue;
  11934. };
  11935. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11936. get: function () {
  11937. return this._buttonA;
  11938. },
  11939. set: function (value) {
  11940. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11946. get: function () {
  11947. return this._buttonB;
  11948. },
  11949. set: function (value) {
  11950. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11956. get: function () {
  11957. return this._buttonX;
  11958. },
  11959. set: function (value) {
  11960. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11966. get: function () {
  11967. return this._buttonY;
  11968. },
  11969. set: function (value) {
  11970. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11976. get: function () {
  11977. return this._buttonStart;
  11978. },
  11979. set: function (value) {
  11980. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11986. get: function () {
  11987. return this._buttonBack;
  11988. },
  11989. set: function (value) {
  11990. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11996. get: function () {
  11997. return this._buttonLB;
  11998. },
  11999. set: function (value) {
  12000. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12006. get: function () {
  12007. return this._buttonRB;
  12008. },
  12009. set: function (value) {
  12010. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12016. get: function () {
  12017. return this._buttonLeftStick;
  12018. },
  12019. set: function (value) {
  12020. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12026. get: function () {
  12027. return this._buttonRightStick;
  12028. },
  12029. set: function (value) {
  12030. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12036. get: function () {
  12037. return this._dPadUp;
  12038. },
  12039. set: function (value) {
  12040. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12046. get: function () {
  12047. return this._dPadDown;
  12048. },
  12049. set: function (value) {
  12050. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12056. get: function () {
  12057. return this._dPadLeft;
  12058. },
  12059. set: function (value) {
  12060. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12066. get: function () {
  12067. return this._dPadRight;
  12068. },
  12069. set: function (value) {
  12070. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Xbox360Pad.prototype.update = function () {
  12076. _super.prototype.update.call(this);
  12077. this.buttonA = this.browserGamepad.buttons[0].value;
  12078. this.buttonB = this.browserGamepad.buttons[1].value;
  12079. this.buttonX = this.browserGamepad.buttons[2].value;
  12080. this.buttonY = this.browserGamepad.buttons[3].value;
  12081. this.buttonLB = this.browserGamepad.buttons[4].value;
  12082. this.buttonRB = this.browserGamepad.buttons[5].value;
  12083. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12084. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12085. this.buttonBack = this.browserGamepad.buttons[8].value;
  12086. this.buttonStart = this.browserGamepad.buttons[9].value;
  12087. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12088. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12089. this.dPadUp = this.browserGamepad.buttons[12].value;
  12090. this.dPadDown = this.browserGamepad.buttons[13].value;
  12091. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12092. this.dPadRight = this.browserGamepad.buttons[15].value;
  12093. };
  12094. return Xbox360Pad;
  12095. })(Gamepad);
  12096. BABYLON.Xbox360Pad = Xbox360Pad;
  12097. })(BABYLON || (BABYLON = {}));
  12098. var BABYLON;
  12099. (function (BABYLON) {
  12100. // We're mainly based on the logic defined into the FreeCamera code
  12101. var GamepadCamera = (function (_super) {
  12102. __extends(GamepadCamera, _super);
  12103. function GamepadCamera(name, position, scene) {
  12104. var _this = this;
  12105. _super.call(this, name, position, scene);
  12106. this.angularSensibility = 200;
  12107. this.moveSensibility = 75;
  12108. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12109. }
  12110. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12111. // Only the first gamepad can control the camera
  12112. if (gamepad.index === 0) {
  12113. this._gamepad = gamepad;
  12114. }
  12115. };
  12116. GamepadCamera.prototype._checkInputs = function () {
  12117. if (this._gamepad) {
  12118. var LSValues = this._gamepad.leftStick;
  12119. var normalizedLX = LSValues.x / this.moveSensibility;
  12120. var normalizedLY = LSValues.y / this.moveSensibility;
  12121. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12122. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12123. var RSValues = this._gamepad.rightStick;
  12124. var normalizedRX = RSValues.x / this.angularSensibility;
  12125. var normalizedRY = RSValues.y / this.angularSensibility;
  12126. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12127. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12128. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12129. var speed = this._computeLocalCameraSpeed() * 50.0;
  12130. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12131. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12132. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12133. }
  12134. _super.prototype._checkInputs.call(this);
  12135. };
  12136. GamepadCamera.prototype.dispose = function () {
  12137. this._gamepads.dispose();
  12138. _super.prototype.dispose.call(this);
  12139. };
  12140. return GamepadCamera;
  12141. })(BABYLON.FreeCamera);
  12142. BABYLON.GamepadCamera = GamepadCamera;
  12143. })(BABYLON || (BABYLON = {}));
  12144. var BABYLON;
  12145. (function (BABYLON) {
  12146. var RenderingManager = (function () {
  12147. function RenderingManager(scene) {
  12148. this._renderingGroups = new Array();
  12149. this._scene = scene;
  12150. }
  12151. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12152. if (this._scene._activeParticleSystems.length === 0) {
  12153. return;
  12154. }
  12155. // Particles
  12156. var activeCamera = this._scene.activeCamera;
  12157. var beforeParticlesDate = BABYLON.Tools.Now;
  12158. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12159. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12160. if (particleSystem.renderingGroupId !== index) {
  12161. continue;
  12162. }
  12163. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12164. continue;
  12165. }
  12166. this._clearDepthBuffer();
  12167. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12168. this._scene._activeParticles += particleSystem.render();
  12169. }
  12170. }
  12171. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12172. };
  12173. RenderingManager.prototype._renderSprites = function (index) {
  12174. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12175. return;
  12176. }
  12177. // Sprites
  12178. var activeCamera = this._scene.activeCamera;
  12179. var beforeSpritessDate = BABYLON.Tools.Now;
  12180. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12181. var spriteManager = this._scene.spriteManagers[id];
  12182. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12183. this._clearDepthBuffer();
  12184. spriteManager.render();
  12185. }
  12186. }
  12187. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12188. };
  12189. RenderingManager.prototype._clearDepthBuffer = function () {
  12190. if (this._depthBufferAlreadyCleaned) {
  12191. return;
  12192. }
  12193. this._scene.getEngine().clear(0, false, true);
  12194. this._depthBufferAlreadyCleaned = true;
  12195. };
  12196. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12197. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12198. this._depthBufferAlreadyCleaned = false;
  12199. var renderingGroup = this._renderingGroups[index];
  12200. var needToStepBack = false;
  12201. if (renderingGroup) {
  12202. this._clearDepthBuffer();
  12203. if (!renderingGroup.render(customRenderFunction)) {
  12204. this._renderingGroups.splice(index, 1);
  12205. needToStepBack = true;
  12206. }
  12207. }
  12208. if (renderSprites) {
  12209. this._renderSprites(index);
  12210. }
  12211. if (renderParticles) {
  12212. this._renderParticles(index, activeMeshes);
  12213. }
  12214. if (needToStepBack) {
  12215. index--;
  12216. }
  12217. }
  12218. };
  12219. RenderingManager.prototype.reset = function () {
  12220. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12221. if (renderingGroup) {
  12222. renderingGroup.prepare();
  12223. }
  12224. });
  12225. };
  12226. RenderingManager.prototype.dispatch = function (subMesh) {
  12227. var mesh = subMesh.getMesh();
  12228. var renderingGroupId = mesh.renderingGroupId || 0;
  12229. if (!this._renderingGroups[renderingGroupId]) {
  12230. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12231. }
  12232. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12233. };
  12234. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12235. return RenderingManager;
  12236. })();
  12237. BABYLON.RenderingManager = RenderingManager;
  12238. })(BABYLON || (BABYLON = {}));
  12239. var BABYLON;
  12240. (function (BABYLON) {
  12241. var RenderingGroup = (function () {
  12242. function RenderingGroup(index, scene) {
  12243. this.index = index;
  12244. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12245. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12246. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12247. this._scene = scene;
  12248. }
  12249. RenderingGroup.prototype.render = function (customRenderFunction) {
  12250. if (customRenderFunction) {
  12251. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12252. return true;
  12253. }
  12254. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12255. return false;
  12256. }
  12257. var engine = this._scene.getEngine();
  12258. // Opaque
  12259. var subIndex;
  12260. var submesh;
  12261. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12262. submesh = this._opaqueSubMeshes.data[subIndex];
  12263. submesh.render(false);
  12264. }
  12265. // Alpha test
  12266. engine.setAlphaTesting(true);
  12267. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12268. submesh = this._alphaTestSubMeshes.data[subIndex];
  12269. submesh.render(false);
  12270. }
  12271. engine.setAlphaTesting(false);
  12272. // Transparent
  12273. if (this._transparentSubMeshes.length) {
  12274. // Sorting
  12275. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12276. submesh = this._transparentSubMeshes.data[subIndex];
  12277. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12278. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12279. }
  12280. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12281. sortedArray.sort(function (a, b) {
  12282. // Alpha index first
  12283. if (a._alphaIndex > b._alphaIndex) {
  12284. return 1;
  12285. }
  12286. if (a._alphaIndex < b._alphaIndex) {
  12287. return -1;
  12288. }
  12289. // Then distance to camera
  12290. if (a._distanceToCamera < b._distanceToCamera) {
  12291. return 1;
  12292. }
  12293. if (a._distanceToCamera > b._distanceToCamera) {
  12294. return -1;
  12295. }
  12296. return 0;
  12297. });
  12298. // Rendering
  12299. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12300. submesh = sortedArray[subIndex];
  12301. submesh.render(true);
  12302. }
  12303. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12304. }
  12305. return true;
  12306. };
  12307. RenderingGroup.prototype.prepare = function () {
  12308. this._opaqueSubMeshes.reset();
  12309. this._transparentSubMeshes.reset();
  12310. this._alphaTestSubMeshes.reset();
  12311. };
  12312. RenderingGroup.prototype.dispatch = function (subMesh) {
  12313. var material = subMesh.getMaterial();
  12314. var mesh = subMesh.getMesh();
  12315. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12316. this._transparentSubMeshes.push(subMesh);
  12317. }
  12318. else if (material.needAlphaTesting()) {
  12319. this._alphaTestSubMeshes.push(subMesh);
  12320. }
  12321. else {
  12322. this._opaqueSubMeshes.push(subMesh); // Opaque
  12323. }
  12324. };
  12325. return RenderingGroup;
  12326. })();
  12327. BABYLON.RenderingGroup = RenderingGroup;
  12328. })(BABYLON || (BABYLON = {}));
  12329. var BABYLON;
  12330. (function (BABYLON) {
  12331. /**
  12332. * Represents a scene to be rendered by the engine.
  12333. * @see http://doc.babylonjs.com/page.php?p=21911
  12334. */
  12335. var Scene = (function () {
  12336. /**
  12337. * @constructor
  12338. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12339. */
  12340. function Scene(engine) {
  12341. // Members
  12342. this.autoClear = true;
  12343. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12344. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12345. this.forceWireframe = false;
  12346. this.forcePointsCloud = false;
  12347. this.forceShowBoundingBoxes = false;
  12348. this.animationsEnabled = true;
  12349. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12350. // Fog
  12351. /**
  12352. * is fog enabled on this scene.
  12353. * @type {boolean}
  12354. */
  12355. this.fogEnabled = true;
  12356. this.fogMode = Scene.FOGMODE_NONE;
  12357. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12358. this.fogDensity = 0.1;
  12359. this.fogStart = 0;
  12360. this.fogEnd = 1000.0;
  12361. // Lights
  12362. /**
  12363. * is shadow enabled on this scene.
  12364. * @type {boolean}
  12365. */
  12366. this.shadowsEnabled = true;
  12367. /**
  12368. * is light enabled on this scene.
  12369. * @type {boolean}
  12370. */
  12371. this.lightsEnabled = true;
  12372. /**
  12373. * All of the lights added to this scene.
  12374. * @see BABYLON.Light
  12375. * @type {BABYLON.Light[]}
  12376. */
  12377. this.lights = new Array();
  12378. // Cameras
  12379. /**
  12380. * All of the cameras added to this scene.
  12381. * @see BABYLON.Camera
  12382. * @type {BABYLON.Camera[]}
  12383. */
  12384. this.cameras = new Array();
  12385. this.activeCameras = new Array();
  12386. // Meshes
  12387. /**
  12388. * All of the (abstract) meshes added to this scene.
  12389. * @see BABYLON.AbstractMesh
  12390. * @type {BABYLON.AbstractMesh[]}
  12391. */
  12392. this.meshes = new Array();
  12393. // Geometries
  12394. this._geometries = new Array();
  12395. this.materials = new Array();
  12396. this.multiMaterials = new Array();
  12397. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12398. // Textures
  12399. this.texturesEnabled = true;
  12400. this.textures = new Array();
  12401. // Particles
  12402. this.particlesEnabled = true;
  12403. this.particleSystems = new Array();
  12404. // Sprites
  12405. this.spritesEnabled = true;
  12406. this.spriteManagers = new Array();
  12407. // Layers
  12408. this.layers = new Array();
  12409. // Skeletons
  12410. this.skeletonsEnabled = true;
  12411. this.skeletons = new Array();
  12412. // Lens flares
  12413. this.lensFlaresEnabled = true;
  12414. this.lensFlareSystems = new Array();
  12415. // Collisions
  12416. this.collisionsEnabled = true;
  12417. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12418. // Postprocesses
  12419. this.postProcessesEnabled = true;
  12420. // Customs render targets
  12421. this.renderTargetsEnabled = true;
  12422. this.dumpNextRenderTargets = false;
  12423. this.customRenderTargets = new Array();
  12424. // Imported meshes
  12425. this.importedMeshesFiles = new Array();
  12426. this._actionManagers = new Array();
  12427. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12428. // Procedural textures
  12429. this.proceduralTexturesEnabled = true;
  12430. this._proceduralTextures = new Array();
  12431. this.soundTracks = new Array();
  12432. this._audioEnabled = true;
  12433. this._headphone = false;
  12434. this._totalVertices = 0;
  12435. this._activeIndices = 0;
  12436. this._activeParticles = 0;
  12437. this._lastFrameDuration = 0;
  12438. this._evaluateActiveMeshesDuration = 0;
  12439. this._renderTargetsDuration = 0;
  12440. this._particlesDuration = 0;
  12441. this._renderDuration = 0;
  12442. this._spritesDuration = 0;
  12443. this._animationRatio = 0;
  12444. this._renderId = 0;
  12445. this._executeWhenReadyTimeoutId = -1;
  12446. this._toBeDisposed = new BABYLON.SmartArray(256);
  12447. this._onReadyCallbacks = new Array();
  12448. this._pendingData = []; //ANY
  12449. this._onBeforeRenderCallbacks = new Array();
  12450. this._onAfterRenderCallbacks = new Array();
  12451. this._activeMeshes = new BABYLON.SmartArray(256);
  12452. this._processedMaterials = new BABYLON.SmartArray(256);
  12453. this._renderTargets = new BABYLON.SmartArray(256);
  12454. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12455. this._activeSkeletons = new BABYLON.SmartArray(32);
  12456. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12457. this._activeBones = 0;
  12458. this._activeAnimatables = new Array();
  12459. this._transformMatrix = BABYLON.Matrix.Zero();
  12460. this._edgesRenderers = new BABYLON.SmartArray(16);
  12461. this._uniqueIdCounter = 0;
  12462. this._engine = engine;
  12463. engine.scenes.push(this);
  12464. this._renderingManager = new BABYLON.RenderingManager(this);
  12465. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12466. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12467. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12468. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12469. this.attachControl();
  12470. this._debugLayer = new BABYLON.DebugLayer(this);
  12471. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12472. //simplification queue
  12473. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12474. //collision coordinator initialization. For now legacy per default.
  12475. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12476. }
  12477. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12478. get: function () {
  12479. return Scene._FOGMODE_NONE;
  12480. },
  12481. enumerable: true,
  12482. configurable: true
  12483. });
  12484. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12485. get: function () {
  12486. return Scene._FOGMODE_EXP;
  12487. },
  12488. enumerable: true,
  12489. configurable: true
  12490. });
  12491. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12492. get: function () {
  12493. return Scene._FOGMODE_EXP2;
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12499. get: function () {
  12500. return Scene._FOGMODE_LINEAR;
  12501. },
  12502. enumerable: true,
  12503. configurable: true
  12504. });
  12505. Object.defineProperty(Scene.prototype, "debugLayer", {
  12506. // Properties
  12507. get: function () {
  12508. return this._debugLayer;
  12509. },
  12510. enumerable: true,
  12511. configurable: true
  12512. });
  12513. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12514. get: function () {
  12515. return this._workerCollisions;
  12516. },
  12517. set: function (enabled) {
  12518. enabled = (enabled && !!Worker);
  12519. this._workerCollisions = enabled;
  12520. if (this.collisionCoordinator) {
  12521. this.collisionCoordinator.destroy();
  12522. }
  12523. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12524. this.collisionCoordinator.init(this);
  12525. },
  12526. enumerable: true,
  12527. configurable: true
  12528. });
  12529. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12530. get: function () {
  12531. return this._selectionOctree;
  12532. },
  12533. enumerable: true,
  12534. configurable: true
  12535. });
  12536. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12537. /**
  12538. * The mesh that is currently under the pointer.
  12539. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12540. */
  12541. get: function () {
  12542. return this._meshUnderPointer;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Scene.prototype, "pointerX", {
  12548. /**
  12549. * Current on-screen X position of the pointer
  12550. * @return {number} X position of the pointer
  12551. */
  12552. get: function () {
  12553. return this._pointerX;
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. Object.defineProperty(Scene.prototype, "pointerY", {
  12559. /**
  12560. * Current on-screen Y position of the pointer
  12561. * @return {number} Y position of the pointer
  12562. */
  12563. get: function () {
  12564. return this._pointerY;
  12565. },
  12566. enumerable: true,
  12567. configurable: true
  12568. });
  12569. Scene.prototype.getCachedMaterial = function () {
  12570. return this._cachedMaterial;
  12571. };
  12572. Scene.prototype.getBoundingBoxRenderer = function () {
  12573. return this._boundingBoxRenderer;
  12574. };
  12575. Scene.prototype.getOutlineRenderer = function () {
  12576. return this._outlineRenderer;
  12577. };
  12578. Scene.prototype.getEngine = function () {
  12579. return this._engine;
  12580. };
  12581. Scene.prototype.getTotalVertices = function () {
  12582. return this._totalVertices;
  12583. };
  12584. Scene.prototype.getActiveIndices = function () {
  12585. return this._activeIndices;
  12586. };
  12587. Scene.prototype.getActiveParticles = function () {
  12588. return this._activeParticles;
  12589. };
  12590. Scene.prototype.getActiveBones = function () {
  12591. return this._activeBones;
  12592. };
  12593. // Stats
  12594. Scene.prototype.getLastFrameDuration = function () {
  12595. return this._lastFrameDuration;
  12596. };
  12597. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12598. return this._evaluateActiveMeshesDuration;
  12599. };
  12600. Scene.prototype.getActiveMeshes = function () {
  12601. return this._activeMeshes;
  12602. };
  12603. Scene.prototype.getRenderTargetsDuration = function () {
  12604. return this._renderTargetsDuration;
  12605. };
  12606. Scene.prototype.getRenderDuration = function () {
  12607. return this._renderDuration;
  12608. };
  12609. Scene.prototype.getParticlesDuration = function () {
  12610. return this._particlesDuration;
  12611. };
  12612. Scene.prototype.getSpritesDuration = function () {
  12613. return this._spritesDuration;
  12614. };
  12615. Scene.prototype.getAnimationRatio = function () {
  12616. return this._animationRatio;
  12617. };
  12618. Scene.prototype.getRenderId = function () {
  12619. return this._renderId;
  12620. };
  12621. Scene.prototype.incrementRenderId = function () {
  12622. this._renderId++;
  12623. };
  12624. Scene.prototype._updatePointerPosition = function (evt) {
  12625. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12626. this._pointerX = evt.clientX - canvasRect.left;
  12627. this._pointerY = evt.clientY - canvasRect.top;
  12628. if (this.cameraToUseForPointers) {
  12629. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12630. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12631. }
  12632. };
  12633. // Pointers handling
  12634. Scene.prototype.attachControl = function () {
  12635. var _this = this;
  12636. this._onPointerMove = function (evt) {
  12637. var canvas = _this._engine.getRenderingCanvas();
  12638. _this._updatePointerPosition(evt);
  12639. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12640. if (pickResult.hit) {
  12641. _this._meshUnderPointer = pickResult.pickedMesh;
  12642. _this.setPointerOverMesh(pickResult.pickedMesh);
  12643. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12644. canvas.style.cursor = "pointer";
  12645. }
  12646. else {
  12647. canvas.style.cursor = "";
  12648. }
  12649. }
  12650. else {
  12651. _this.setPointerOverMesh(null);
  12652. canvas.style.cursor = "";
  12653. _this._meshUnderPointer = null;
  12654. }
  12655. };
  12656. this._onPointerDown = function (evt) {
  12657. var predicate = null;
  12658. if (!_this.onPointerDown) {
  12659. predicate = function (mesh) {
  12660. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12661. };
  12662. }
  12663. _this._updatePointerPosition(evt);
  12664. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12665. if (pickResult.hit) {
  12666. if (pickResult.pickedMesh.actionManager) {
  12667. switch (evt.button) {
  12668. case 0:
  12669. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12670. break;
  12671. case 1:
  12672. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12673. break;
  12674. case 2:
  12675. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12676. break;
  12677. }
  12678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12679. }
  12680. }
  12681. if (_this.onPointerDown) {
  12682. _this.onPointerDown(evt, pickResult);
  12683. }
  12684. };
  12685. this._onPointerUp = function (evt) {
  12686. var predicate = null;
  12687. if (!_this.onPointerUp) {
  12688. predicate = function (mesh) {
  12689. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12690. };
  12691. }
  12692. _this._updatePointerPosition(evt);
  12693. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12694. if (pickResult.hit) {
  12695. if (pickResult.pickedMesh.actionManager) {
  12696. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12697. }
  12698. }
  12699. if (_this.onPointerUp) {
  12700. _this.onPointerUp(evt, pickResult);
  12701. }
  12702. };
  12703. this._onKeyDown = function (evt) {
  12704. if (_this.actionManager) {
  12705. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12706. }
  12707. };
  12708. this._onKeyUp = function (evt) {
  12709. if (_this.actionManager) {
  12710. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12711. }
  12712. };
  12713. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12714. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12715. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12716. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12717. // Wheel
  12718. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12719. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12720. BABYLON.Tools.RegisterTopRootEvents([
  12721. { name: "keydown", handler: this._onKeyDown },
  12722. { name: "keyup", handler: this._onKeyUp }
  12723. ]);
  12724. };
  12725. Scene.prototype.detachControl = function () {
  12726. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12727. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12728. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12729. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12730. // Wheel
  12731. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12732. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12733. BABYLON.Tools.UnregisterTopRootEvents([
  12734. { name: "keydown", handler: this._onKeyDown },
  12735. { name: "keyup", handler: this._onKeyUp }
  12736. ]);
  12737. };
  12738. // Ready
  12739. Scene.prototype.isReady = function () {
  12740. if (this._pendingData.length > 0) {
  12741. return false;
  12742. }
  12743. var index;
  12744. for (index = 0; index < this._geometries.length; index++) {
  12745. var geometry = this._geometries[index];
  12746. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12747. return false;
  12748. }
  12749. }
  12750. for (index = 0; index < this.meshes.length; index++) {
  12751. var mesh = this.meshes[index];
  12752. if (!mesh.isReady()) {
  12753. return false;
  12754. }
  12755. var mat = mesh.material;
  12756. if (mat) {
  12757. if (!mat.isReady(mesh)) {
  12758. return false;
  12759. }
  12760. }
  12761. }
  12762. return true;
  12763. };
  12764. Scene.prototype.resetCachedMaterial = function () {
  12765. this._cachedMaterial = null;
  12766. };
  12767. Scene.prototype.registerBeforeRender = function (func) {
  12768. this._onBeforeRenderCallbacks.push(func);
  12769. };
  12770. Scene.prototype.unregisterBeforeRender = function (func) {
  12771. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12772. if (index > -1) {
  12773. this._onBeforeRenderCallbacks.splice(index, 1);
  12774. }
  12775. };
  12776. Scene.prototype.registerAfterRender = function (func) {
  12777. this._onAfterRenderCallbacks.push(func);
  12778. };
  12779. Scene.prototype.unregisterAfterRender = function (func) {
  12780. var index = this._onAfterRenderCallbacks.indexOf(func);
  12781. if (index > -1) {
  12782. this._onAfterRenderCallbacks.splice(index, 1);
  12783. }
  12784. };
  12785. Scene.prototype._addPendingData = function (data) {
  12786. this._pendingData.push(data);
  12787. };
  12788. Scene.prototype._removePendingData = function (data) {
  12789. var index = this._pendingData.indexOf(data);
  12790. if (index !== -1) {
  12791. this._pendingData.splice(index, 1);
  12792. }
  12793. };
  12794. Scene.prototype.getWaitingItemsCount = function () {
  12795. return this._pendingData.length;
  12796. };
  12797. /**
  12798. * Registers a function to be executed when the scene is ready.
  12799. * @param {Function} func - the function to be executed.
  12800. */
  12801. Scene.prototype.executeWhenReady = function (func) {
  12802. var _this = this;
  12803. this._onReadyCallbacks.push(func);
  12804. if (this._executeWhenReadyTimeoutId !== -1) {
  12805. return;
  12806. }
  12807. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12808. _this._checkIsReady();
  12809. }, 150);
  12810. };
  12811. Scene.prototype._checkIsReady = function () {
  12812. var _this = this;
  12813. if (this.isReady()) {
  12814. this._onReadyCallbacks.forEach(function (func) {
  12815. func();
  12816. });
  12817. this._onReadyCallbacks = [];
  12818. this._executeWhenReadyTimeoutId = -1;
  12819. return;
  12820. }
  12821. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12822. _this._checkIsReady();
  12823. }, 150);
  12824. };
  12825. // Animations
  12826. /**
  12827. * Will start the animation sequence of a given target
  12828. * @param target - the target
  12829. * @param {number} from - from which frame should animation start
  12830. * @param {number} to - till which frame should animation run.
  12831. * @param {boolean} [loop] - should the animation loop
  12832. * @param {number} [speedRatio] - the speed in which to run the animation
  12833. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12834. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12835. * @return {BABYLON.Animatable} the animatable object created for this animation
  12836. * @see BABYLON.Animatable
  12837. * @see http://doc.babylonjs.com/page.php?p=22081
  12838. */
  12839. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12840. if (speedRatio === undefined) {
  12841. speedRatio = 1.0;
  12842. }
  12843. this.stopAnimation(target);
  12844. if (!animatable) {
  12845. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12846. }
  12847. // Local animations
  12848. if (target.animations) {
  12849. animatable.appendAnimations(target, target.animations);
  12850. }
  12851. // Children animations
  12852. if (target.getAnimatables) {
  12853. var animatables = target.getAnimatables();
  12854. for (var index = 0; index < animatables.length; index++) {
  12855. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12856. }
  12857. }
  12858. return animatable;
  12859. };
  12860. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12861. if (speedRatio === undefined) {
  12862. speedRatio = 1.0;
  12863. }
  12864. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12865. return animatable;
  12866. };
  12867. Scene.prototype.getAnimatableByTarget = function (target) {
  12868. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12869. if (this._activeAnimatables[index].target === target) {
  12870. return this._activeAnimatables[index];
  12871. }
  12872. }
  12873. return null;
  12874. };
  12875. /**
  12876. * Will stop the animation of the given target
  12877. * @param target - the target
  12878. * @see beginAnimation
  12879. */
  12880. Scene.prototype.stopAnimation = function (target) {
  12881. var animatable = this.getAnimatableByTarget(target);
  12882. if (animatable) {
  12883. animatable.stop();
  12884. }
  12885. };
  12886. Scene.prototype._animate = function () {
  12887. if (!this.animationsEnabled) {
  12888. return;
  12889. }
  12890. if (!this._animationStartDate) {
  12891. this._animationStartDate = BABYLON.Tools.Now;
  12892. }
  12893. // Getting time
  12894. var now = BABYLON.Tools.Now;
  12895. var delay = now - this._animationStartDate;
  12896. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12897. this._activeAnimatables[index]._animate(delay);
  12898. }
  12899. };
  12900. // Matrix
  12901. Scene.prototype.getViewMatrix = function () {
  12902. return this._viewMatrix;
  12903. };
  12904. Scene.prototype.getProjectionMatrix = function () {
  12905. return this._projectionMatrix;
  12906. };
  12907. Scene.prototype.getTransformMatrix = function () {
  12908. return this._transformMatrix;
  12909. };
  12910. Scene.prototype.setTransformMatrix = function (view, projection) {
  12911. this._viewMatrix = view;
  12912. this._projectionMatrix = projection;
  12913. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12914. };
  12915. // Methods
  12916. Scene.prototype.addMesh = function (newMesh) {
  12917. newMesh.uniqueId = this._uniqueIdCounter++;
  12918. var position = this.meshes.push(newMesh);
  12919. //notify the collision coordinator
  12920. this.collisionCoordinator.onMeshAdded(newMesh);
  12921. if (this.onNewMeshAdded) {
  12922. this.onNewMeshAdded(newMesh, position, this);
  12923. }
  12924. };
  12925. Scene.prototype.removeMesh = function (toRemove) {
  12926. var index = this.meshes.indexOf(toRemove);
  12927. if (index !== -1) {
  12928. // Remove from the scene if mesh found
  12929. this.meshes.splice(index, 1);
  12930. }
  12931. //notify the collision coordinator
  12932. this.collisionCoordinator.onMeshRemoved(toRemove);
  12933. if (this.onMeshRemoved) {
  12934. this.onMeshRemoved(toRemove);
  12935. }
  12936. return index;
  12937. };
  12938. Scene.prototype.removeLight = function (toRemove) {
  12939. var index = this.lights.indexOf(toRemove);
  12940. if (index !== -1) {
  12941. // Remove from the scene if mesh found
  12942. this.lights.splice(index, 1);
  12943. }
  12944. if (this.onLightRemoved) {
  12945. this.onLightRemoved(toRemove);
  12946. }
  12947. return index;
  12948. };
  12949. Scene.prototype.removeCamera = function (toRemove) {
  12950. var index = this.cameras.indexOf(toRemove);
  12951. if (index !== -1) {
  12952. // Remove from the scene if mesh found
  12953. this.cameras.splice(index, 1);
  12954. }
  12955. // Remove from activeCameras
  12956. var index2 = this.activeCameras.indexOf(toRemove);
  12957. if (index2 !== -1) {
  12958. // Remove from the scene if mesh found
  12959. this.activeCameras.splice(index2, 1);
  12960. }
  12961. // Reset the activeCamera
  12962. if (this.activeCamera === toRemove) {
  12963. if (this.cameras.length > 0) {
  12964. this.activeCamera = this.cameras[0];
  12965. }
  12966. else {
  12967. this.activeCamera = null;
  12968. }
  12969. }
  12970. if (this.onCameraRemoved) {
  12971. this.onCameraRemoved(toRemove);
  12972. }
  12973. return index;
  12974. };
  12975. Scene.prototype.addLight = function (newLight) {
  12976. newLight.uniqueId = this._uniqueIdCounter++;
  12977. var position = this.lights.push(newLight);
  12978. if (this.onNewLightAdded) {
  12979. this.onNewLightAdded(newLight, position, this);
  12980. }
  12981. };
  12982. Scene.prototype.addCamera = function (newCamera) {
  12983. newCamera.uniqueId = this._uniqueIdCounter++;
  12984. var position = this.cameras.push(newCamera);
  12985. if (this.onNewCameraAdded) {
  12986. this.onNewCameraAdded(newCamera, position, this);
  12987. }
  12988. };
  12989. /**
  12990. * sets the active camera of the scene using its ID
  12991. * @param {string} id - the camera's ID
  12992. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12993. * @see activeCamera
  12994. */
  12995. Scene.prototype.setActiveCameraByID = function (id) {
  12996. var camera = this.getCameraByID(id);
  12997. if (camera) {
  12998. this.activeCamera = camera;
  12999. return camera;
  13000. }
  13001. return null;
  13002. };
  13003. /**
  13004. * sets the active camera of the scene using its name
  13005. * @param {string} name - the camera's name
  13006. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13007. * @see activeCamera
  13008. */
  13009. Scene.prototype.setActiveCameraByName = function (name) {
  13010. var camera = this.getCameraByName(name);
  13011. if (camera) {
  13012. this.activeCamera = camera;
  13013. return camera;
  13014. }
  13015. return null;
  13016. };
  13017. /**
  13018. * get a material using its id
  13019. * @param {string} the material's ID
  13020. * @return {BABYLON.Material|null} the material or null if none found.
  13021. */
  13022. Scene.prototype.getMaterialByID = function (id) {
  13023. for (var index = 0; index < this.materials.length; index++) {
  13024. if (this.materials[index].id === id) {
  13025. return this.materials[index];
  13026. }
  13027. }
  13028. return null;
  13029. };
  13030. /**
  13031. * get a material using its name
  13032. * @param {string} the material's name
  13033. * @return {BABYLON.Material|null} the material or null if none found.
  13034. */
  13035. Scene.prototype.getMaterialByName = function (name) {
  13036. for (var index = 0; index < this.materials.length; index++) {
  13037. if (this.materials[index].name === name) {
  13038. return this.materials[index];
  13039. }
  13040. }
  13041. return null;
  13042. };
  13043. Scene.prototype.getLensFlareSystemByName = function (name) {
  13044. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13045. if (this.lensFlareSystems[index].name === name) {
  13046. return this.lensFlareSystems[index];
  13047. }
  13048. }
  13049. return null;
  13050. };
  13051. Scene.prototype.getCameraByID = function (id) {
  13052. for (var index = 0; index < this.cameras.length; index++) {
  13053. if (this.cameras[index].id === id) {
  13054. return this.cameras[index];
  13055. }
  13056. }
  13057. return null;
  13058. };
  13059. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13060. for (var index = 0; index < this.cameras.length; index++) {
  13061. if (this.cameras[index].uniqueId === uniqueId) {
  13062. return this.cameras[index];
  13063. }
  13064. }
  13065. return null;
  13066. };
  13067. /**
  13068. * get a camera using its name
  13069. * @param {string} the camera's name
  13070. * @return {BABYLON.Camera|null} the camera or null if none found.
  13071. */
  13072. Scene.prototype.getCameraByName = function (name) {
  13073. for (var index = 0; index < this.cameras.length; index++) {
  13074. if (this.cameras[index].name === name) {
  13075. return this.cameras[index];
  13076. }
  13077. }
  13078. return null;
  13079. };
  13080. /**
  13081. * get a light node using its name
  13082. * @param {string} the light's name
  13083. * @return {BABYLON.Light|null} the light or null if none found.
  13084. */
  13085. Scene.prototype.getLightByName = function (name) {
  13086. for (var index = 0; index < this.lights.length; index++) {
  13087. if (this.lights[index].name === name) {
  13088. return this.lights[index];
  13089. }
  13090. }
  13091. return null;
  13092. };
  13093. /**
  13094. * get a light node using its ID
  13095. * @param {string} the light's id
  13096. * @return {BABYLON.Light|null} the light or null if none found.
  13097. */
  13098. Scene.prototype.getLightByID = function (id) {
  13099. for (var index = 0; index < this.lights.length; index++) {
  13100. if (this.lights[index].id === id) {
  13101. return this.lights[index];
  13102. }
  13103. }
  13104. return null;
  13105. };
  13106. /**
  13107. * get a light node using its scene-generated unique ID
  13108. * @param {number} the light's unique id
  13109. * @return {BABYLON.Light|null} the light or null if none found.
  13110. */
  13111. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13112. for (var index = 0; index < this.lights.length; index++) {
  13113. if (this.lights[index].uniqueId === uniqueId) {
  13114. return this.lights[index];
  13115. }
  13116. }
  13117. return null;
  13118. };
  13119. /**
  13120. * get a geometry using its ID
  13121. * @param {string} the geometry's id
  13122. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13123. */
  13124. Scene.prototype.getGeometryByID = function (id) {
  13125. for (var index = 0; index < this._geometries.length; index++) {
  13126. if (this._geometries[index].id === id) {
  13127. return this._geometries[index];
  13128. }
  13129. }
  13130. return null;
  13131. };
  13132. /**
  13133. * add a new geometry to this scene.
  13134. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13135. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13136. * @return {boolean} was the geometry added or not
  13137. */
  13138. Scene.prototype.pushGeometry = function (geometry, force) {
  13139. if (!force && this.getGeometryByID(geometry.id)) {
  13140. return false;
  13141. }
  13142. this._geometries.push(geometry);
  13143. //notify the collision coordinator
  13144. this.collisionCoordinator.onGeometryAdded(geometry);
  13145. if (this.onGeometryAdded) {
  13146. this.onGeometryAdded(geometry);
  13147. }
  13148. return true;
  13149. };
  13150. /**
  13151. * Removes an existing geometry
  13152. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13153. * @return {boolean} was the geometry removed or not
  13154. */
  13155. Scene.prototype.removeGeometry = function (geometry) {
  13156. var index = this._geometries.indexOf(geometry);
  13157. if (index > -1) {
  13158. this._geometries.splice(index, 1);
  13159. //notify the collision coordinator
  13160. this.collisionCoordinator.onGeometryDeleted(geometry);
  13161. if (this.onGeometryRemoved) {
  13162. this.onGeometryRemoved(geometry);
  13163. }
  13164. return true;
  13165. }
  13166. return false;
  13167. };
  13168. Scene.prototype.getGeometries = function () {
  13169. return this._geometries;
  13170. };
  13171. /**
  13172. * Get the first added mesh found of a given ID
  13173. * @param {string} id - the id to search for
  13174. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13175. */
  13176. Scene.prototype.getMeshByID = function (id) {
  13177. for (var index = 0; index < this.meshes.length; index++) {
  13178. if (this.meshes[index].id === id) {
  13179. return this.meshes[index];
  13180. }
  13181. }
  13182. return null;
  13183. };
  13184. /**
  13185. * Get a mesh with its auto-generated unique id
  13186. * @param {number} uniqueId - the unique id to search for
  13187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13188. */
  13189. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13190. for (var index = 0; index < this.meshes.length; index++) {
  13191. if (this.meshes[index].uniqueId === uniqueId) {
  13192. return this.meshes[index];
  13193. }
  13194. }
  13195. return null;
  13196. };
  13197. /**
  13198. * Get a the last added mesh found of a given ID
  13199. * @param {string} id - the id to search for
  13200. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13201. */
  13202. Scene.prototype.getLastMeshByID = function (id) {
  13203. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13204. if (this.meshes[index].id === id) {
  13205. return this.meshes[index];
  13206. }
  13207. }
  13208. return null;
  13209. };
  13210. /**
  13211. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13212. * @param {string} id - the id to search for
  13213. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13214. */
  13215. Scene.prototype.getLastEntryByID = function (id) {
  13216. var index;
  13217. for (index = this.meshes.length - 1; index >= 0; index--) {
  13218. if (this.meshes[index].id === id) {
  13219. return this.meshes[index];
  13220. }
  13221. }
  13222. for (index = this.cameras.length - 1; index >= 0; index--) {
  13223. if (this.cameras[index].id === id) {
  13224. return this.cameras[index];
  13225. }
  13226. }
  13227. for (index = this.lights.length - 1; index >= 0; index--) {
  13228. if (this.lights[index].id === id) {
  13229. return this.lights[index];
  13230. }
  13231. }
  13232. return null;
  13233. };
  13234. Scene.prototype.getNodeByID = function (id) {
  13235. var mesh = this.getMeshByID(id);
  13236. if (mesh) {
  13237. return mesh;
  13238. }
  13239. var light = this.getLightByID(id);
  13240. if (light) {
  13241. return light;
  13242. }
  13243. return this.getCameraByID(id);
  13244. };
  13245. Scene.prototype.getNodeByName = function (name) {
  13246. var mesh = this.getMeshByName(name);
  13247. if (mesh) {
  13248. return mesh;
  13249. }
  13250. var light = this.getLightByName(name);
  13251. if (light) {
  13252. return light;
  13253. }
  13254. return this.getCameraByName(name);
  13255. };
  13256. Scene.prototype.getMeshByName = function (name) {
  13257. for (var index = 0; index < this.meshes.length; index++) {
  13258. if (this.meshes[index].name === name) {
  13259. return this.meshes[index];
  13260. }
  13261. }
  13262. return null;
  13263. };
  13264. Scene.prototype.getSoundByName = function (name) {
  13265. var index;
  13266. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13267. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13268. return this.mainSoundTrack.soundCollection[index];
  13269. }
  13270. }
  13271. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13272. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13273. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13274. return this.soundTracks[sdIndex].soundCollection[index];
  13275. }
  13276. }
  13277. }
  13278. return null;
  13279. };
  13280. Scene.prototype.getLastSkeletonByID = function (id) {
  13281. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13282. if (this.skeletons[index].id === id) {
  13283. return this.skeletons[index];
  13284. }
  13285. }
  13286. return null;
  13287. };
  13288. Scene.prototype.getSkeletonById = function (id) {
  13289. for (var index = 0; index < this.skeletons.length; index++) {
  13290. if (this.skeletons[index].id === id) {
  13291. return this.skeletons[index];
  13292. }
  13293. }
  13294. return null;
  13295. };
  13296. Scene.prototype.getSkeletonByName = function (name) {
  13297. for (var index = 0; index < this.skeletons.length; index++) {
  13298. if (this.skeletons[index].name === name) {
  13299. return this.skeletons[index];
  13300. }
  13301. }
  13302. return null;
  13303. };
  13304. Scene.prototype.isActiveMesh = function (mesh) {
  13305. return (this._activeMeshes.indexOf(mesh) !== -1);
  13306. };
  13307. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13308. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13309. var material = subMesh.getMaterial();
  13310. if (mesh.showSubMeshesBoundingBox) {
  13311. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13312. }
  13313. if (material) {
  13314. // Render targets
  13315. if (material.getRenderTargetTextures) {
  13316. if (this._processedMaterials.indexOf(material) === -1) {
  13317. this._processedMaterials.push(material);
  13318. this._renderTargets.concat(material.getRenderTargetTextures());
  13319. }
  13320. }
  13321. // Dispatch
  13322. this._activeIndices += subMesh.indexCount;
  13323. this._renderingManager.dispatch(subMesh);
  13324. }
  13325. }
  13326. };
  13327. Scene.prototype._evaluateActiveMeshes = function () {
  13328. this.activeCamera._activeMeshes.reset();
  13329. this._activeMeshes.reset();
  13330. this._renderingManager.reset();
  13331. this._processedMaterials.reset();
  13332. this._activeParticleSystems.reset();
  13333. this._activeSkeletons.reset();
  13334. this._softwareSkinnedMeshes.reset();
  13335. this._boundingBoxRenderer.reset();
  13336. this._edgesRenderers.reset();
  13337. if (!this._frustumPlanes) {
  13338. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13339. }
  13340. else {
  13341. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13342. }
  13343. // Meshes
  13344. var meshes;
  13345. var len;
  13346. if (this._selectionOctree) {
  13347. var selection = this._selectionOctree.select(this._frustumPlanes);
  13348. meshes = selection.data;
  13349. len = selection.length;
  13350. }
  13351. else {
  13352. len = this.meshes.length;
  13353. meshes = this.meshes;
  13354. }
  13355. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13356. var mesh = meshes[meshIndex];
  13357. if (mesh.isBlocked) {
  13358. continue;
  13359. }
  13360. this._totalVertices += mesh.getTotalVertices();
  13361. if (!mesh.isReady() || !mesh.isEnabled()) {
  13362. continue;
  13363. }
  13364. mesh.computeWorldMatrix();
  13365. // Intersections
  13366. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13367. this._meshesForIntersections.pushNoDuplicate(mesh);
  13368. }
  13369. // Switch to current LOD
  13370. var meshLOD = mesh.getLOD(this.activeCamera);
  13371. if (!meshLOD) {
  13372. continue;
  13373. }
  13374. mesh._preActivate();
  13375. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13376. this._activeMeshes.push(mesh);
  13377. this.activeCamera._activeMeshes.push(mesh);
  13378. mesh._activate(this._renderId);
  13379. this._activeMesh(meshLOD);
  13380. }
  13381. }
  13382. // Particle systems
  13383. var beforeParticlesDate = BABYLON.Tools.Now;
  13384. if (this.particlesEnabled) {
  13385. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13386. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13387. var particleSystem = this.particleSystems[particleIndex];
  13388. if (!particleSystem.isStarted()) {
  13389. continue;
  13390. }
  13391. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13392. this._activeParticleSystems.push(particleSystem);
  13393. particleSystem.animate();
  13394. }
  13395. }
  13396. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13397. }
  13398. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13399. };
  13400. Scene.prototype._activeMesh = function (mesh) {
  13401. if (mesh.skeleton && this.skeletonsEnabled) {
  13402. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13403. if (!mesh.computeBonesUsingShaders) {
  13404. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13405. }
  13406. }
  13407. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13408. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13409. }
  13410. if (mesh._edgesRenderer) {
  13411. this._edgesRenderers.push(mesh._edgesRenderer);
  13412. }
  13413. if (mesh && mesh.subMeshes) {
  13414. // Submeshes Octrees
  13415. var len;
  13416. var subMeshes;
  13417. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13418. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13419. len = intersections.length;
  13420. subMeshes = intersections.data;
  13421. }
  13422. else {
  13423. subMeshes = mesh.subMeshes;
  13424. len = subMeshes.length;
  13425. }
  13426. for (var subIndex = 0; subIndex < len; subIndex++) {
  13427. var subMesh = subMeshes[subIndex];
  13428. this._evaluateSubMesh(subMesh, mesh);
  13429. }
  13430. }
  13431. };
  13432. Scene.prototype.updateTransformMatrix = function (force) {
  13433. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13434. };
  13435. Scene.prototype._renderForCamera = function (camera) {
  13436. var engine = this._engine;
  13437. this.activeCamera = camera;
  13438. if (!this.activeCamera)
  13439. throw new Error("Active camera not set");
  13440. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13441. // Viewport
  13442. engine.setViewport(this.activeCamera.viewport);
  13443. // Camera
  13444. this.resetCachedMaterial();
  13445. this._renderId++;
  13446. this.updateTransformMatrix();
  13447. if (this.beforeCameraRender) {
  13448. this.beforeCameraRender(this.activeCamera);
  13449. }
  13450. // Meshes
  13451. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13452. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13453. this._evaluateActiveMeshes();
  13454. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13455. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13456. // Skeletons
  13457. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13458. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13459. skeleton.prepare();
  13460. }
  13461. // Software skinning
  13462. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13463. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13464. mesh.applySkeleton(mesh.skeleton);
  13465. }
  13466. // Render targets
  13467. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13468. if (this.renderTargetsEnabled) {
  13469. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13470. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13471. var renderTarget = this._renderTargets.data[renderIndex];
  13472. if (renderTarget._shouldRender()) {
  13473. this._renderId++;
  13474. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13475. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13476. }
  13477. }
  13478. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13479. this._renderId++;
  13480. }
  13481. if (this._renderTargets.length > 0) {
  13482. engine.restoreDefaultFramebuffer();
  13483. }
  13484. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13485. // Prepare Frame
  13486. this.postProcessManager._prepareFrame();
  13487. var beforeRenderDate = BABYLON.Tools.Now;
  13488. // Backgrounds
  13489. var layerIndex;
  13490. var layer;
  13491. if (this.layers.length) {
  13492. engine.setDepthBuffer(false);
  13493. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13494. layer = this.layers[layerIndex];
  13495. if (layer.isBackground) {
  13496. layer.render();
  13497. }
  13498. }
  13499. engine.setDepthBuffer(true);
  13500. }
  13501. // Render
  13502. BABYLON.Tools.StartPerformanceCounter("Main render");
  13503. this._renderingManager.render(null, null, true, true);
  13504. BABYLON.Tools.EndPerformanceCounter("Main render");
  13505. // Bounding boxes
  13506. this._boundingBoxRenderer.render();
  13507. // Edges
  13508. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13509. this._edgesRenderers.data[edgesRendererIndex].render();
  13510. }
  13511. // Lens flares
  13512. if (this.lensFlaresEnabled) {
  13513. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13514. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13515. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13516. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13517. lensFlareSystem.render();
  13518. }
  13519. }
  13520. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13521. }
  13522. // Foregrounds
  13523. if (this.layers.length) {
  13524. engine.setDepthBuffer(false);
  13525. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13526. layer = this.layers[layerIndex];
  13527. if (!layer.isBackground) {
  13528. layer.render();
  13529. }
  13530. }
  13531. engine.setDepthBuffer(true);
  13532. }
  13533. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13534. // Finalize frame
  13535. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13536. // Update camera
  13537. this.activeCamera._updateFromScene();
  13538. // Reset some special arrays
  13539. this._renderTargets.reset();
  13540. if (this.afterCameraRender) {
  13541. this.afterCameraRender(this.activeCamera);
  13542. }
  13543. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13544. };
  13545. Scene.prototype._processSubCameras = function (camera) {
  13546. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13547. this._renderForCamera(camera);
  13548. return;
  13549. }
  13550. // rig cameras
  13551. for (var index = 0; index < camera._rigCameras.length; index++) {
  13552. this._renderForCamera(camera._rigCameras[index]);
  13553. }
  13554. this.activeCamera = camera;
  13555. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13556. // Update camera
  13557. this.activeCamera._updateFromScene();
  13558. };
  13559. Scene.prototype._checkIntersections = function () {
  13560. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13561. var sourceMesh = this._meshesForIntersections.data[index];
  13562. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13563. var action = sourceMesh.actionManager.actions[actionIndex];
  13564. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13565. var parameters = action.getTriggerParameter();
  13566. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13567. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13568. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13569. if (areIntersecting && currentIntersectionInProgress === -1) {
  13570. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13571. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13572. sourceMesh._intersectionsInProgress.push(otherMesh);
  13573. }
  13574. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13575. sourceMesh._intersectionsInProgress.push(otherMesh);
  13576. }
  13577. }
  13578. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13579. //They intersected, and now they don't.
  13580. //is this trigger an exit trigger? execute an event.
  13581. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13582. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13583. }
  13584. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13585. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13586. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13587. }
  13588. }
  13589. }
  13590. }
  13591. }
  13592. };
  13593. Scene.prototype.render = function () {
  13594. var startDate = BABYLON.Tools.Now;
  13595. this._particlesDuration = 0;
  13596. this._spritesDuration = 0;
  13597. this._activeParticles = 0;
  13598. this._renderDuration = 0;
  13599. this._renderTargetsDuration = 0;
  13600. this._evaluateActiveMeshesDuration = 0;
  13601. this._totalVertices = 0;
  13602. this._activeIndices = 0;
  13603. this._activeBones = 0;
  13604. this.getEngine().resetDrawCalls();
  13605. this._meshesForIntersections.reset();
  13606. this.resetCachedMaterial();
  13607. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13608. // Actions
  13609. if (this.actionManager) {
  13610. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13611. }
  13612. //Simplification Queue
  13613. if (!this.simplificationQueue.running) {
  13614. this.simplificationQueue.executeNext();
  13615. }
  13616. // Animations
  13617. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13618. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13619. this._animate();
  13620. // Physics
  13621. if (this._physicsEngine) {
  13622. BABYLON.Tools.StartPerformanceCounter("Physics");
  13623. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13624. BABYLON.Tools.EndPerformanceCounter("Physics");
  13625. }
  13626. // Before render
  13627. if (this.beforeRender) {
  13628. this.beforeRender();
  13629. }
  13630. var callbackIndex;
  13631. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13632. this._onBeforeRenderCallbacks[callbackIndex]();
  13633. }
  13634. // Customs render targets
  13635. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13636. var engine = this.getEngine();
  13637. var currentActiveCamera = this.activeCamera;
  13638. if (this.renderTargetsEnabled) {
  13639. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13640. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13641. var renderTarget = this.customRenderTargets[customIndex];
  13642. if (renderTarget._shouldRender()) {
  13643. this._renderId++;
  13644. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13645. if (!this.activeCamera)
  13646. throw new Error("Active camera not set");
  13647. // Viewport
  13648. engine.setViewport(this.activeCamera.viewport);
  13649. // Camera
  13650. this.updateTransformMatrix();
  13651. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13652. }
  13653. }
  13654. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13655. this._renderId++;
  13656. }
  13657. if (this.customRenderTargets.length > 0) {
  13658. engine.restoreDefaultFramebuffer();
  13659. }
  13660. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13661. this.activeCamera = currentActiveCamera;
  13662. // Procedural textures
  13663. if (this.proceduralTexturesEnabled) {
  13664. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13665. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13666. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13667. if (proceduralTexture._shouldRender()) {
  13668. proceduralTexture.render();
  13669. }
  13670. }
  13671. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13672. }
  13673. // Clear
  13674. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13675. // Shadows
  13676. if (this.shadowsEnabled) {
  13677. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13678. var light = this.lights[lightIndex];
  13679. var shadowGenerator = light.getShadowGenerator();
  13680. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13681. this._renderTargets.push(shadowGenerator.getShadowMap());
  13682. }
  13683. }
  13684. }
  13685. // Depth renderer
  13686. if (this._depthRenderer) {
  13687. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13688. }
  13689. // RenderPipeline
  13690. this.postProcessRenderPipelineManager.update();
  13691. // Multi-cameras?
  13692. if (this.activeCameras.length > 0) {
  13693. var currentRenderId = this._renderId;
  13694. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13695. this._renderId = currentRenderId;
  13696. this._processSubCameras(this.activeCameras[cameraIndex]);
  13697. }
  13698. }
  13699. else {
  13700. if (!this.activeCamera) {
  13701. throw new Error("No camera defined");
  13702. }
  13703. this._processSubCameras(this.activeCamera);
  13704. }
  13705. // Intersection checks
  13706. this._checkIntersections();
  13707. // Update the audio listener attached to the camera
  13708. this._updateAudioParameters();
  13709. // After render
  13710. if (this.afterRender) {
  13711. this.afterRender();
  13712. }
  13713. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13714. this._onAfterRenderCallbacks[callbackIndex]();
  13715. }
  13716. // Cleaning
  13717. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13718. this._toBeDisposed.data[index].dispose();
  13719. this._toBeDisposed[index] = null;
  13720. }
  13721. this._toBeDisposed.reset();
  13722. if (this.dumpNextRenderTargets) {
  13723. this.dumpNextRenderTargets = false;
  13724. }
  13725. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13726. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13727. };
  13728. Scene.prototype._updateAudioParameters = function () {
  13729. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13730. return;
  13731. }
  13732. var listeningCamera;
  13733. var audioEngine = BABYLON.Engine.audioEngine;
  13734. if (this.activeCameras.length > 0) {
  13735. listeningCamera = this.activeCameras[0];
  13736. }
  13737. else {
  13738. listeningCamera = this.activeCamera;
  13739. }
  13740. if (listeningCamera && audioEngine.canUseWebAudio) {
  13741. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13742. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13743. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13744. cameraDirection.normalize();
  13745. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13746. var i;
  13747. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13748. var sound = this.mainSoundTrack.soundCollection[i];
  13749. if (sound.useCustomAttenuation) {
  13750. sound.updateDistanceFromListener();
  13751. }
  13752. }
  13753. for (i = 0; i < this.soundTracks.length; i++) {
  13754. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13755. sound = this.soundTracks[i].soundCollection[j];
  13756. if (sound.useCustomAttenuation) {
  13757. sound.updateDistanceFromListener();
  13758. }
  13759. }
  13760. }
  13761. }
  13762. };
  13763. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13764. // Audio
  13765. get: function () {
  13766. return this._audioEnabled;
  13767. },
  13768. set: function (value) {
  13769. this._audioEnabled = value;
  13770. if (this._audioEnabled) {
  13771. this._enableAudio();
  13772. }
  13773. else {
  13774. this._disableAudio();
  13775. }
  13776. },
  13777. enumerable: true,
  13778. configurable: true
  13779. });
  13780. Scene.prototype._disableAudio = function () {
  13781. var i;
  13782. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13783. this.mainSoundTrack.soundCollection[i].pause();
  13784. }
  13785. for (i = 0; i < this.soundTracks.length; i++) {
  13786. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13787. this.soundTracks[i].soundCollection[j].pause();
  13788. }
  13789. }
  13790. };
  13791. Scene.prototype._enableAudio = function () {
  13792. var i;
  13793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13794. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13795. this.mainSoundTrack.soundCollection[i].play();
  13796. }
  13797. }
  13798. for (i = 0; i < this.soundTracks.length; i++) {
  13799. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13800. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13801. this.soundTracks[i].soundCollection[j].play();
  13802. }
  13803. }
  13804. }
  13805. };
  13806. Object.defineProperty(Scene.prototype, "headphone", {
  13807. get: function () {
  13808. return this._headphone;
  13809. },
  13810. set: function (value) {
  13811. this._headphone = value;
  13812. if (this._headphone) {
  13813. this._switchAudioModeForHeadphones();
  13814. }
  13815. else {
  13816. this._switchAudioModeForNormalSpeakers();
  13817. }
  13818. },
  13819. enumerable: true,
  13820. configurable: true
  13821. });
  13822. Scene.prototype._switchAudioModeForHeadphones = function () {
  13823. this.mainSoundTrack.switchPanningModelToHRTF();
  13824. for (var i = 0; i < this.soundTracks.length; i++) {
  13825. this.soundTracks[i].switchPanningModelToHRTF();
  13826. }
  13827. };
  13828. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13829. this.mainSoundTrack.switchPanningModelToEqualPower();
  13830. for (var i = 0; i < this.soundTracks.length; i++) {
  13831. this.soundTracks[i].switchPanningModelToEqualPower();
  13832. }
  13833. };
  13834. Scene.prototype.enableDepthRenderer = function () {
  13835. if (this._depthRenderer) {
  13836. return this._depthRenderer;
  13837. }
  13838. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13839. return this._depthRenderer;
  13840. };
  13841. Scene.prototype.disableDepthRenderer = function () {
  13842. if (!this._depthRenderer) {
  13843. return;
  13844. }
  13845. this._depthRenderer.dispose();
  13846. this._depthRenderer = null;
  13847. };
  13848. Scene.prototype.dispose = function () {
  13849. this.beforeRender = null;
  13850. this.afterRender = null;
  13851. this.skeletons = [];
  13852. this._boundingBoxRenderer.dispose();
  13853. if (this._depthRenderer) {
  13854. this._depthRenderer.dispose();
  13855. }
  13856. // Debug layer
  13857. this.debugLayer.hide();
  13858. // Events
  13859. if (this.onDispose) {
  13860. this.onDispose();
  13861. }
  13862. this._onBeforeRenderCallbacks = [];
  13863. this._onAfterRenderCallbacks = [];
  13864. this.detachControl();
  13865. // Release sounds & sounds tracks
  13866. this.disposeSounds();
  13867. // Detach cameras
  13868. var canvas = this._engine.getRenderingCanvas();
  13869. var index;
  13870. for (index = 0; index < this.cameras.length; index++) {
  13871. this.cameras[index].detachControl(canvas);
  13872. }
  13873. // Release lights
  13874. while (this.lights.length) {
  13875. this.lights[0].dispose();
  13876. }
  13877. // Release meshes
  13878. while (this.meshes.length) {
  13879. this.meshes[0].dispose(true);
  13880. }
  13881. // Release cameras
  13882. while (this.cameras.length) {
  13883. this.cameras[0].dispose();
  13884. }
  13885. // Release materials
  13886. while (this.materials.length) {
  13887. this.materials[0].dispose();
  13888. }
  13889. // Release particles
  13890. while (this.particleSystems.length) {
  13891. this.particleSystems[0].dispose();
  13892. }
  13893. // Release sprites
  13894. while (this.spriteManagers.length) {
  13895. this.spriteManagers[0].dispose();
  13896. }
  13897. // Release layers
  13898. while (this.layers.length) {
  13899. this.layers[0].dispose();
  13900. }
  13901. // Release textures
  13902. while (this.textures.length) {
  13903. this.textures[0].dispose();
  13904. }
  13905. // Post-processes
  13906. this.postProcessManager.dispose();
  13907. // Physics
  13908. if (this._physicsEngine) {
  13909. this.disablePhysicsEngine();
  13910. }
  13911. // Remove from engine
  13912. index = this._engine.scenes.indexOf(this);
  13913. if (index > -1) {
  13914. this._engine.scenes.splice(index, 1);
  13915. }
  13916. this._engine.wipeCaches();
  13917. };
  13918. // Release sounds & sounds tracks
  13919. Scene.prototype.disposeSounds = function () {
  13920. this.mainSoundTrack.dispose();
  13921. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13922. this.soundTracks[scIndex].dispose();
  13923. }
  13924. };
  13925. // Octrees
  13926. Scene.prototype.getWorldExtends = function () {
  13927. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13928. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13929. for (var index = 0; index < this.meshes.length; index++) {
  13930. var mesh = this.meshes[index];
  13931. mesh.computeWorldMatrix(true);
  13932. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13933. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13934. BABYLON.Tools.CheckExtends(minBox, min, max);
  13935. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13936. }
  13937. return {
  13938. min: min,
  13939. max: max
  13940. };
  13941. };
  13942. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13943. if (maxCapacity === void 0) { maxCapacity = 64; }
  13944. if (maxDepth === void 0) { maxDepth = 2; }
  13945. if (!this._selectionOctree) {
  13946. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13947. }
  13948. var worldExtends = this.getWorldExtends();
  13949. // Update octree
  13950. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13951. return this._selectionOctree;
  13952. };
  13953. // Picking
  13954. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13955. var engine = this._engine;
  13956. if (!camera) {
  13957. if (!this.activeCamera)
  13958. throw new Error("Active camera not set");
  13959. camera = this.activeCamera;
  13960. }
  13961. var cameraViewport = camera.viewport;
  13962. var viewport = cameraViewport.toGlobal(engine);
  13963. // Moving coordinates to local viewport world
  13964. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13965. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13966. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13967. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13968. };
  13969. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13970. var pickingInfo = null;
  13971. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13972. var mesh = this.meshes[meshIndex];
  13973. if (predicate) {
  13974. if (!predicate(mesh)) {
  13975. continue;
  13976. }
  13977. }
  13978. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13979. continue;
  13980. }
  13981. var world = mesh.getWorldMatrix();
  13982. var ray = rayFunction(world);
  13983. var result = mesh.intersects(ray, fastCheck);
  13984. if (!result || !result.hit)
  13985. continue;
  13986. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13987. continue;
  13988. pickingInfo = result;
  13989. if (fastCheck) {
  13990. break;
  13991. }
  13992. }
  13993. return pickingInfo || new BABYLON.PickingInfo();
  13994. };
  13995. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13996. var _this = this;
  13997. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13998. /// <param name="x">X position on screen</param>
  13999. /// <param name="y">Y position on screen</param>
  14000. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14001. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14002. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14003. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14004. };
  14005. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14006. var _this = this;
  14007. return this._internalPick(function (world) {
  14008. if (!_this._pickWithRayInverseMatrix) {
  14009. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14010. }
  14011. world.invertToRef(_this._pickWithRayInverseMatrix);
  14012. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14013. }, predicate, fastCheck);
  14014. };
  14015. Scene.prototype.setPointerOverMesh = function (mesh) {
  14016. if (this._pointerOverMesh === mesh) {
  14017. return;
  14018. }
  14019. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14020. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14021. }
  14022. this._pointerOverMesh = mesh;
  14023. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14024. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14025. }
  14026. };
  14027. Scene.prototype.getPointerOverMesh = function () {
  14028. return this._pointerOverMesh;
  14029. };
  14030. // Physics
  14031. Scene.prototype.getPhysicsEngine = function () {
  14032. return this._physicsEngine;
  14033. };
  14034. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14035. if (this._physicsEngine) {
  14036. return true;
  14037. }
  14038. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14039. if (!this._physicsEngine.isSupported()) {
  14040. this._physicsEngine = null;
  14041. return false;
  14042. }
  14043. this._physicsEngine._initialize(gravity);
  14044. return true;
  14045. };
  14046. Scene.prototype.disablePhysicsEngine = function () {
  14047. if (!this._physicsEngine) {
  14048. return;
  14049. }
  14050. this._physicsEngine.dispose();
  14051. this._physicsEngine = undefined;
  14052. };
  14053. Scene.prototype.isPhysicsEnabled = function () {
  14054. return this._physicsEngine !== undefined;
  14055. };
  14056. Scene.prototype.setGravity = function (gravity) {
  14057. if (!this._physicsEngine) {
  14058. return;
  14059. }
  14060. this._physicsEngine._setGravity(gravity);
  14061. };
  14062. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14063. if (parts.parts) {
  14064. options = parts;
  14065. parts = parts.parts;
  14066. }
  14067. if (!this._physicsEngine) {
  14068. return null;
  14069. }
  14070. for (var index = 0; index < parts.length; index++) {
  14071. var mesh = parts[index].mesh;
  14072. mesh._physicImpostor = parts[index].impostor;
  14073. mesh._physicsMass = options.mass / parts.length;
  14074. mesh._physicsFriction = options.friction;
  14075. mesh._physicRestitution = options.restitution;
  14076. }
  14077. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14078. };
  14079. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14080. for (var index = 0; index < compound.parts.length; index++) {
  14081. var mesh = compound.parts[index].mesh;
  14082. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14083. this._physicsEngine._unregisterMesh(mesh);
  14084. }
  14085. };
  14086. // Misc.
  14087. Scene.prototype.createDefaultCameraOrLight = function () {
  14088. // Light
  14089. if (this.lights.length === 0) {
  14090. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14091. }
  14092. // Camera
  14093. if (!this.activeCamera) {
  14094. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14095. // Compute position
  14096. var worldExtends = this.getWorldExtends();
  14097. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14098. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14099. camera.setTarget(worldCenter);
  14100. this.activeCamera = camera;
  14101. }
  14102. };
  14103. // Tags
  14104. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14105. if (tagsQuery === undefined) {
  14106. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14107. return list;
  14108. }
  14109. var listByTags = [];
  14110. forEach = forEach || (function (item) { return; });
  14111. for (var i in list) {
  14112. var item = list[i];
  14113. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14114. listByTags.push(item);
  14115. forEach(item);
  14116. }
  14117. }
  14118. return listByTags;
  14119. };
  14120. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14121. return this._getByTags(this.meshes, tagsQuery, forEach);
  14122. };
  14123. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14124. return this._getByTags(this.cameras, tagsQuery, forEach);
  14125. };
  14126. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14127. return this._getByTags(this.lights, tagsQuery, forEach);
  14128. };
  14129. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14130. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14131. };
  14132. // Statics
  14133. Scene._FOGMODE_NONE = 0;
  14134. Scene._FOGMODE_EXP = 1;
  14135. Scene._FOGMODE_EXP2 = 2;
  14136. Scene._FOGMODE_LINEAR = 3;
  14137. Scene.MinDeltaTime = 1.0;
  14138. Scene.MaxDeltaTime = 1000.0;
  14139. return Scene;
  14140. })();
  14141. BABYLON.Scene = Scene;
  14142. })(BABYLON || (BABYLON = {}));
  14143. var BABYLON;
  14144. (function (BABYLON) {
  14145. var VertexBuffer = (function () {
  14146. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14147. if (engine instanceof BABYLON.Mesh) {
  14148. this._engine = engine.getScene().getEngine();
  14149. }
  14150. else {
  14151. this._engine = engine;
  14152. }
  14153. this._updatable = updatable;
  14154. this._data = data;
  14155. if (!postponeInternalCreation) {
  14156. this.create();
  14157. }
  14158. this._kind = kind;
  14159. if (stride) {
  14160. this._strideSize = stride;
  14161. return;
  14162. }
  14163. // Deduce stride from kind
  14164. switch (kind) {
  14165. case VertexBuffer.PositionKind:
  14166. this._strideSize = 3;
  14167. break;
  14168. case VertexBuffer.NormalKind:
  14169. this._strideSize = 3;
  14170. break;
  14171. case VertexBuffer.UVKind:
  14172. case VertexBuffer.UV2Kind:
  14173. case VertexBuffer.UV3Kind:
  14174. case VertexBuffer.UV4Kind:
  14175. case VertexBuffer.UV5Kind:
  14176. case VertexBuffer.UV6Kind:
  14177. this._strideSize = 2;
  14178. break;
  14179. case VertexBuffer.ColorKind:
  14180. this._strideSize = 4;
  14181. break;
  14182. case VertexBuffer.MatricesIndicesKind:
  14183. this._strideSize = 4;
  14184. break;
  14185. case VertexBuffer.MatricesWeightsKind:
  14186. this._strideSize = 4;
  14187. break;
  14188. }
  14189. }
  14190. // Properties
  14191. VertexBuffer.prototype.isUpdatable = function () {
  14192. return this._updatable;
  14193. };
  14194. VertexBuffer.prototype.getData = function () {
  14195. return this._data;
  14196. };
  14197. VertexBuffer.prototype.getBuffer = function () {
  14198. return this._buffer;
  14199. };
  14200. VertexBuffer.prototype.getStrideSize = function () {
  14201. return this._strideSize;
  14202. };
  14203. // Methods
  14204. VertexBuffer.prototype.create = function (data) {
  14205. if (!data && this._buffer) {
  14206. return; // nothing to do
  14207. }
  14208. data = data || this._data;
  14209. if (!this._buffer) {
  14210. if (this._updatable) {
  14211. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14212. }
  14213. else {
  14214. this._buffer = this._engine.createVertexBuffer(data);
  14215. }
  14216. }
  14217. if (this._updatable) {
  14218. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14219. this._data = data;
  14220. }
  14221. };
  14222. VertexBuffer.prototype.update = function (data) {
  14223. this.create(data);
  14224. };
  14225. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14226. if (!this._buffer) {
  14227. return;
  14228. }
  14229. if (this._updatable) {
  14230. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14231. this._data = null;
  14232. }
  14233. };
  14234. VertexBuffer.prototype.dispose = function () {
  14235. if (!this._buffer) {
  14236. return;
  14237. }
  14238. if (this._engine._releaseBuffer(this._buffer)) {
  14239. this._buffer = null;
  14240. }
  14241. };
  14242. Object.defineProperty(VertexBuffer, "PositionKind", {
  14243. get: function () {
  14244. return VertexBuffer._PositionKind;
  14245. },
  14246. enumerable: true,
  14247. configurable: true
  14248. });
  14249. Object.defineProperty(VertexBuffer, "NormalKind", {
  14250. get: function () {
  14251. return VertexBuffer._NormalKind;
  14252. },
  14253. enumerable: true,
  14254. configurable: true
  14255. });
  14256. Object.defineProperty(VertexBuffer, "UVKind", {
  14257. get: function () {
  14258. return VertexBuffer._UVKind;
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14264. get: function () {
  14265. return VertexBuffer._UV2Kind;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14271. get: function () {
  14272. return VertexBuffer._UV3Kind;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14278. get: function () {
  14279. return VertexBuffer._UV4Kind;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14285. get: function () {
  14286. return VertexBuffer._UV5Kind;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14292. get: function () {
  14293. return VertexBuffer._UV6Kind;
  14294. },
  14295. enumerable: true,
  14296. configurable: true
  14297. });
  14298. Object.defineProperty(VertexBuffer, "ColorKind", {
  14299. get: function () {
  14300. return VertexBuffer._ColorKind;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14306. get: function () {
  14307. return VertexBuffer._MatricesIndicesKind;
  14308. },
  14309. enumerable: true,
  14310. configurable: true
  14311. });
  14312. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14313. get: function () {
  14314. return VertexBuffer._MatricesWeightsKind;
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. // Enums
  14320. VertexBuffer._PositionKind = "position";
  14321. VertexBuffer._NormalKind = "normal";
  14322. VertexBuffer._UVKind = "uv";
  14323. VertexBuffer._UV2Kind = "uv2";
  14324. VertexBuffer._UV3Kind = "uv3";
  14325. VertexBuffer._UV4Kind = "uv4";
  14326. VertexBuffer._UV5Kind = "uv5";
  14327. VertexBuffer._UV6Kind = "uv6";
  14328. VertexBuffer._ColorKind = "color";
  14329. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14330. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14331. return VertexBuffer;
  14332. })();
  14333. BABYLON.VertexBuffer = VertexBuffer;
  14334. })(BABYLON || (BABYLON = {}));
  14335. var BABYLON;
  14336. (function (BABYLON) {
  14337. /**
  14338. * Creates an instance based on a source mesh.
  14339. */
  14340. var InstancedMesh = (function (_super) {
  14341. __extends(InstancedMesh, _super);
  14342. function InstancedMesh(name, source) {
  14343. _super.call(this, name, source.getScene());
  14344. source.instances.push(this);
  14345. this._sourceMesh = source;
  14346. this.position.copyFrom(source.position);
  14347. this.rotation.copyFrom(source.rotation);
  14348. this.scaling.copyFrom(source.scaling);
  14349. if (source.rotationQuaternion) {
  14350. this.rotationQuaternion = source.rotationQuaternion.clone();
  14351. }
  14352. this.infiniteDistance = source.infiniteDistance;
  14353. this.setPivotMatrix(source.getPivotMatrix());
  14354. this.refreshBoundingInfo();
  14355. this._syncSubMeshes();
  14356. }
  14357. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14358. // Methods
  14359. get: function () {
  14360. return this._sourceMesh.receiveShadows;
  14361. },
  14362. enumerable: true,
  14363. configurable: true
  14364. });
  14365. Object.defineProperty(InstancedMesh.prototype, "material", {
  14366. get: function () {
  14367. return this._sourceMesh.material;
  14368. },
  14369. enumerable: true,
  14370. configurable: true
  14371. });
  14372. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14373. get: function () {
  14374. return this._sourceMesh.visibility;
  14375. },
  14376. enumerable: true,
  14377. configurable: true
  14378. });
  14379. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14380. get: function () {
  14381. return this._sourceMesh.skeleton;
  14382. },
  14383. enumerable: true,
  14384. configurable: true
  14385. });
  14386. InstancedMesh.prototype.getTotalVertices = function () {
  14387. return this._sourceMesh.getTotalVertices();
  14388. };
  14389. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14390. get: function () {
  14391. return this._sourceMesh;
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. InstancedMesh.prototype.getVerticesData = function (kind) {
  14397. return this._sourceMesh.getVerticesData(kind);
  14398. };
  14399. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14400. return this._sourceMesh.isVerticesDataPresent(kind);
  14401. };
  14402. InstancedMesh.prototype.getIndices = function () {
  14403. return this._sourceMesh.getIndices();
  14404. };
  14405. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14406. get: function () {
  14407. return this._sourceMesh._positions;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14413. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14414. if (data) {
  14415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14416. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14417. }
  14418. this._updateBoundingInfo();
  14419. };
  14420. InstancedMesh.prototype._preActivate = function () {
  14421. if (this._currentLOD) {
  14422. this._currentLOD._preActivate();
  14423. }
  14424. };
  14425. InstancedMesh.prototype._activate = function (renderId) {
  14426. if (this._currentLOD) {
  14427. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14428. }
  14429. };
  14430. InstancedMesh.prototype.getLOD = function (camera) {
  14431. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14432. if (this._currentLOD === this.sourceMesh) {
  14433. return this;
  14434. }
  14435. return this._currentLOD;
  14436. };
  14437. InstancedMesh.prototype._syncSubMeshes = function () {
  14438. this.releaseSubMeshes();
  14439. if (this._sourceMesh.subMeshes) {
  14440. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14441. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14442. }
  14443. }
  14444. };
  14445. InstancedMesh.prototype._generatePointsArray = function () {
  14446. return this._sourceMesh._generatePointsArray();
  14447. };
  14448. // Clone
  14449. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14450. var result = this._sourceMesh.createInstance(name);
  14451. // Deep copy
  14452. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14453. // Bounding info
  14454. this.refreshBoundingInfo();
  14455. // Parent
  14456. if (newParent) {
  14457. result.parent = newParent;
  14458. }
  14459. if (!doNotCloneChildren) {
  14460. // Children
  14461. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14462. var mesh = this.getScene().meshes[index];
  14463. if (mesh.parent === this) {
  14464. mesh.clone(mesh.name, result);
  14465. }
  14466. }
  14467. }
  14468. result.computeWorldMatrix(true);
  14469. return result;
  14470. };
  14471. // Dispoe
  14472. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14473. // Remove from mesh
  14474. var index = this._sourceMesh.instances.indexOf(this);
  14475. this._sourceMesh.instances.splice(index, 1);
  14476. _super.prototype.dispose.call(this, doNotRecurse);
  14477. };
  14478. return InstancedMesh;
  14479. })(BABYLON.AbstractMesh);
  14480. BABYLON.InstancedMesh = InstancedMesh;
  14481. })(BABYLON || (BABYLON = {}));
  14482. var BABYLON;
  14483. (function (BABYLON) {
  14484. var _InstancesBatch = (function () {
  14485. function _InstancesBatch() {
  14486. this.mustReturn = false;
  14487. this.visibleInstances = new Array();
  14488. this.renderSelf = new Array();
  14489. }
  14490. return _InstancesBatch;
  14491. })();
  14492. BABYLON._InstancesBatch = _InstancesBatch;
  14493. var Mesh = (function (_super) {
  14494. __extends(Mesh, _super);
  14495. /**
  14496. * @constructor
  14497. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14498. * @param {Scene} scene - The scene to add this mesh to.
  14499. * @param {Node} parent - The parent of this mesh, if it has one
  14500. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14501. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14502. * When false, achieved by calling a clone(), also passing False.
  14503. * This will make creation of children, recursive.
  14504. */
  14505. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14506. if (parent === void 0) { parent = null; }
  14507. _super.call(this, name, scene);
  14508. // Members
  14509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14510. this.instances = new Array();
  14511. this._LODLevels = new Array();
  14512. this._onBeforeRenderCallbacks = new Array();
  14513. this._onAfterRenderCallbacks = new Array();
  14514. this._visibleInstances = {};
  14515. this._renderIdForInstances = new Array();
  14516. this._batchCache = new _InstancesBatch();
  14517. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14518. this._sideOrientation = Mesh._DEFAULTSIDE;
  14519. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14520. if (source) {
  14521. // Geometry
  14522. if (source._geometry) {
  14523. source._geometry.applyToMesh(this);
  14524. }
  14525. // Deep copy
  14526. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14527. this.id = name + "." + source.id;
  14528. // Material
  14529. this.material = source.material;
  14530. if (!doNotCloneChildren) {
  14531. // Children
  14532. for (var index = 0; index < scene.meshes.length; index++) {
  14533. var mesh = scene.meshes[index];
  14534. if (mesh.parent === source) {
  14535. // doNotCloneChildren is always going to be False
  14536. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14537. }
  14538. }
  14539. }
  14540. // Particles
  14541. for (index = 0; index < scene.particleSystems.length; index++) {
  14542. var system = scene.particleSystems[index];
  14543. if (system.emitter === source) {
  14544. system.clone(system.name, this);
  14545. }
  14546. }
  14547. this.computeWorldMatrix(true);
  14548. }
  14549. // Parent
  14550. if (parent !== null) {
  14551. this.parent = parent;
  14552. }
  14553. }
  14554. Object.defineProperty(Mesh, "FRONTSIDE", {
  14555. get: function () {
  14556. return Mesh._FRONTSIDE;
  14557. },
  14558. enumerable: true,
  14559. configurable: true
  14560. });
  14561. Object.defineProperty(Mesh, "BACKSIDE", {
  14562. get: function () {
  14563. return Mesh._BACKSIDE;
  14564. },
  14565. enumerable: true,
  14566. configurable: true
  14567. });
  14568. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14569. get: function () {
  14570. return Mesh._DOUBLESIDE;
  14571. },
  14572. enumerable: true,
  14573. configurable: true
  14574. });
  14575. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14576. get: function () {
  14577. return Mesh._DEFAULTSIDE;
  14578. },
  14579. enumerable: true,
  14580. configurable: true
  14581. });
  14582. Object.defineProperty(Mesh, "NO_CAP", {
  14583. get: function () {
  14584. return Mesh._NO_CAP;
  14585. },
  14586. enumerable: true,
  14587. configurable: true
  14588. });
  14589. Object.defineProperty(Mesh, "CAP_START", {
  14590. get: function () {
  14591. return Mesh._CAP_START;
  14592. },
  14593. enumerable: true,
  14594. configurable: true
  14595. });
  14596. Object.defineProperty(Mesh, "CAP_END", {
  14597. get: function () {
  14598. return Mesh._CAP_END;
  14599. },
  14600. enumerable: true,
  14601. configurable: true
  14602. });
  14603. Object.defineProperty(Mesh, "CAP_ALL", {
  14604. get: function () {
  14605. return Mesh._CAP_ALL;
  14606. },
  14607. enumerable: true,
  14608. configurable: true
  14609. });
  14610. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14611. // Methods
  14612. get: function () {
  14613. return this._LODLevels.length > 0;
  14614. },
  14615. enumerable: true,
  14616. configurable: true
  14617. });
  14618. Mesh.prototype._sortLODLevels = function () {
  14619. this._LODLevels.sort(function (a, b) {
  14620. if (a.distance < b.distance) {
  14621. return 1;
  14622. }
  14623. if (a.distance > b.distance) {
  14624. return -1;
  14625. }
  14626. return 0;
  14627. });
  14628. };
  14629. /**
  14630. * Add a mesh as LOD level triggered at the given distance.
  14631. * @param {number} distance - the distance from the center of the object to show this level
  14632. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14633. * @return {BABYLON.Mesh} this mesh (for chaining)
  14634. */
  14635. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14636. if (mesh && mesh._masterMesh) {
  14637. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14638. return this;
  14639. }
  14640. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14641. this._LODLevels.push(level);
  14642. if (mesh) {
  14643. mesh._masterMesh = this;
  14644. }
  14645. this._sortLODLevels();
  14646. return this;
  14647. };
  14648. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14649. for (var index = 0; index < this._LODLevels.length; index++) {
  14650. var level = this._LODLevels[index];
  14651. if (level.distance === distance) {
  14652. return level.mesh;
  14653. }
  14654. }
  14655. return null;
  14656. };
  14657. /**
  14658. * Remove a mesh from the LOD array
  14659. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14660. * @return {BABYLON.Mesh} this mesh (for chaining)
  14661. */
  14662. Mesh.prototype.removeLODLevel = function (mesh) {
  14663. for (var index = 0; index < this._LODLevels.length; index++) {
  14664. if (this._LODLevels[index].mesh === mesh) {
  14665. this._LODLevels.splice(index, 1);
  14666. if (mesh) {
  14667. mesh._masterMesh = null;
  14668. }
  14669. }
  14670. }
  14671. this._sortLODLevels();
  14672. return this;
  14673. };
  14674. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14675. if (!this._LODLevels || this._LODLevels.length === 0) {
  14676. return this;
  14677. }
  14678. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14679. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14680. if (this.onLODLevelSelection) {
  14681. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14682. }
  14683. return this;
  14684. }
  14685. for (var index = 0; index < this._LODLevels.length; index++) {
  14686. var level = this._LODLevels[index];
  14687. if (level.distance < distanceToCamera) {
  14688. if (level.mesh) {
  14689. level.mesh._preActivate();
  14690. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14691. }
  14692. if (this.onLODLevelSelection) {
  14693. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14694. }
  14695. return level.mesh;
  14696. }
  14697. }
  14698. if (this.onLODLevelSelection) {
  14699. this.onLODLevelSelection(distanceToCamera, this, this);
  14700. }
  14701. return this;
  14702. };
  14703. Object.defineProperty(Mesh.prototype, "geometry", {
  14704. get: function () {
  14705. return this._geometry;
  14706. },
  14707. enumerable: true,
  14708. configurable: true
  14709. });
  14710. Mesh.prototype.getTotalVertices = function () {
  14711. if (!this._geometry) {
  14712. return 0;
  14713. }
  14714. return this._geometry.getTotalVertices();
  14715. };
  14716. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14717. if (!this._geometry) {
  14718. return null;
  14719. }
  14720. return this._geometry.getVerticesData(kind, copyWhenShared);
  14721. };
  14722. Mesh.prototype.getVertexBuffer = function (kind) {
  14723. if (!this._geometry) {
  14724. return undefined;
  14725. }
  14726. return this._geometry.getVertexBuffer(kind);
  14727. };
  14728. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14729. if (!this._geometry) {
  14730. if (this._delayInfo) {
  14731. return this._delayInfo.indexOf(kind) !== -1;
  14732. }
  14733. return false;
  14734. }
  14735. return this._geometry.isVerticesDataPresent(kind);
  14736. };
  14737. Mesh.prototype.getVerticesDataKinds = function () {
  14738. if (!this._geometry) {
  14739. var result = [];
  14740. if (this._delayInfo) {
  14741. for (var kind in this._delayInfo) {
  14742. result.push(kind);
  14743. }
  14744. }
  14745. return result;
  14746. }
  14747. return this._geometry.getVerticesDataKinds();
  14748. };
  14749. Mesh.prototype.getTotalIndices = function () {
  14750. if (!this._geometry) {
  14751. return 0;
  14752. }
  14753. return this._geometry.getTotalIndices();
  14754. };
  14755. Mesh.prototype.getIndices = function (copyWhenShared) {
  14756. if (!this._geometry) {
  14757. return [];
  14758. }
  14759. return this._geometry.getIndices(copyWhenShared);
  14760. };
  14761. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14762. get: function () {
  14763. return this._masterMesh !== null && this._masterMesh !== undefined;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Mesh.prototype.isReady = function () {
  14769. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14770. return false;
  14771. }
  14772. return _super.prototype.isReady.call(this);
  14773. };
  14774. Mesh.prototype.isDisposed = function () {
  14775. return this._isDisposed;
  14776. };
  14777. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14778. get: function () {
  14779. return this._sideOrientation;
  14780. },
  14781. set: function (sideO) {
  14782. this._sideOrientation = sideO;
  14783. },
  14784. enumerable: true,
  14785. configurable: true
  14786. });
  14787. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14788. get: function () {
  14789. return this._areNormalsFrozen;
  14790. },
  14791. enumerable: true,
  14792. configurable: true
  14793. });
  14794. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14795. Mesh.prototype.freezeNormals = function () {
  14796. this._areNormalsFrozen = true;
  14797. };
  14798. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14799. Mesh.prototype.unfreezeNormals = function () {
  14800. this._areNormalsFrozen = false;
  14801. };
  14802. // Methods
  14803. Mesh.prototype._preActivate = function () {
  14804. var sceneRenderId = this.getScene().getRenderId();
  14805. if (this._preActivateId === sceneRenderId) {
  14806. return;
  14807. }
  14808. this._preActivateId = sceneRenderId;
  14809. this._visibleInstances = null;
  14810. };
  14811. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14812. if (!this._visibleInstances) {
  14813. this._visibleInstances = {};
  14814. this._visibleInstances.defaultRenderId = renderId;
  14815. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14816. }
  14817. if (!this._visibleInstances[renderId]) {
  14818. this._visibleInstances[renderId] = new Array();
  14819. }
  14820. this._visibleInstances[renderId].push(instance);
  14821. };
  14822. Mesh.prototype.refreshBoundingInfo = function () {
  14823. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14824. if (data) {
  14825. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14826. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14827. }
  14828. if (this.subMeshes) {
  14829. for (var index = 0; index < this.subMeshes.length; index++) {
  14830. this.subMeshes[index].refreshBoundingInfo();
  14831. }
  14832. }
  14833. this._updateBoundingInfo();
  14834. };
  14835. Mesh.prototype._createGlobalSubMesh = function () {
  14836. var totalVertices = this.getTotalVertices();
  14837. if (!totalVertices || !this.getIndices()) {
  14838. return null;
  14839. }
  14840. this.releaseSubMeshes();
  14841. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14842. };
  14843. Mesh.prototype.subdivide = function (count) {
  14844. if (count < 1) {
  14845. return;
  14846. }
  14847. var totalIndices = this.getTotalIndices();
  14848. var subdivisionSize = (totalIndices / count) | 0;
  14849. var offset = 0;
  14850. // Ensure that subdivisionSize is a multiple of 3
  14851. while (subdivisionSize % 3 !== 0) {
  14852. subdivisionSize++;
  14853. }
  14854. this.releaseSubMeshes();
  14855. for (var index = 0; index < count; index++) {
  14856. if (offset >= totalIndices) {
  14857. break;
  14858. }
  14859. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14860. offset += subdivisionSize;
  14861. }
  14862. this.synchronizeInstances();
  14863. };
  14864. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14865. if (kind instanceof Array) {
  14866. var temp = data;
  14867. data = kind;
  14868. kind = temp;
  14869. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14870. }
  14871. if (!this._geometry) {
  14872. var vertexData = new BABYLON.VertexData();
  14873. vertexData.set(data, kind);
  14874. var scene = this.getScene();
  14875. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14876. }
  14877. else {
  14878. this._geometry.setVerticesData(kind, data, updatable, stride);
  14879. }
  14880. };
  14881. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14882. if (!this._geometry) {
  14883. return;
  14884. }
  14885. if (!makeItUnique) {
  14886. this._geometry.updateVerticesData(kind, data, updateExtends);
  14887. }
  14888. else {
  14889. this.makeGeometryUnique();
  14890. this.updateVerticesData(kind, data, updateExtends, false);
  14891. }
  14892. };
  14893. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14894. if (!this._geometry) {
  14895. return;
  14896. }
  14897. if (!makeItUnique) {
  14898. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14899. }
  14900. else {
  14901. this.makeGeometryUnique();
  14902. this.updateVerticesDataDirectly(kind, data, offset, false);
  14903. }
  14904. };
  14905. // Mesh positions update function :
  14906. // updates the mesh positions according to the positionFunction returned values.
  14907. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14908. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14909. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14910. if (computeNormals === void 0) { computeNormals = true; }
  14911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14912. positionFunction(positions);
  14913. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14914. if (computeNormals) {
  14915. var indices = this.getIndices();
  14916. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14917. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14918. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14919. }
  14920. };
  14921. Mesh.prototype.makeGeometryUnique = function () {
  14922. if (!this._geometry) {
  14923. return;
  14924. }
  14925. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14926. geometry.applyToMesh(this);
  14927. };
  14928. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14929. if (!this._geometry) {
  14930. var vertexData = new BABYLON.VertexData();
  14931. vertexData.indices = indices;
  14932. var scene = this.getScene();
  14933. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14934. }
  14935. else {
  14936. this._geometry.setIndices(indices, totalVertices);
  14937. }
  14938. };
  14939. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14940. var engine = this.getScene().getEngine();
  14941. // Wireframe
  14942. var indexToBind;
  14943. switch (fillMode) {
  14944. case BABYLON.Material.PointFillMode:
  14945. indexToBind = null;
  14946. break;
  14947. case BABYLON.Material.WireFrameFillMode:
  14948. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14949. break;
  14950. default:
  14951. case BABYLON.Material.TriangleFillMode:
  14952. indexToBind = this._geometry.getIndexBuffer();
  14953. break;
  14954. }
  14955. // VBOs
  14956. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14957. };
  14958. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14959. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14960. return;
  14961. }
  14962. var engine = this.getScene().getEngine();
  14963. // Draw order
  14964. switch (fillMode) {
  14965. case BABYLON.Material.PointFillMode:
  14966. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14967. break;
  14968. case BABYLON.Material.WireFrameFillMode:
  14969. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14970. break;
  14971. default:
  14972. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14973. }
  14974. };
  14975. Mesh.prototype.registerBeforeRender = function (func) {
  14976. this._onBeforeRenderCallbacks.push(func);
  14977. };
  14978. Mesh.prototype.unregisterBeforeRender = function (func) {
  14979. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14980. if (index > -1) {
  14981. this._onBeforeRenderCallbacks.splice(index, 1);
  14982. }
  14983. };
  14984. Mesh.prototype.registerAfterRender = function (func) {
  14985. this._onAfterRenderCallbacks.push(func);
  14986. };
  14987. Mesh.prototype.unregisterAfterRender = function (func) {
  14988. var index = this._onAfterRenderCallbacks.indexOf(func);
  14989. if (index > -1) {
  14990. this._onAfterRenderCallbacks.splice(index, 1);
  14991. }
  14992. };
  14993. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14994. var scene = this.getScene();
  14995. this._batchCache.mustReturn = false;
  14996. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14997. this._batchCache.visibleInstances[subMeshId] = null;
  14998. if (this._visibleInstances) {
  14999. var currentRenderId = scene.getRenderId();
  15000. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15001. var selfRenderId = this._renderId;
  15002. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15003. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15004. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15005. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15006. }
  15007. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15008. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15009. this._batchCache.mustReturn = true;
  15010. return this._batchCache;
  15011. }
  15012. if (currentRenderId !== selfRenderId) {
  15013. this._batchCache.renderSelf[subMeshId] = false;
  15014. }
  15015. }
  15016. this._renderIdForInstances[subMeshId] = currentRenderId;
  15017. }
  15018. return this._batchCache;
  15019. };
  15020. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15021. var visibleInstances = batch.visibleInstances[subMesh._id];
  15022. var matricesCount = visibleInstances.length + 1;
  15023. var bufferSize = matricesCount * 16 * 4;
  15024. while (this._instancesBufferSize < bufferSize) {
  15025. this._instancesBufferSize *= 2;
  15026. }
  15027. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15028. if (this._worldMatricesInstancesBuffer) {
  15029. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15030. }
  15031. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15032. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15033. }
  15034. var offset = 0;
  15035. var instancesCount = 0;
  15036. var world = this.getWorldMatrix();
  15037. if (batch.renderSelf[subMesh._id]) {
  15038. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15039. offset += 16;
  15040. instancesCount++;
  15041. }
  15042. if (visibleInstances) {
  15043. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15044. var instance = visibleInstances[instanceIndex];
  15045. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15046. offset += 16;
  15047. instancesCount++;
  15048. }
  15049. }
  15050. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15051. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15052. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15053. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15054. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15055. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15056. this._draw(subMesh, fillMode, instancesCount);
  15057. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15058. };
  15059. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15060. var scene = this.getScene();
  15061. var engine = scene.getEngine();
  15062. if (hardwareInstancedRendering) {
  15063. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15064. }
  15065. else {
  15066. if (batch.renderSelf[subMesh._id]) {
  15067. // Draw
  15068. if (onBeforeDraw) {
  15069. onBeforeDraw(false, this.getWorldMatrix());
  15070. }
  15071. this._draw(subMesh, fillMode);
  15072. }
  15073. if (batch.visibleInstances[subMesh._id]) {
  15074. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15075. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15076. // World
  15077. var world = instance.getWorldMatrix();
  15078. if (onBeforeDraw) {
  15079. onBeforeDraw(true, world);
  15080. }
  15081. // Draw
  15082. this._draw(subMesh, fillMode);
  15083. }
  15084. }
  15085. }
  15086. };
  15087. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15088. var scene = this.getScene();
  15089. // Managing instances
  15090. var batch = this._getInstancesRenderList(subMesh._id);
  15091. if (batch.mustReturn) {
  15092. return;
  15093. }
  15094. // Checking geometry state
  15095. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15096. return;
  15097. }
  15098. var callbackIndex;
  15099. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15100. this._onBeforeRenderCallbacks[callbackIndex](this);
  15101. }
  15102. var engine = scene.getEngine();
  15103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15104. // Material
  15105. var effectiveMaterial = subMesh.getMaterial();
  15106. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15107. return;
  15108. }
  15109. // Outline - step 1
  15110. var savedDepthWrite = engine.getDepthWrite();
  15111. if (this.renderOutline) {
  15112. engine.setDepthWrite(false);
  15113. scene.getOutlineRenderer().render(subMesh, batch);
  15114. engine.setDepthWrite(savedDepthWrite);
  15115. }
  15116. effectiveMaterial._preBind();
  15117. var effect = effectiveMaterial.getEffect();
  15118. // Bind
  15119. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15120. this._bind(subMesh, effect, fillMode);
  15121. var world = this.getWorldMatrix();
  15122. effectiveMaterial.bind(world, this);
  15123. // Alpha mode
  15124. if (enableAlphaMode) {
  15125. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15126. }
  15127. // Draw
  15128. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15129. if (isInstance) {
  15130. effectiveMaterial.bindOnlyWorldMatrix(world);
  15131. }
  15132. });
  15133. // Unbind
  15134. effectiveMaterial.unbind();
  15135. // Outline - step 2
  15136. if (this.renderOutline && savedDepthWrite) {
  15137. engine.setDepthWrite(true);
  15138. engine.setColorWrite(false);
  15139. scene.getOutlineRenderer().render(subMesh, batch);
  15140. engine.setColorWrite(true);
  15141. }
  15142. // Overlay
  15143. if (this.renderOverlay) {
  15144. var currentMode = engine.getAlphaMode();
  15145. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15146. scene.getOutlineRenderer().render(subMesh, batch, true);
  15147. engine.setAlphaMode(currentMode);
  15148. }
  15149. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15150. this._onAfterRenderCallbacks[callbackIndex](this);
  15151. }
  15152. };
  15153. Mesh.prototype.getEmittedParticleSystems = function () {
  15154. var results = new Array();
  15155. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15156. var particleSystem = this.getScene().particleSystems[index];
  15157. if (particleSystem.emitter === this) {
  15158. results.push(particleSystem);
  15159. }
  15160. }
  15161. return results;
  15162. };
  15163. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15164. var results = new Array();
  15165. var descendants = this.getDescendants();
  15166. descendants.push(this);
  15167. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15168. var particleSystem = this.getScene().particleSystems[index];
  15169. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15170. results.push(particleSystem);
  15171. }
  15172. }
  15173. return results;
  15174. };
  15175. Mesh.prototype.getChildren = function () {
  15176. var results = [];
  15177. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15178. var mesh = this.getScene().meshes[index];
  15179. if (mesh.parent === this) {
  15180. results.push(mesh);
  15181. }
  15182. }
  15183. return results;
  15184. };
  15185. Mesh.prototype._checkDelayState = function () {
  15186. var _this = this;
  15187. var that = this;
  15188. var scene = this.getScene();
  15189. if (this._geometry) {
  15190. this._geometry.load(scene);
  15191. }
  15192. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15193. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15194. scene._addPendingData(that);
  15195. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15196. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15197. if (data instanceof ArrayBuffer) {
  15198. _this._delayLoadingFunction(data, _this);
  15199. }
  15200. else {
  15201. _this._delayLoadingFunction(JSON.parse(data), _this);
  15202. }
  15203. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15204. scene._removePendingData(_this);
  15205. }, function () { }, scene.database, getBinaryData);
  15206. }
  15207. };
  15208. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15209. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15210. return false;
  15211. }
  15212. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15213. return false;
  15214. }
  15215. this._checkDelayState();
  15216. return true;
  15217. };
  15218. Mesh.prototype.setMaterialByID = function (id) {
  15219. var materials = this.getScene().materials;
  15220. var index;
  15221. for (index = 0; index < materials.length; index++) {
  15222. if (materials[index].id === id) {
  15223. this.material = materials[index];
  15224. return;
  15225. }
  15226. }
  15227. // Multi
  15228. var multiMaterials = this.getScene().multiMaterials;
  15229. for (index = 0; index < multiMaterials.length; index++) {
  15230. if (multiMaterials[index].id === id) {
  15231. this.material = multiMaterials[index];
  15232. return;
  15233. }
  15234. }
  15235. };
  15236. Mesh.prototype.getAnimatables = function () {
  15237. var results = [];
  15238. if (this.material) {
  15239. results.push(this.material);
  15240. }
  15241. if (this.skeleton) {
  15242. results.push(this.skeleton);
  15243. }
  15244. return results;
  15245. };
  15246. // Geometry
  15247. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15248. // Position
  15249. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15250. return;
  15251. }
  15252. this._resetPointsArrayCache();
  15253. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15254. var temp = [];
  15255. var index;
  15256. for (index = 0; index < data.length; index += 3) {
  15257. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15258. }
  15259. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15260. // Normals
  15261. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15262. return;
  15263. }
  15264. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15265. temp = [];
  15266. for (index = 0; index < data.length; index += 3) {
  15267. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15268. }
  15269. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15270. // flip faces?
  15271. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15272. this.flipFaces();
  15273. }
  15274. };
  15275. // Will apply current transform to mesh and reset world matrix
  15276. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15277. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15278. this.scaling.copyFromFloats(1, 1, 1);
  15279. this.position.copyFromFloats(0, 0, 0);
  15280. this.rotation.copyFromFloats(0, 0, 0);
  15281. //only if quaternion is already set
  15282. if (this.rotationQuaternion) {
  15283. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15284. }
  15285. this._worldMatrix = BABYLON.Matrix.Identity();
  15286. };
  15287. // Cache
  15288. Mesh.prototype._resetPointsArrayCache = function () {
  15289. this._positions = null;
  15290. };
  15291. Mesh.prototype._generatePointsArray = function () {
  15292. if (this._positions)
  15293. return true;
  15294. this._positions = [];
  15295. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15296. if (!data) {
  15297. return false;
  15298. }
  15299. for (var index = 0; index < data.length; index += 3) {
  15300. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15301. }
  15302. return true;
  15303. };
  15304. // Clone
  15305. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15306. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15307. };
  15308. // Dispose
  15309. Mesh.prototype.dispose = function (doNotRecurse) {
  15310. if (this._geometry) {
  15311. this._geometry.releaseForMesh(this, true);
  15312. }
  15313. // Instances
  15314. if (this._worldMatricesInstancesBuffer) {
  15315. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15316. this._worldMatricesInstancesBuffer = null;
  15317. }
  15318. while (this.instances.length) {
  15319. this.instances[0].dispose();
  15320. }
  15321. _super.prototype.dispose.call(this, doNotRecurse);
  15322. };
  15323. // Geometric tools
  15324. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15325. var _this = this;
  15326. var scene = this.getScene();
  15327. var onload = function (img) {
  15328. // Getting height map data
  15329. var canvas = document.createElement("canvas");
  15330. var context = canvas.getContext("2d");
  15331. var heightMapWidth = img.width;
  15332. var heightMapHeight = img.height;
  15333. canvas.width = heightMapWidth;
  15334. canvas.height = heightMapHeight;
  15335. context.drawImage(img, 0, 0);
  15336. // Create VertexData from map data
  15337. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15338. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15339. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15340. //execute success callback, if set
  15341. if (onSuccess) {
  15342. onSuccess(_this);
  15343. }
  15344. };
  15345. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15346. };
  15347. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15348. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15349. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15350. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15351. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15352. return;
  15353. }
  15354. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15355. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15356. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15357. var position = BABYLON.Vector3.Zero();
  15358. var normal = BABYLON.Vector3.Zero();
  15359. var uv = BABYLON.Vector2.Zero();
  15360. for (var index = 0; index < positions.length; index += 3) {
  15361. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15362. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15363. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15364. // Compute height
  15365. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15366. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15367. var pos = (u + v * heightMapWidth) * 4;
  15368. var r = buffer[pos] / 255.0;
  15369. var g = buffer[pos + 1] / 255.0;
  15370. var b = buffer[pos + 2] / 255.0;
  15371. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15372. normal.normalize();
  15373. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15374. position = position.add(normal);
  15375. position.toArray(positions, index);
  15376. }
  15377. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15378. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15379. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15380. };
  15381. Mesh.prototype.convertToFlatShadedMesh = function () {
  15382. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15383. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15384. var kinds = this.getVerticesDataKinds();
  15385. var vbs = [];
  15386. var data = [];
  15387. var newdata = [];
  15388. var updatableNormals = false;
  15389. var kindIndex;
  15390. var kind;
  15391. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15392. kind = kinds[kindIndex];
  15393. var vertexBuffer = this.getVertexBuffer(kind);
  15394. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15395. updatableNormals = vertexBuffer.isUpdatable();
  15396. kinds.splice(kindIndex, 1);
  15397. kindIndex--;
  15398. continue;
  15399. }
  15400. vbs[kind] = vertexBuffer;
  15401. data[kind] = vbs[kind].getData();
  15402. newdata[kind] = [];
  15403. }
  15404. // Save previous submeshes
  15405. var previousSubmeshes = this.subMeshes.slice(0);
  15406. var indices = this.getIndices();
  15407. var totalIndices = this.getTotalIndices();
  15408. // Generating unique vertices per face
  15409. var index;
  15410. for (index = 0; index < totalIndices; index++) {
  15411. var vertexIndex = indices[index];
  15412. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15413. kind = kinds[kindIndex];
  15414. var stride = vbs[kind].getStrideSize();
  15415. for (var offset = 0; offset < stride; offset++) {
  15416. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15417. }
  15418. }
  15419. }
  15420. // Updating faces & normal
  15421. var normals = [];
  15422. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15423. for (index = 0; index < totalIndices; index += 3) {
  15424. indices[index] = index;
  15425. indices[index + 1] = index + 1;
  15426. indices[index + 2] = index + 2;
  15427. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15428. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15429. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15430. var p1p2 = p1.subtract(p2);
  15431. var p3p2 = p3.subtract(p2);
  15432. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15433. // Store same normals for every vertex
  15434. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15435. normals.push(normal.x);
  15436. normals.push(normal.y);
  15437. normals.push(normal.z);
  15438. }
  15439. }
  15440. this.setIndices(indices);
  15441. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15442. // Updating vertex buffers
  15443. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15444. kind = kinds[kindIndex];
  15445. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15446. }
  15447. // Updating submeshes
  15448. this.releaseSubMeshes();
  15449. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15450. var previousOne = previousSubmeshes[submeshIndex];
  15451. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15452. }
  15453. this.synchronizeInstances();
  15454. };
  15455. // will inverse faces orientations, and invert normals too if specified
  15456. Mesh.prototype.flipFaces = function (flipNormals) {
  15457. if (flipNormals === void 0) { flipNormals = false; }
  15458. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15459. var i;
  15460. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15461. for (i = 0; i < vertex_data.normals.length; i++) {
  15462. vertex_data.normals[i] *= -1;
  15463. }
  15464. }
  15465. var temp;
  15466. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15467. // reassign indices
  15468. temp = vertex_data.indices[i + 1];
  15469. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15470. vertex_data.indices[i + 2] = temp;
  15471. }
  15472. vertex_data.applyToMesh(this);
  15473. };
  15474. // Instances
  15475. Mesh.prototype.createInstance = function (name) {
  15476. return new BABYLON.InstancedMesh(name, this);
  15477. };
  15478. Mesh.prototype.synchronizeInstances = function () {
  15479. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15480. var instance = this.instances[instanceIndex];
  15481. instance._syncSubMeshes();
  15482. }
  15483. };
  15484. /**
  15485. * Simplify the mesh according to the given array of settings.
  15486. * Function will return immediately and will simplify async.
  15487. * @param settings a collection of simplification settings.
  15488. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15489. * @param type the type of simplification to run.
  15490. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15491. */
  15492. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15493. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15494. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15495. this.getScene().simplificationQueue.addTask({
  15496. settings: settings,
  15497. parallelProcessing: parallelProcessing,
  15498. mesh: this,
  15499. simplificationType: simplificationType,
  15500. successCallback: successCallback
  15501. });
  15502. };
  15503. /**
  15504. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15505. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15506. * This should be used together with the simplification to avoid disappearing triangles.
  15507. * @param successCallback an optional success callback to be called after the optimization finished.
  15508. */
  15509. Mesh.prototype.optimizeIndices = function (successCallback) {
  15510. var _this = this;
  15511. var indices = this.getIndices();
  15512. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15513. var vectorPositions = [];
  15514. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15515. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15516. }
  15517. var dupes = [];
  15518. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15519. var realPos = vectorPositions.length - 1 - iteration;
  15520. var testedPosition = vectorPositions[realPos];
  15521. for (var j = 0; j < realPos; ++j) {
  15522. var againstPosition = vectorPositions[j];
  15523. if (testedPosition.equals(againstPosition)) {
  15524. dupes[realPos] = j;
  15525. break;
  15526. }
  15527. }
  15528. }, function () {
  15529. for (var i = 0; i < indices.length; ++i) {
  15530. indices[i] = dupes[indices[i]] || indices[i];
  15531. }
  15532. //indices are now reordered
  15533. var originalSubMeshes = _this.subMeshes.slice(0);
  15534. _this.setIndices(indices);
  15535. _this.subMeshes = originalSubMeshes;
  15536. if (successCallback) {
  15537. successCallback(_this);
  15538. }
  15539. });
  15540. };
  15541. Mesh.CreateRibbon = function (name, options, closeArrayOrScene, closePath, offset, scene, updatable, sideOrientation, instance) {
  15542. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15543. if (instance === void 0) { instance = null; }
  15544. var pathArray;
  15545. if (closeArrayOrScene instanceof BABYLON.Scene) {
  15546. scene = closeArrayOrScene;
  15547. updatable = options.updatable;
  15548. if (options.instance) {
  15549. pathArray = options.pathArray;
  15550. instance = options.instance;
  15551. closePath = options.closePath;
  15552. var closeArray = options.closeArray;
  15553. }
  15554. }
  15555. else {
  15556. pathArray = options;
  15557. options = {
  15558. pathArray: pathArray,
  15559. closeArray: closeArrayOrScene,
  15560. closePath: closePath,
  15561. offset: offset,
  15562. sideOrientation: sideOrientation,
  15563. };
  15564. }
  15565. if (instance) {
  15566. // positionFunction : ribbon case
  15567. // only pathArray and sideOrientation parameters are taken into account for positions update
  15568. var positionFunction = function (positions) {
  15569. var minlg = pathArray[0].length;
  15570. var i = 0;
  15571. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15572. for (var si = 1; si <= ns; si++) {
  15573. for (var p = 0; p < pathArray.length; p++) {
  15574. var path = pathArray[p];
  15575. var l = path.length;
  15576. minlg = (minlg < l) ? minlg : l;
  15577. var j = 0;
  15578. while (j < minlg) {
  15579. positions[i] = path[j].x;
  15580. positions[i + 1] = path[j].y;
  15581. positions[i + 2] = path[j].z;
  15582. j++;
  15583. i += 3;
  15584. }
  15585. if (instance._closePath) {
  15586. positions[i] = path[0].x;
  15587. positions[i + 1] = path[0].y;
  15588. positions[i + 2] = path[0].z;
  15589. i += 3;
  15590. }
  15591. }
  15592. }
  15593. };
  15594. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15595. positionFunction(positions);
  15596. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15597. if (!(instance.areNormalsFrozen)) {
  15598. var indices = instance.getIndices();
  15599. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15600. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15601. if (instance._closePath) {
  15602. var indexFirst = 0;
  15603. var indexLast = 0;
  15604. for (var p = 0; p < pathArray.length; p++) {
  15605. indexFirst = instance._idx[p] * 3;
  15606. if (p + 1 < pathArray.length) {
  15607. indexLast = (instance._idx[p + 1] - 1) * 3;
  15608. }
  15609. else {
  15610. indexLast = normals.length - 3;
  15611. }
  15612. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15613. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15614. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15615. normals[indexLast] = normals[indexFirst];
  15616. normals[indexLast + 1] = normals[indexFirst + 1];
  15617. normals[indexLast + 2] = normals[indexFirst + 2];
  15618. }
  15619. }
  15620. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15621. }
  15622. return instance;
  15623. }
  15624. else {
  15625. var ribbon = new Mesh(name, scene);
  15626. ribbon.sideOrientation = sideOrientation;
  15627. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15628. if (closePath) {
  15629. ribbon._idx = vertexData._idx;
  15630. }
  15631. ribbon._closePath = closePath;
  15632. vertexData.applyToMesh(ribbon, updatable);
  15633. return ribbon;
  15634. }
  15635. };
  15636. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15637. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15638. var disc = new Mesh(name, scene);
  15639. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15640. vertexData.applyToMesh(disc, updatable);
  15641. return disc;
  15642. };
  15643. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15644. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15645. // Check parameters
  15646. updatable = updatable || options.updatable;
  15647. var box = new Mesh(name, scene);
  15648. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15649. vertexData.applyToMesh(box, updatable);
  15650. return box;
  15651. };
  15652. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15653. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15654. if (diameterOrScene instanceof BABYLON.Scene) {
  15655. scene = diameterOrScene;
  15656. updatable = options.updatable;
  15657. }
  15658. else {
  15659. var segments = options;
  15660. options = {
  15661. segments: segments,
  15662. diameterX: diameterOrScene,
  15663. diameterY: diameterOrScene,
  15664. diameterZ: diameterOrScene,
  15665. sideOrientation: sideOrientation
  15666. };
  15667. }
  15668. var sphere = new Mesh(name, scene);
  15669. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15670. vertexData.applyToMesh(sphere, updatable);
  15671. return sphere;
  15672. };
  15673. Mesh.CreateCylinder = function (name, options, diameterTopOrScene, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15674. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15675. if (diameterTopOrScene instanceof BABYLON.Scene) {
  15676. scene = diameterTopOrScene;
  15677. updatable = options.updatable;
  15678. }
  15679. else {
  15680. var height = options;
  15681. options = {
  15682. height: height,
  15683. diameterTop: diameterTopOrScene,
  15684. diameterBottom: diameterBottom,
  15685. tessellation: tessellation,
  15686. subdivisions: subdivisions,
  15687. sideOrientation: sideOrientation
  15688. };
  15689. }
  15690. var cylinder = new Mesh(name, scene);
  15691. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15692. vertexData.applyToMesh(cylinder, updatable);
  15693. return cylinder;
  15694. };
  15695. // Torus (Code from SharpDX.org)
  15696. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15697. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15698. var torus = new Mesh(name, scene);
  15699. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15700. vertexData.applyToMesh(torus, updatable);
  15701. return torus;
  15702. };
  15703. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15704. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15705. var torusKnot = new Mesh(name, scene);
  15706. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15707. vertexData.applyToMesh(torusKnot, updatable);
  15708. return torusKnot;
  15709. };
  15710. // Lines
  15711. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15712. if (linesInstance === void 0) { linesInstance = null; }
  15713. if (linesInstance) {
  15714. var positionFunction = function (positions) {
  15715. var i = 0;
  15716. for (var p = 0; p < points.length; p++) {
  15717. positions[i] = points[p].x;
  15718. positions[i + 1] = points[p].y;
  15719. positions[i + 2] = points[p].z;
  15720. i += 3;
  15721. }
  15722. };
  15723. linesInstance.updateMeshPositions(positionFunction, false);
  15724. return linesInstance;
  15725. }
  15726. // lines creation
  15727. var lines = new BABYLON.LinesMesh(name, scene);
  15728. var vertexData = BABYLON.VertexData.CreateLines(points);
  15729. vertexData.applyToMesh(lines, updatable);
  15730. return lines;
  15731. };
  15732. // Dashed Lines
  15733. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15734. if (linesInstance === void 0) { linesInstance = null; }
  15735. if (linesInstance) {
  15736. var positionFunction = function (positions) {
  15737. var curvect = BABYLON.Vector3.Zero();
  15738. var nbSeg = positions.length / 6;
  15739. var lg = 0;
  15740. var nb = 0;
  15741. var shft = 0;
  15742. var dashshft = 0;
  15743. var curshft = 0;
  15744. var p = 0;
  15745. var i = 0;
  15746. var j = 0;
  15747. for (i = 0; i < points.length - 1; i++) {
  15748. points[i + 1].subtractToRef(points[i], curvect);
  15749. lg += curvect.length();
  15750. }
  15751. shft = lg / nbSeg;
  15752. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15753. for (i = 0; i < points.length - 1; i++) {
  15754. points[i + 1].subtractToRef(points[i], curvect);
  15755. nb = Math.floor(curvect.length() / shft);
  15756. curvect.normalize();
  15757. j = 0;
  15758. while (j < nb && p < positions.length) {
  15759. curshft = shft * j;
  15760. positions[p] = points[i].x + curshft * curvect.x;
  15761. positions[p + 1] = points[i].y + curshft * curvect.y;
  15762. positions[p + 2] = points[i].z + curshft * curvect.z;
  15763. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15764. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15765. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15766. p += 6;
  15767. j++;
  15768. }
  15769. }
  15770. while (p < positions.length) {
  15771. positions[p] = points[i].x;
  15772. positions[p + 1] = points[i].y;
  15773. positions[p + 2] = points[i].z;
  15774. p += 3;
  15775. }
  15776. };
  15777. linesInstance.updateMeshPositions(positionFunction, false);
  15778. return linesInstance;
  15779. }
  15780. // dashed lines creation
  15781. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15782. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15783. vertexData.applyToMesh(dashedLines, updatable);
  15784. dashedLines.dashSize = dashSize;
  15785. dashedLines.gapSize = gapSize;
  15786. return dashedLines;
  15787. };
  15788. // Extrusion
  15789. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15790. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15791. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15792. scale = scale || 1;
  15793. rotation = rotation || 0;
  15794. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15795. return extruded;
  15796. };
  15797. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15798. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15799. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15800. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15801. return extrudedCustom;
  15802. };
  15803. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15804. // extrusion geometry
  15805. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15806. var tangents = path3D.getTangents();
  15807. var normals = path3D.getNormals();
  15808. var binormals = path3D.getBinormals();
  15809. var distances = path3D.getDistances();
  15810. var angle = 0;
  15811. var returnScale = function (i, distance) { return scale; };
  15812. var returnRotation = function (i, distance) { return rotation; };
  15813. var rotate = custom ? rotateFunction : returnRotation;
  15814. var scl = custom ? scaleFunction : returnScale;
  15815. var index = 0;
  15816. for (var i = 0; i < curve.length; i++) {
  15817. var shapePath = new Array();
  15818. var angleStep = rotate(i, distances[i]);
  15819. var scaleRatio = scl(i, distances[i]);
  15820. for (var p = 0; p < shape.length; p++) {
  15821. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15822. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15823. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15824. shapePath.push(rotated);
  15825. }
  15826. shapePaths[index] = shapePath;
  15827. angle += angleStep;
  15828. index++;
  15829. }
  15830. // cap
  15831. var capPath = function (shapePath) {
  15832. var pointCap = Array();
  15833. var barycenter = BABYLON.Vector3.Zero();
  15834. var i;
  15835. for (i = 0; i < shapePath.length; i++) {
  15836. barycenter.addInPlace(shapePath[i]);
  15837. }
  15838. barycenter.scaleInPlace(1 / shapePath.length);
  15839. for (i = 0; i < shapePath.length; i++) {
  15840. pointCap.push(barycenter);
  15841. }
  15842. return pointCap;
  15843. };
  15844. switch (cap) {
  15845. case Mesh.NO_CAP:
  15846. break;
  15847. case Mesh.CAP_START:
  15848. shapePaths.unshift(capPath(shapePaths[0]));
  15849. break;
  15850. case Mesh.CAP_END:
  15851. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15852. break;
  15853. case Mesh.CAP_ALL:
  15854. shapePaths.unshift(capPath(shapePaths[0]));
  15855. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15856. break;
  15857. default:
  15858. break;
  15859. }
  15860. return shapePaths;
  15861. };
  15862. var path3D;
  15863. var pathArray;
  15864. if (instance) {
  15865. path3D = (instance.path3D).update(curve);
  15866. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15867. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15868. return instance;
  15869. }
  15870. // extruded shape creation
  15871. path3D = new BABYLON.Path3D(curve);
  15872. var newShapePaths = new Array();
  15873. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15874. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15875. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15876. extrudedGeneric.pathArray = pathArray;
  15877. extrudedGeneric.path3D = path3D;
  15878. extrudedGeneric.cap = cap;
  15879. return extrudedGeneric;
  15880. };
  15881. // Lathe
  15882. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15883. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15884. radius = radius || 1;
  15885. tessellation = tessellation || radius * 60;
  15886. var pi2 = Math.PI * 2;
  15887. var shapeLathe = new Array();
  15888. // first rotatable point
  15889. var i = 0;
  15890. while (shape[i].x === 0) {
  15891. i++;
  15892. }
  15893. var pt = shape[i];
  15894. for (i = 0; i < shape.length; i++) {
  15895. shapeLathe.push(shape[i].subtract(pt));
  15896. }
  15897. // circle path
  15898. var step = pi2 / tessellation;
  15899. var rotated;
  15900. var path = new Array();
  15901. ;
  15902. for (i = 0; i < tessellation; i++) {
  15903. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15904. path.push(rotated);
  15905. }
  15906. path.push(path[0]);
  15907. // extrusion
  15908. var scaleFunction = function () { return 1; };
  15909. var rotateFunction = function () { return 0; };
  15910. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15911. return lathe;
  15912. };
  15913. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  15914. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15915. var plane = new Mesh(name, scene);
  15916. var vertexData = BABYLON.VertexData.CreatePlane(options, sideOrientation);
  15917. vertexData.applyToMesh(plane, updatable || options.updatable);
  15918. return plane;
  15919. };
  15920. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  15921. if (heightOrScene instanceof BABYLON.Scene) {
  15922. scene = heightOrScene;
  15923. updatable = options.updatable;
  15924. }
  15925. else {
  15926. var width = options;
  15927. options = {
  15928. width: width,
  15929. height: heightOrScene,
  15930. subdivisions: subdivisions
  15931. };
  15932. }
  15933. var ground = new BABYLON.GroundMesh(name, scene);
  15934. ground._setReady(false);
  15935. ground._subdivisions = options.subdivisions || 1;
  15936. var vertexData = BABYLON.VertexData.CreateGround(options);
  15937. vertexData.applyToMesh(ground, updatable || options.updatable);
  15938. ground._setReady(true);
  15939. return ground;
  15940. };
  15941. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15942. var tiledGround = new Mesh(name, scene);
  15943. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15944. vertexData.applyToMesh(tiledGround, updatable);
  15945. return tiledGround;
  15946. };
  15947. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15948. var ground = new BABYLON.GroundMesh(name, scene);
  15949. ground._subdivisions = subdivisions;
  15950. ground._setReady(false);
  15951. var onload = function (img) {
  15952. // Getting height map data
  15953. var canvas = document.createElement("canvas");
  15954. var context = canvas.getContext("2d");
  15955. var heightMapWidth = img.width;
  15956. var heightMapHeight = img.height;
  15957. canvas.width = heightMapWidth;
  15958. canvas.height = heightMapHeight;
  15959. context.drawImage(img, 0, 0);
  15960. // Create VertexData from map data
  15961. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15962. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15963. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15964. vertexData.applyToMesh(ground, updatable);
  15965. ground._setReady(true);
  15966. //execute ready callback, if set
  15967. if (onReady) {
  15968. onReady(ground);
  15969. }
  15970. };
  15971. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15972. return ground;
  15973. };
  15974. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15975. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15976. if (tubeInstance === void 0) { tubeInstance = null; }
  15977. // tube geometry
  15978. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15979. var tangents = path3D.getTangents();
  15980. var normals = path3D.getNormals();
  15981. var distances = path3D.getDistances();
  15982. var pi2 = Math.PI * 2;
  15983. var step = pi2 / tessellation;
  15984. var returnRadius = function (i, distance) { return radius; };
  15985. var radiusFunctionFinal = radiusFunction || returnRadius;
  15986. var circlePath;
  15987. var rad;
  15988. var normal;
  15989. var rotated;
  15990. var rotationMatrix;
  15991. var index = 0;
  15992. for (var i = 0; i < path.length; i++) {
  15993. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15994. circlePath = Array(); // current circle array
  15995. normal = normals[i]; // current normal
  15996. for (var t = 0; t < tessellation; t++) {
  15997. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15998. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15999. circlePath.push(rotated);
  16000. }
  16001. circlePaths[index] = circlePath;
  16002. index++;
  16003. }
  16004. // cap
  16005. var capPath = function (nbPoints, pathIndex) {
  16006. var pointCap = Array();
  16007. for (var i = 0; i < nbPoints; i++) {
  16008. pointCap.push(path[pathIndex]);
  16009. }
  16010. return pointCap;
  16011. };
  16012. switch (cap) {
  16013. case Mesh.NO_CAP:
  16014. break;
  16015. case Mesh.CAP_START:
  16016. circlePaths.unshift(capPath(tessellation + 1, 0));
  16017. break;
  16018. case Mesh.CAP_END:
  16019. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16020. break;
  16021. case Mesh.CAP_ALL:
  16022. circlePaths.unshift(capPath(tessellation + 1, 0));
  16023. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16024. break;
  16025. default:
  16026. break;
  16027. }
  16028. return circlePaths;
  16029. };
  16030. var path3D;
  16031. var pathArray;
  16032. if (tubeInstance) {
  16033. path3D = (tubeInstance.path3D).update(path);
  16034. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  16035. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  16036. return tubeInstance;
  16037. }
  16038. // tube creation
  16039. path3D = new BABYLON.Path3D(path);
  16040. var newPathArray = new Array();
  16041. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16042. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16043. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16044. tube.pathArray = pathArray;
  16045. tube.path3D = path3D;
  16046. tube.tessellation = tessellation;
  16047. tube.cap = cap;
  16048. return tube;
  16049. };
  16050. // Decals
  16051. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16052. if (angle === void 0) { angle = 0; }
  16053. var indices = sourceMesh.getIndices();
  16054. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16055. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16056. // Getting correct rotation
  16057. if (!normal) {
  16058. var target = new BABYLON.Vector3(0, 0, 1);
  16059. var camera = sourceMesh.getScene().activeCamera;
  16060. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16061. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16062. }
  16063. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16064. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16065. var pitch = Math.atan2(normal.y, len);
  16066. // Matrix
  16067. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16068. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16069. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16070. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16071. var vertexData = new BABYLON.VertexData();
  16072. vertexData.indices = [];
  16073. vertexData.positions = [];
  16074. vertexData.normals = [];
  16075. vertexData.uvs = [];
  16076. var currentVertexDataIndex = 0;
  16077. var extractDecalVector3 = function (indexId) {
  16078. var vertexId = indices[indexId];
  16079. var result = new BABYLON.PositionNormalVertex();
  16080. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16081. // Send vector to decal local world
  16082. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16083. // Get normal
  16084. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16085. return result;
  16086. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16087. var clip = function (vertices, axis) {
  16088. if (vertices.length === 0) {
  16089. return vertices;
  16090. }
  16091. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16092. var clipVertices = function (v0, v1) {
  16093. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16094. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16095. };
  16096. var result = new Array();
  16097. for (var index = 0; index < vertices.length; index += 3) {
  16098. var v1Out;
  16099. var v2Out;
  16100. var v3Out;
  16101. var total = 0;
  16102. var nV1, nV2, nV3, nV4;
  16103. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16104. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16105. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16106. v1Out = d1 > 0;
  16107. v2Out = d2 > 0;
  16108. v3Out = d3 > 0;
  16109. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16110. switch (total) {
  16111. case 0:
  16112. result.push(vertices[index]);
  16113. result.push(vertices[index + 1]);
  16114. result.push(vertices[index + 2]);
  16115. break;
  16116. case 1:
  16117. if (v1Out) {
  16118. nV1 = vertices[index + 1];
  16119. nV2 = vertices[index + 2];
  16120. nV3 = clipVertices(vertices[index], nV1);
  16121. nV4 = clipVertices(vertices[index], nV2);
  16122. }
  16123. if (v2Out) {
  16124. nV1 = vertices[index];
  16125. nV2 = vertices[index + 2];
  16126. nV3 = clipVertices(vertices[index + 1], nV1);
  16127. nV4 = clipVertices(vertices[index + 1], nV2);
  16128. result.push(nV3);
  16129. result.push(nV2.clone());
  16130. result.push(nV1.clone());
  16131. result.push(nV2.clone());
  16132. result.push(nV3.clone());
  16133. result.push(nV4);
  16134. break;
  16135. }
  16136. if (v3Out) {
  16137. nV1 = vertices[index];
  16138. nV2 = vertices[index + 1];
  16139. nV3 = clipVertices(vertices[index + 2], nV1);
  16140. nV4 = clipVertices(vertices[index + 2], nV2);
  16141. }
  16142. result.push(nV1.clone());
  16143. result.push(nV2.clone());
  16144. result.push(nV3);
  16145. result.push(nV4);
  16146. result.push(nV3.clone());
  16147. result.push(nV2.clone());
  16148. break;
  16149. case 2:
  16150. if (!v1Out) {
  16151. nV1 = vertices[index].clone();
  16152. nV2 = clipVertices(nV1, vertices[index + 1]);
  16153. nV3 = clipVertices(nV1, vertices[index + 2]);
  16154. result.push(nV1);
  16155. result.push(nV2);
  16156. result.push(nV3);
  16157. }
  16158. if (!v2Out) {
  16159. nV1 = vertices[index + 1].clone();
  16160. nV2 = clipVertices(nV1, vertices[index + 2]);
  16161. nV3 = clipVertices(nV1, vertices[index]);
  16162. result.push(nV1);
  16163. result.push(nV2);
  16164. result.push(nV3);
  16165. }
  16166. if (!v3Out) {
  16167. nV1 = vertices[index + 2].clone();
  16168. nV2 = clipVertices(nV1, vertices[index]);
  16169. nV3 = clipVertices(nV1, vertices[index + 1]);
  16170. result.push(nV1);
  16171. result.push(nV2);
  16172. result.push(nV3);
  16173. }
  16174. break;
  16175. case 3:
  16176. break;
  16177. }
  16178. }
  16179. return result;
  16180. };
  16181. for (var index = 0; index < indices.length; index += 3) {
  16182. var faceVertices = new Array();
  16183. faceVertices.push(extractDecalVector3(index));
  16184. faceVertices.push(extractDecalVector3(index + 1));
  16185. faceVertices.push(extractDecalVector3(index + 2));
  16186. // Clip
  16187. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16188. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16189. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16190. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16191. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16192. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16193. if (faceVertices.length === 0) {
  16194. continue;
  16195. }
  16196. // Add UVs and get back to world
  16197. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16198. var vertex = faceVertices[vIndex];
  16199. vertexData.indices.push(currentVertexDataIndex);
  16200. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16201. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16202. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16203. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16204. currentVertexDataIndex++;
  16205. }
  16206. }
  16207. // Return mesh
  16208. var decal = new Mesh(name, sourceMesh.getScene());
  16209. vertexData.applyToMesh(decal);
  16210. decal.position = position.clone();
  16211. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16212. return decal;
  16213. };
  16214. // Skeletons
  16215. /**
  16216. * Update the vertex buffers by applying transformation from the bones
  16217. * @param {skeleton} skeleton to apply
  16218. */
  16219. Mesh.prototype.applySkeleton = function (skeleton) {
  16220. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16221. return this;
  16222. }
  16223. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16224. return this;
  16225. }
  16226. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16227. return this;
  16228. }
  16229. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16230. return this;
  16231. }
  16232. var source;
  16233. if (!this._sourcePositions) {
  16234. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16235. this._sourcePositions = new Float32Array(source);
  16236. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16237. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16238. }
  16239. }
  16240. if (!this._sourceNormals) {
  16241. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16242. this._sourceNormals = new Float32Array(source);
  16243. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16244. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16245. }
  16246. }
  16247. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16248. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16249. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16250. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16251. var skeletonMatrices = skeleton.getTransformMatrices();
  16252. var tempVector3 = BABYLON.Vector3.Zero();
  16253. var finalMatrix = new BABYLON.Matrix();
  16254. var tempMatrix = new BABYLON.Matrix();
  16255. for (var index = 0; index < positionsData.length; index += 3) {
  16256. var index4 = (index / 3) * 4;
  16257. var matricesWeight0 = matricesWeightsData[index4];
  16258. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16259. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16260. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16261. if (matricesWeight0 > 0) {
  16262. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16263. finalMatrix.addToSelf(tempMatrix);
  16264. }
  16265. if (matricesWeight1 > 0) {
  16266. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16267. finalMatrix.addToSelf(tempMatrix);
  16268. }
  16269. if (matricesWeight2 > 0) {
  16270. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16271. finalMatrix.addToSelf(tempMatrix);
  16272. }
  16273. if (matricesWeight3 > 0) {
  16274. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16275. finalMatrix.addToSelf(tempMatrix);
  16276. }
  16277. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16278. tempVector3.toArray(positionsData, index);
  16279. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16280. tempVector3.toArray(normalsData, index);
  16281. finalMatrix.reset();
  16282. }
  16283. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16284. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16285. return this;
  16286. };
  16287. // Tools
  16288. Mesh.MinMax = function (meshes) {
  16289. var minVector = null;
  16290. var maxVector = null;
  16291. for (var i in meshes) {
  16292. var mesh = meshes[i];
  16293. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16294. if (!minVector) {
  16295. minVector = boundingBox.minimumWorld;
  16296. maxVector = boundingBox.maximumWorld;
  16297. continue;
  16298. }
  16299. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16300. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16301. }
  16302. return {
  16303. min: minVector,
  16304. max: maxVector
  16305. };
  16306. };
  16307. Mesh.Center = function (meshesOrMinMaxVector) {
  16308. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16309. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16310. };
  16311. /**
  16312. * Merge the array of meshes into a single mesh for performance reasons.
  16313. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16314. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16315. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16316. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16317. */
  16318. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16319. if (disposeSource === void 0) { disposeSource = true; }
  16320. var index;
  16321. if (!allow32BitsIndices) {
  16322. var totalVertices = 0;
  16323. // Counting vertices
  16324. for (index = 0; index < meshes.length; index++) {
  16325. if (meshes[index]) {
  16326. totalVertices += meshes[index].getTotalVertices();
  16327. if (totalVertices > 65536) {
  16328. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16329. return null;
  16330. }
  16331. }
  16332. }
  16333. }
  16334. // Merge
  16335. var vertexData;
  16336. var otherVertexData;
  16337. var source;
  16338. for (index = 0; index < meshes.length; index++) {
  16339. if (meshes[index]) {
  16340. meshes[index].computeWorldMatrix(true);
  16341. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16342. otherVertexData.transform(meshes[index].getWorldMatrix());
  16343. if (vertexData) {
  16344. vertexData.merge(otherVertexData);
  16345. }
  16346. else {
  16347. vertexData = otherVertexData;
  16348. source = meshes[index];
  16349. }
  16350. }
  16351. }
  16352. if (!meshSubclass) {
  16353. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16354. }
  16355. vertexData.applyToMesh(meshSubclass);
  16356. // Setting properties
  16357. meshSubclass.material = source.material;
  16358. meshSubclass.checkCollisions = source.checkCollisions;
  16359. // Cleaning
  16360. if (disposeSource) {
  16361. for (index = 0; index < meshes.length; index++) {
  16362. if (meshes[index]) {
  16363. meshes[index].dispose();
  16364. }
  16365. }
  16366. }
  16367. return meshSubclass;
  16368. };
  16369. // Consts
  16370. Mesh._FRONTSIDE = 0;
  16371. Mesh._BACKSIDE = 1;
  16372. Mesh._DOUBLESIDE = 2;
  16373. Mesh._DEFAULTSIDE = 0;
  16374. Mesh._NO_CAP = 0;
  16375. Mesh._CAP_START = 1;
  16376. Mesh._CAP_END = 2;
  16377. Mesh._CAP_ALL = 3;
  16378. return Mesh;
  16379. })(BABYLON.AbstractMesh);
  16380. BABYLON.Mesh = Mesh;
  16381. })(BABYLON || (BABYLON = {}));
  16382. var BABYLON;
  16383. (function (BABYLON) {
  16384. var SubMesh = (function () {
  16385. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16386. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16387. this.materialIndex = materialIndex;
  16388. this.verticesStart = verticesStart;
  16389. this.verticesCount = verticesCount;
  16390. this.indexStart = indexStart;
  16391. this.indexCount = indexCount;
  16392. this._renderId = 0;
  16393. this._mesh = mesh;
  16394. this._renderingMesh = renderingMesh || mesh;
  16395. mesh.subMeshes.push(this);
  16396. this._trianglePlanes = [];
  16397. this._id = mesh.subMeshes.length - 1;
  16398. if (createBoundingBox) {
  16399. this.refreshBoundingInfo();
  16400. mesh.computeWorldMatrix(true);
  16401. }
  16402. }
  16403. SubMesh.prototype.getBoundingInfo = function () {
  16404. return this._boundingInfo;
  16405. };
  16406. SubMesh.prototype.getMesh = function () {
  16407. return this._mesh;
  16408. };
  16409. SubMesh.prototype.getRenderingMesh = function () {
  16410. return this._renderingMesh;
  16411. };
  16412. SubMesh.prototype.getMaterial = function () {
  16413. var rootMaterial = this._renderingMesh.material;
  16414. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16415. var multiMaterial = rootMaterial;
  16416. return multiMaterial.getSubMaterial(this.materialIndex);
  16417. }
  16418. if (!rootMaterial) {
  16419. return this._mesh.getScene().defaultMaterial;
  16420. }
  16421. return rootMaterial;
  16422. };
  16423. // Methods
  16424. SubMesh.prototype.refreshBoundingInfo = function () {
  16425. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16426. if (!data) {
  16427. this._boundingInfo = this._mesh._boundingInfo;
  16428. return;
  16429. }
  16430. var indices = this._renderingMesh.getIndices();
  16431. var extend;
  16432. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16433. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16434. }
  16435. else {
  16436. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16437. }
  16438. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16439. };
  16440. SubMesh.prototype._checkCollision = function (collider) {
  16441. return this._boundingInfo._checkCollision(collider);
  16442. };
  16443. SubMesh.prototype.updateBoundingInfo = function (world) {
  16444. if (!this._boundingInfo) {
  16445. this.refreshBoundingInfo();
  16446. }
  16447. this._boundingInfo._update(world);
  16448. };
  16449. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16450. return this._boundingInfo.isInFrustum(frustumPlanes);
  16451. };
  16452. SubMesh.prototype.render = function (enableAlphaMode) {
  16453. this._renderingMesh.render(this, enableAlphaMode);
  16454. };
  16455. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16456. if (!this._linesIndexBuffer) {
  16457. var linesIndices = [];
  16458. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16459. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16460. }
  16461. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16462. this.linesIndexCount = linesIndices.length;
  16463. }
  16464. return this._linesIndexBuffer;
  16465. };
  16466. SubMesh.prototype.canIntersects = function (ray) {
  16467. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16468. };
  16469. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16470. var intersectInfo = null;
  16471. // Triangles test
  16472. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16473. var p0 = positions[indices[index]];
  16474. var p1 = positions[indices[index + 1]];
  16475. var p2 = positions[indices[index + 2]];
  16476. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16477. if (currentIntersectInfo) {
  16478. if (currentIntersectInfo.distance < 0) {
  16479. continue;
  16480. }
  16481. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16482. intersectInfo = currentIntersectInfo;
  16483. intersectInfo.faceId = index / 3;
  16484. if (fastCheck) {
  16485. break;
  16486. }
  16487. }
  16488. }
  16489. }
  16490. return intersectInfo;
  16491. };
  16492. // Clone
  16493. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16494. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16495. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16496. return result;
  16497. };
  16498. // Dispose
  16499. SubMesh.prototype.dispose = function () {
  16500. if (this._linesIndexBuffer) {
  16501. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16502. this._linesIndexBuffer = null;
  16503. }
  16504. // Remove from mesh
  16505. var index = this._mesh.subMeshes.indexOf(this);
  16506. this._mesh.subMeshes.splice(index, 1);
  16507. };
  16508. // Statics
  16509. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16510. var minVertexIndex = Number.MAX_VALUE;
  16511. var maxVertexIndex = -Number.MAX_VALUE;
  16512. renderingMesh = renderingMesh || mesh;
  16513. var indices = renderingMesh.getIndices();
  16514. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16515. var vertexIndex = indices[index];
  16516. if (vertexIndex < minVertexIndex)
  16517. minVertexIndex = vertexIndex;
  16518. if (vertexIndex > maxVertexIndex)
  16519. maxVertexIndex = vertexIndex;
  16520. }
  16521. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16522. };
  16523. return SubMesh;
  16524. })();
  16525. BABYLON.SubMesh = SubMesh;
  16526. })(BABYLON || (BABYLON = {}));
  16527. var BABYLON;
  16528. (function (BABYLON) {
  16529. var BaseTexture = (function () {
  16530. function BaseTexture(scene) {
  16531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16532. this.hasAlpha = false;
  16533. this.getAlphaFromRGB = false;
  16534. this.level = 1;
  16535. this.isCube = false;
  16536. this.isRenderTarget = false;
  16537. this.animations = new Array();
  16538. this.coordinatesIndex = 0;
  16539. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16540. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16541. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16542. this.anisotropicFilteringLevel = 4;
  16543. this._scene = scene;
  16544. this._scene.textures.push(this);
  16545. }
  16546. BaseTexture.prototype.getScene = function () {
  16547. return this._scene;
  16548. };
  16549. BaseTexture.prototype.getTextureMatrix = function () {
  16550. return null;
  16551. };
  16552. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16553. return null;
  16554. };
  16555. BaseTexture.prototype.getInternalTexture = function () {
  16556. return this._texture;
  16557. };
  16558. BaseTexture.prototype.isReady = function () {
  16559. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16560. return true;
  16561. }
  16562. if (this._texture) {
  16563. return this._texture.isReady;
  16564. }
  16565. return false;
  16566. };
  16567. BaseTexture.prototype.getSize = function () {
  16568. if (this._texture._width) {
  16569. return { width: this._texture._width, height: this._texture._height };
  16570. }
  16571. if (this._texture._size) {
  16572. return { width: this._texture._size, height: this._texture._size };
  16573. }
  16574. return { width: 0, height: 0 };
  16575. };
  16576. BaseTexture.prototype.getBaseSize = function () {
  16577. if (!this.isReady())
  16578. return { width: 0, height: 0 };
  16579. if (this._texture._size) {
  16580. return { width: this._texture._size, height: this._texture._size };
  16581. }
  16582. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16583. };
  16584. BaseTexture.prototype.scale = function (ratio) {
  16585. };
  16586. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16587. get: function () {
  16588. return false;
  16589. },
  16590. enumerable: true,
  16591. configurable: true
  16592. });
  16593. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16594. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16595. for (var index = 0; index < texturesCache.length; index++) {
  16596. var texturesCacheEntry = texturesCache[index];
  16597. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16598. texturesCache.splice(index, 1);
  16599. return;
  16600. }
  16601. }
  16602. };
  16603. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16604. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16605. for (var index = 0; index < texturesCache.length; index++) {
  16606. var texturesCacheEntry = texturesCache[index];
  16607. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16608. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16609. texturesCacheEntry.references++;
  16610. return texturesCacheEntry;
  16611. }
  16612. }
  16613. }
  16614. return null;
  16615. };
  16616. BaseTexture.prototype.delayLoad = function () {
  16617. };
  16618. BaseTexture.prototype.releaseInternalTexture = function () {
  16619. if (!this._texture) {
  16620. return;
  16621. }
  16622. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16623. this._texture.references--;
  16624. // Final reference ?
  16625. if (this._texture.references === 0) {
  16626. var index = texturesCache.indexOf(this._texture);
  16627. texturesCache.splice(index, 1);
  16628. this._scene.getEngine()._releaseTexture(this._texture);
  16629. delete this._texture;
  16630. }
  16631. };
  16632. BaseTexture.prototype.clone = function () {
  16633. return null;
  16634. };
  16635. BaseTexture.prototype.dispose = function () {
  16636. // Remove from scene
  16637. var index = this._scene.textures.indexOf(this);
  16638. if (index >= 0) {
  16639. this._scene.textures.splice(index, 1);
  16640. }
  16641. if (this._texture === undefined) {
  16642. return;
  16643. }
  16644. this.releaseInternalTexture();
  16645. // Callback
  16646. if (this.onDispose) {
  16647. this.onDispose();
  16648. }
  16649. };
  16650. return BaseTexture;
  16651. })();
  16652. BABYLON.BaseTexture = BaseTexture;
  16653. })(BABYLON || (BABYLON = {}));
  16654. var BABYLON;
  16655. (function (BABYLON) {
  16656. var Texture = (function (_super) {
  16657. __extends(Texture, _super);
  16658. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16659. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16660. if (onLoad === void 0) { onLoad = null; }
  16661. if (onError === void 0) { onError = null; }
  16662. if (buffer === void 0) { buffer = null; }
  16663. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16664. _super.call(this, scene);
  16665. this.uOffset = 0;
  16666. this.vOffset = 0;
  16667. this.uScale = 1.0;
  16668. this.vScale = 1.0;
  16669. this.uAng = 0;
  16670. this.vAng = 0;
  16671. this.wAng = 0;
  16672. this.name = url;
  16673. this.url = url;
  16674. this._noMipmap = noMipmap;
  16675. this._invertY = invertY;
  16676. this._samplingMode = samplingMode;
  16677. this._buffer = buffer;
  16678. this._deleteBuffer = deleteBuffer;
  16679. if (!url) {
  16680. return;
  16681. }
  16682. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16683. if (!this._texture) {
  16684. if (!scene.useDelayedTextureLoading) {
  16685. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16686. if (deleteBuffer) {
  16687. delete this._buffer;
  16688. }
  16689. }
  16690. else {
  16691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16692. }
  16693. }
  16694. else {
  16695. BABYLON.Tools.SetImmediate(function () {
  16696. if (onLoad) {
  16697. onLoad();
  16698. }
  16699. });
  16700. }
  16701. }
  16702. Texture.prototype.delayLoad = function () {
  16703. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16704. return;
  16705. }
  16706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16707. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16708. if (!this._texture) {
  16709. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16710. if (this._deleteBuffer) {
  16711. delete this._buffer;
  16712. }
  16713. }
  16714. };
  16715. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16716. if (!this._texture) {
  16717. return;
  16718. }
  16719. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16720. };
  16721. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16722. x *= this.uScale;
  16723. y *= this.vScale;
  16724. x -= 0.5 * this.uScale;
  16725. y -= 0.5 * this.vScale;
  16726. z -= 0.5;
  16727. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16728. t.x += 0.5 * this.uScale + this.uOffset;
  16729. t.y += 0.5 * this.vScale + this.vOffset;
  16730. t.z += 0.5;
  16731. };
  16732. Texture.prototype.getTextureMatrix = function () {
  16733. if (this.uOffset === this._cachedUOffset &&
  16734. this.vOffset === this._cachedVOffset &&
  16735. this.uScale === this._cachedUScale &&
  16736. this.vScale === this._cachedVScale &&
  16737. this.uAng === this._cachedUAng &&
  16738. this.vAng === this._cachedVAng &&
  16739. this.wAng === this._cachedWAng) {
  16740. return this._cachedTextureMatrix;
  16741. }
  16742. this._cachedUOffset = this.uOffset;
  16743. this._cachedVOffset = this.vOffset;
  16744. this._cachedUScale = this.uScale;
  16745. this._cachedVScale = this.vScale;
  16746. this._cachedUAng = this.uAng;
  16747. this._cachedVAng = this.vAng;
  16748. this._cachedWAng = this.wAng;
  16749. if (!this._cachedTextureMatrix) {
  16750. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16751. this._rowGenerationMatrix = new BABYLON.Matrix();
  16752. this._t0 = BABYLON.Vector3.Zero();
  16753. this._t1 = BABYLON.Vector3.Zero();
  16754. this._t2 = BABYLON.Vector3.Zero();
  16755. }
  16756. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16757. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16758. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16759. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16760. this._t1.subtractInPlace(this._t0);
  16761. this._t2.subtractInPlace(this._t0);
  16762. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16763. this._cachedTextureMatrix.m[0] = this._t1.x;
  16764. this._cachedTextureMatrix.m[1] = this._t1.y;
  16765. this._cachedTextureMatrix.m[2] = this._t1.z;
  16766. this._cachedTextureMatrix.m[4] = this._t2.x;
  16767. this._cachedTextureMatrix.m[5] = this._t2.y;
  16768. this._cachedTextureMatrix.m[6] = this._t2.z;
  16769. this._cachedTextureMatrix.m[8] = this._t0.x;
  16770. this._cachedTextureMatrix.m[9] = this._t0.y;
  16771. this._cachedTextureMatrix.m[10] = this._t0.z;
  16772. return this._cachedTextureMatrix;
  16773. };
  16774. Texture.prototype.getReflectionTextureMatrix = function () {
  16775. if (this.uOffset === this._cachedUOffset &&
  16776. this.vOffset === this._cachedVOffset &&
  16777. this.uScale === this._cachedUScale &&
  16778. this.vScale === this._cachedVScale &&
  16779. this.coordinatesMode === this._cachedCoordinatesMode) {
  16780. return this._cachedTextureMatrix;
  16781. }
  16782. if (!this._cachedTextureMatrix) {
  16783. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16784. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16785. }
  16786. this._cachedCoordinatesMode = this.coordinatesMode;
  16787. switch (this.coordinatesMode) {
  16788. case Texture.SPHERICAL_MODE:
  16789. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16790. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16791. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16792. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16793. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16794. break;
  16795. case Texture.PLANAR_MODE:
  16796. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16797. this._cachedTextureMatrix[0] = this.uScale;
  16798. this._cachedTextureMatrix[5] = this.vScale;
  16799. this._cachedTextureMatrix[12] = this.uOffset;
  16800. this._cachedTextureMatrix[13] = this.vOffset;
  16801. break;
  16802. case Texture.PROJECTION_MODE:
  16803. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16804. this._projectionModeMatrix.m[0] = 0.5;
  16805. this._projectionModeMatrix.m[5] = -0.5;
  16806. this._projectionModeMatrix.m[10] = 0.0;
  16807. this._projectionModeMatrix.m[12] = 0.5;
  16808. this._projectionModeMatrix.m[13] = 0.5;
  16809. this._projectionModeMatrix.m[14] = 1.0;
  16810. this._projectionModeMatrix.m[15] = 1.0;
  16811. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16812. break;
  16813. default:
  16814. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16815. break;
  16816. }
  16817. return this._cachedTextureMatrix;
  16818. };
  16819. Texture.prototype.clone = function () {
  16820. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16821. // Base texture
  16822. newTexture.hasAlpha = this.hasAlpha;
  16823. newTexture.level = this.level;
  16824. newTexture.wrapU = this.wrapU;
  16825. newTexture.wrapV = this.wrapV;
  16826. newTexture.coordinatesIndex = this.coordinatesIndex;
  16827. newTexture.coordinatesMode = this.coordinatesMode;
  16828. // Texture
  16829. newTexture.uOffset = this.uOffset;
  16830. newTexture.vOffset = this.vOffset;
  16831. newTexture.uScale = this.uScale;
  16832. newTexture.vScale = this.vScale;
  16833. newTexture.uAng = this.uAng;
  16834. newTexture.vAng = this.vAng;
  16835. newTexture.wAng = this.wAng;
  16836. return newTexture;
  16837. };
  16838. // Statics
  16839. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16840. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16841. if (onLoad === void 0) { onLoad = null; }
  16842. if (onError === void 0) { onError = null; }
  16843. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16844. };
  16845. // Constants
  16846. Texture.NEAREST_SAMPLINGMODE = 1;
  16847. Texture.BILINEAR_SAMPLINGMODE = 2;
  16848. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16849. Texture.EXPLICIT_MODE = 0;
  16850. Texture.SPHERICAL_MODE = 1;
  16851. Texture.PLANAR_MODE = 2;
  16852. Texture.CUBIC_MODE = 3;
  16853. Texture.PROJECTION_MODE = 4;
  16854. Texture.SKYBOX_MODE = 5;
  16855. Texture.CLAMP_ADDRESSMODE = 0;
  16856. Texture.WRAP_ADDRESSMODE = 1;
  16857. Texture.MIRROR_ADDRESSMODE = 2;
  16858. return Texture;
  16859. })(BABYLON.BaseTexture);
  16860. BABYLON.Texture = Texture;
  16861. })(BABYLON || (BABYLON = {}));
  16862. var BABYLON;
  16863. (function (BABYLON) {
  16864. var CubeTexture = (function (_super) {
  16865. __extends(CubeTexture, _super);
  16866. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16867. _super.call(this, scene);
  16868. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16869. this.name = rootUrl;
  16870. this.url = rootUrl;
  16871. this._noMipmap = noMipmap;
  16872. this.hasAlpha = false;
  16873. this._texture = this._getFromCache(rootUrl, noMipmap);
  16874. if (!extensions) {
  16875. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16876. }
  16877. this._extensions = extensions;
  16878. if (!this._texture) {
  16879. if (!scene.useDelayedTextureLoading) {
  16880. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16881. }
  16882. else {
  16883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16884. }
  16885. }
  16886. this.isCube = true;
  16887. this._textureMatrix = BABYLON.Matrix.Identity();
  16888. }
  16889. CubeTexture.prototype.clone = function () {
  16890. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16891. // Base texture
  16892. newTexture.level = this.level;
  16893. newTexture.wrapU = this.wrapU;
  16894. newTexture.wrapV = this.wrapV;
  16895. newTexture.coordinatesIndex = this.coordinatesIndex;
  16896. newTexture.coordinatesMode = this.coordinatesMode;
  16897. return newTexture;
  16898. };
  16899. // Methods
  16900. CubeTexture.prototype.delayLoad = function () {
  16901. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16902. return;
  16903. }
  16904. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16905. this._texture = this._getFromCache(this.url, this._noMipmap);
  16906. if (!this._texture) {
  16907. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16908. }
  16909. };
  16910. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16911. return this._textureMatrix;
  16912. };
  16913. return CubeTexture;
  16914. })(BABYLON.BaseTexture);
  16915. BABYLON.CubeTexture = CubeTexture;
  16916. })(BABYLON || (BABYLON = {}));
  16917. var BABYLON;
  16918. (function (BABYLON) {
  16919. var RenderTargetTexture = (function (_super) {
  16920. __extends(RenderTargetTexture, _super);
  16921. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16922. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16923. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16924. _super.call(this, null, scene, !generateMipMaps);
  16925. this.renderList = new Array();
  16926. this.renderParticles = true;
  16927. this.renderSprites = false;
  16928. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16929. this._currentRefreshId = -1;
  16930. this._refreshRate = 1;
  16931. this.name = name;
  16932. this.isRenderTarget = true;
  16933. this._size = size;
  16934. this._generateMipMaps = generateMipMaps;
  16935. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16936. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16937. // Rendering groups
  16938. this._renderingManager = new BABYLON.RenderingManager(scene);
  16939. }
  16940. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16941. this._currentRefreshId = -1;
  16942. };
  16943. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16944. get: function () {
  16945. return this._refreshRate;
  16946. },
  16947. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16948. set: function (value) {
  16949. this._refreshRate = value;
  16950. this.resetRefreshCounter();
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. RenderTargetTexture.prototype._shouldRender = function () {
  16956. if (this._currentRefreshId === -1) {
  16957. this._currentRefreshId = 1;
  16958. return true;
  16959. }
  16960. if (this.refreshRate === this._currentRefreshId) {
  16961. this._currentRefreshId = 1;
  16962. return true;
  16963. }
  16964. this._currentRefreshId++;
  16965. return false;
  16966. };
  16967. RenderTargetTexture.prototype.isReady = function () {
  16968. if (!this.getScene().renderTargetsEnabled) {
  16969. return false;
  16970. }
  16971. return _super.prototype.isReady.call(this);
  16972. };
  16973. RenderTargetTexture.prototype.getRenderSize = function () {
  16974. return this._size;
  16975. };
  16976. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16977. get: function () {
  16978. return true;
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. RenderTargetTexture.prototype.scale = function (ratio) {
  16984. var newSize = this._size * ratio;
  16985. this.resize(newSize, this._generateMipMaps);
  16986. };
  16987. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16988. this.releaseInternalTexture();
  16989. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16990. };
  16991. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16992. var scene = this.getScene();
  16993. var engine = scene.getEngine();
  16994. if (this._waitingRenderList) {
  16995. this.renderList = [];
  16996. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16997. var id = this._waitingRenderList[index];
  16998. this.renderList.push(scene.getMeshByID(id));
  16999. }
  17000. delete this._waitingRenderList;
  17001. }
  17002. if (this.renderList && this.renderList.length === 0) {
  17003. return;
  17004. }
  17005. // Bind
  17006. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17007. engine.bindFramebuffer(this._texture);
  17008. }
  17009. this._renderingManager.reset();
  17010. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17011. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17012. var mesh = currentRenderList[meshIndex];
  17013. if (mesh) {
  17014. if (!mesh.isReady()) {
  17015. // Reset _currentRefreshId
  17016. this.resetRefreshCounter();
  17017. continue;
  17018. }
  17019. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17020. mesh._activate(scene.getRenderId());
  17021. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17022. var subMesh = mesh.subMeshes[subIndex];
  17023. scene._activeIndices += subMesh.indexCount;
  17024. this._renderingManager.dispatch(subMesh);
  17025. }
  17026. }
  17027. }
  17028. }
  17029. if (this.onBeforeRender) {
  17030. this.onBeforeRender();
  17031. }
  17032. // Clear
  17033. if (this.onClear) {
  17034. this.onClear(engine);
  17035. }
  17036. else {
  17037. engine.clear(scene.clearColor, true, true);
  17038. }
  17039. if (!this._doNotChangeAspectRatio) {
  17040. scene.updateTransformMatrix(true);
  17041. }
  17042. // Render
  17043. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17044. if (useCameraPostProcess) {
  17045. scene.postProcessManager._finalizeFrame(false, this._texture);
  17046. }
  17047. if (!this._doNotChangeAspectRatio) {
  17048. scene.updateTransformMatrix(true);
  17049. }
  17050. if (this.onAfterRender) {
  17051. this.onAfterRender();
  17052. }
  17053. // Dump ?
  17054. if (dumpForDebug) {
  17055. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17056. }
  17057. // Unbind
  17058. engine.unBindFramebuffer(this._texture);
  17059. if (this.onAfterUnbind) {
  17060. this.onAfterUnbind();
  17061. }
  17062. };
  17063. RenderTargetTexture.prototype.clone = function () {
  17064. var textureSize = this.getSize();
  17065. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17066. // Base texture
  17067. newTexture.hasAlpha = this.hasAlpha;
  17068. newTexture.level = this.level;
  17069. // RenderTarget Texture
  17070. newTexture.coordinatesMode = this.coordinatesMode;
  17071. newTexture.renderList = this.renderList.slice(0);
  17072. return newTexture;
  17073. };
  17074. return RenderTargetTexture;
  17075. })(BABYLON.Texture);
  17076. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17077. })(BABYLON || (BABYLON = {}));
  17078. var BABYLON;
  17079. (function (BABYLON) {
  17080. var ProceduralTexture = (function (_super) {
  17081. __extends(ProceduralTexture, _super);
  17082. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17084. _super.call(this, null, scene, !generateMipMaps);
  17085. this.isEnabled = true;
  17086. this._currentRefreshId = -1;
  17087. this._refreshRate = 1;
  17088. this._vertexDeclaration = [2];
  17089. this._vertexStrideSize = 2 * 4;
  17090. this._uniforms = new Array();
  17091. this._samplers = new Array();
  17092. this._textures = new Array();
  17093. this._floats = new Array();
  17094. this._floatsArrays = {};
  17095. this._colors3 = new Array();
  17096. this._colors4 = new Array();
  17097. this._vectors2 = new Array();
  17098. this._vectors3 = new Array();
  17099. this._matrices = new Array();
  17100. this._fallbackTextureUsed = false;
  17101. scene._proceduralTextures.push(this);
  17102. this.name = name;
  17103. this.isRenderTarget = true;
  17104. this._size = size;
  17105. this._generateMipMaps = generateMipMaps;
  17106. this.setFragment(fragment);
  17107. this._fallbackTexture = fallbackTexture;
  17108. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17109. // VBO
  17110. var vertices = [];
  17111. vertices.push(1, 1);
  17112. vertices.push(-1, 1);
  17113. vertices.push(-1, -1);
  17114. vertices.push(1, -1);
  17115. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17116. // Indices
  17117. var indices = [];
  17118. indices.push(0);
  17119. indices.push(1);
  17120. indices.push(2);
  17121. indices.push(0);
  17122. indices.push(2);
  17123. indices.push(3);
  17124. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17125. }
  17126. ProceduralTexture.prototype.reset = function () {
  17127. if (this._effect === undefined) {
  17128. return;
  17129. }
  17130. var engine = this.getScene().getEngine();
  17131. engine._releaseEffect(this._effect);
  17132. };
  17133. ProceduralTexture.prototype.isReady = function () {
  17134. var _this = this;
  17135. var engine = this.getScene().getEngine();
  17136. var shaders;
  17137. if (!this._fragment) {
  17138. return false;
  17139. }
  17140. if (this._fallbackTextureUsed) {
  17141. return true;
  17142. }
  17143. if (this._fragment.fragmentElement !== undefined) {
  17144. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17145. }
  17146. else {
  17147. shaders = { vertex: "procedural", fragment: this._fragment };
  17148. }
  17149. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17150. _this.releaseInternalTexture();
  17151. if (_this._fallbackTexture) {
  17152. _this._texture = _this._fallbackTexture._texture;
  17153. _this._texture.references++;
  17154. }
  17155. _this._fallbackTextureUsed = true;
  17156. });
  17157. return this._effect.isReady();
  17158. };
  17159. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17160. this._currentRefreshId = -1;
  17161. };
  17162. ProceduralTexture.prototype.setFragment = function (fragment) {
  17163. this._fragment = fragment;
  17164. };
  17165. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17166. get: function () {
  17167. return this._refreshRate;
  17168. },
  17169. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17170. set: function (value) {
  17171. this._refreshRate = value;
  17172. this.resetRefreshCounter();
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. ProceduralTexture.prototype._shouldRender = function () {
  17178. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17179. return false;
  17180. }
  17181. if (this._fallbackTextureUsed) {
  17182. return false;
  17183. }
  17184. if (this._currentRefreshId === -1) {
  17185. this._currentRefreshId = 1;
  17186. return true;
  17187. }
  17188. if (this.refreshRate === this._currentRefreshId) {
  17189. this._currentRefreshId = 1;
  17190. return true;
  17191. }
  17192. this._currentRefreshId++;
  17193. return false;
  17194. };
  17195. ProceduralTexture.prototype.getRenderSize = function () {
  17196. return this._size;
  17197. };
  17198. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17199. if (this._fallbackTextureUsed) {
  17200. return;
  17201. }
  17202. this.releaseInternalTexture();
  17203. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17204. };
  17205. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17206. if (this._uniforms.indexOf(uniformName) === -1) {
  17207. this._uniforms.push(uniformName);
  17208. }
  17209. };
  17210. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17211. if (this._samplers.indexOf(name) === -1) {
  17212. this._samplers.push(name);
  17213. }
  17214. this._textures[name] = texture;
  17215. return this;
  17216. };
  17217. ProceduralTexture.prototype.setFloat = function (name, value) {
  17218. this._checkUniform(name);
  17219. this._floats[name] = value;
  17220. return this;
  17221. };
  17222. ProceduralTexture.prototype.setFloats = function (name, value) {
  17223. this._checkUniform(name);
  17224. this._floatsArrays[name] = value;
  17225. return this;
  17226. };
  17227. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17228. this._checkUniform(name);
  17229. this._colors3[name] = value;
  17230. return this;
  17231. };
  17232. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17233. this._checkUniform(name);
  17234. this._colors4[name] = value;
  17235. return this;
  17236. };
  17237. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17238. this._checkUniform(name);
  17239. this._vectors2[name] = value;
  17240. return this;
  17241. };
  17242. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17243. this._checkUniform(name);
  17244. this._vectors3[name] = value;
  17245. return this;
  17246. };
  17247. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17248. this._checkUniform(name);
  17249. this._matrices[name] = value;
  17250. return this;
  17251. };
  17252. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17253. var scene = this.getScene();
  17254. var engine = scene.getEngine();
  17255. engine.bindFramebuffer(this._texture);
  17256. // Clear
  17257. engine.clear(scene.clearColor, true, true);
  17258. // Render
  17259. engine.enableEffect(this._effect);
  17260. engine.setState(false);
  17261. // Texture
  17262. for (var name in this._textures) {
  17263. this._effect.setTexture(name, this._textures[name]);
  17264. }
  17265. // Float
  17266. for (name in this._floats) {
  17267. this._effect.setFloat(name, this._floats[name]);
  17268. }
  17269. // Floats
  17270. for (name in this._floatsArrays) {
  17271. this._effect.setArray(name, this._floatsArrays[name]);
  17272. }
  17273. // Color3
  17274. for (name in this._colors3) {
  17275. this._effect.setColor3(name, this._colors3[name]);
  17276. }
  17277. // Color4
  17278. for (name in this._colors4) {
  17279. var color = this._colors4[name];
  17280. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17281. }
  17282. // Vector2
  17283. for (name in this._vectors2) {
  17284. this._effect.setVector2(name, this._vectors2[name]);
  17285. }
  17286. // Vector3
  17287. for (name in this._vectors3) {
  17288. this._effect.setVector3(name, this._vectors3[name]);
  17289. }
  17290. // Matrix
  17291. for (name in this._matrices) {
  17292. this._effect.setMatrix(name, this._matrices[name]);
  17293. }
  17294. // VBOs
  17295. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17296. // Draw order
  17297. engine.draw(true, 0, 6);
  17298. // Unbind
  17299. engine.unBindFramebuffer(this._texture);
  17300. };
  17301. ProceduralTexture.prototype.clone = function () {
  17302. var textureSize = this.getSize();
  17303. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17304. // Base texture
  17305. newTexture.hasAlpha = this.hasAlpha;
  17306. newTexture.level = this.level;
  17307. // RenderTarget Texture
  17308. newTexture.coordinatesMode = this.coordinatesMode;
  17309. return newTexture;
  17310. };
  17311. ProceduralTexture.prototype.dispose = function () {
  17312. var index = this.getScene()._proceduralTextures.indexOf(this);
  17313. if (index >= 0) {
  17314. this.getScene()._proceduralTextures.splice(index, 1);
  17315. }
  17316. _super.prototype.dispose.call(this);
  17317. };
  17318. return ProceduralTexture;
  17319. })(BABYLON.Texture);
  17320. BABYLON.ProceduralTexture = ProceduralTexture;
  17321. })(BABYLON || (BABYLON = {}));
  17322. var BABYLON;
  17323. (function (BABYLON) {
  17324. var MirrorTexture = (function (_super) {
  17325. __extends(MirrorTexture, _super);
  17326. function MirrorTexture(name, size, scene, generateMipMaps) {
  17327. var _this = this;
  17328. _super.call(this, name, size, scene, generateMipMaps, true);
  17329. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17330. this._transformMatrix = BABYLON.Matrix.Zero();
  17331. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17332. this.onBeforeRender = function () {
  17333. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17334. _this._savedViewMatrix = scene.getViewMatrix();
  17335. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17336. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17337. scene.clipPlane = _this.mirrorPlane;
  17338. scene.getEngine().cullBackFaces = false;
  17339. };
  17340. this.onAfterRender = function () {
  17341. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17342. scene.getEngine().cullBackFaces = true;
  17343. delete scene.clipPlane;
  17344. };
  17345. }
  17346. MirrorTexture.prototype.clone = function () {
  17347. var textureSize = this.getSize();
  17348. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17349. // Base texture
  17350. newTexture.hasAlpha = this.hasAlpha;
  17351. newTexture.level = this.level;
  17352. // Mirror Texture
  17353. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17354. newTexture.renderList = this.renderList.slice(0);
  17355. return newTexture;
  17356. };
  17357. return MirrorTexture;
  17358. })(BABYLON.RenderTargetTexture);
  17359. BABYLON.MirrorTexture = MirrorTexture;
  17360. })(BABYLON || (BABYLON = {}));
  17361. var BABYLON;
  17362. (function (BABYLON) {
  17363. var DynamicTexture = (function (_super) {
  17364. __extends(DynamicTexture, _super);
  17365. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17367. _super.call(this, null, scene, !generateMipMaps);
  17368. this.name = name;
  17369. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17370. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17371. this._generateMipMaps = generateMipMaps;
  17372. if (options.getContext) {
  17373. this._canvas = options;
  17374. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17375. }
  17376. else {
  17377. this._canvas = document.createElement("canvas");
  17378. if (options.width) {
  17379. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17380. }
  17381. else {
  17382. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17383. }
  17384. }
  17385. var textureSize = this.getSize();
  17386. this._canvas.width = textureSize.width;
  17387. this._canvas.height = textureSize.height;
  17388. this._context = this._canvas.getContext("2d");
  17389. }
  17390. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17391. get: function () {
  17392. return true;
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. DynamicTexture.prototype.scale = function (ratio) {
  17398. var textureSize = this.getSize();
  17399. textureSize.width *= ratio;
  17400. textureSize.height *= ratio;
  17401. this._canvas.width = textureSize.width;
  17402. this._canvas.height = textureSize.height;
  17403. this.releaseInternalTexture();
  17404. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17405. };
  17406. DynamicTexture.prototype.getContext = function () {
  17407. return this._context;
  17408. };
  17409. DynamicTexture.prototype.clear = function () {
  17410. var size = this.getSize();
  17411. this._context.fillRect(0, 0, size.width, size.height);
  17412. };
  17413. DynamicTexture.prototype.update = function (invertY) {
  17414. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17415. };
  17416. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17417. if (update === void 0) { update = true; }
  17418. var size = this.getSize();
  17419. if (clearColor) {
  17420. this._context.fillStyle = clearColor;
  17421. this._context.fillRect(0, 0, size.width, size.height);
  17422. }
  17423. this._context.font = font;
  17424. if (x === null) {
  17425. var textSize = this._context.measureText(text);
  17426. x = (size.width - textSize.width) / 2;
  17427. }
  17428. this._context.fillStyle = color;
  17429. this._context.fillText(text, x, y);
  17430. if (update) {
  17431. this.update(invertY);
  17432. }
  17433. };
  17434. DynamicTexture.prototype.clone = function () {
  17435. var textureSize = this.getSize();
  17436. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17437. // Base texture
  17438. newTexture.hasAlpha = this.hasAlpha;
  17439. newTexture.level = this.level;
  17440. // Dynamic Texture
  17441. newTexture.wrapU = this.wrapU;
  17442. newTexture.wrapV = this.wrapV;
  17443. return newTexture;
  17444. };
  17445. return DynamicTexture;
  17446. })(BABYLON.Texture);
  17447. BABYLON.DynamicTexture = DynamicTexture;
  17448. })(BABYLON || (BABYLON = {}));
  17449. var BABYLON;
  17450. (function (BABYLON) {
  17451. var VideoTexture = (function (_super) {
  17452. __extends(VideoTexture, _super);
  17453. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17454. var _this = this;
  17455. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17456. if (invertY === void 0) { invertY = false; }
  17457. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17458. _super.call(this, null, scene, !generateMipMaps, invertY);
  17459. this._autoLaunch = true;
  17460. this.name = name;
  17461. this.video = document.createElement("video");
  17462. this.video.autoplay = false;
  17463. this.video.loop = true;
  17464. this.video.addEventListener("canplaythrough", function () {
  17465. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17466. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17467. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17468. }
  17469. else {
  17470. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17471. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17472. generateMipMaps = false;
  17473. }
  17474. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17475. _this._texture.isReady = true;
  17476. });
  17477. urls.forEach(function (url) {
  17478. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17479. var source = document.createElement("source");
  17480. source.src = url;
  17481. _this.video.appendChild(source);
  17482. });
  17483. this._lastUpdate = BABYLON.Tools.Now;
  17484. }
  17485. VideoTexture.prototype.update = function () {
  17486. if (this._autoLaunch) {
  17487. this._autoLaunch = false;
  17488. this.video.play();
  17489. }
  17490. var now = BABYLON.Tools.Now;
  17491. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17492. return false;
  17493. }
  17494. this._lastUpdate = now;
  17495. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17496. return true;
  17497. };
  17498. return VideoTexture;
  17499. })(BABYLON.Texture);
  17500. BABYLON.VideoTexture = VideoTexture;
  17501. })(BABYLON || (BABYLON = {}));
  17502. var BABYLON;
  17503. (function (BABYLON) {
  17504. var CustomProceduralTexture = (function (_super) {
  17505. __extends(CustomProceduralTexture, _super);
  17506. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17507. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17508. this._animate = true;
  17509. this._time = 0;
  17510. this._texturePath = texturePath;
  17511. //Try to load json
  17512. this.loadJson(texturePath);
  17513. this.refreshRate = 1;
  17514. }
  17515. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17516. var _this = this;
  17517. var that = this;
  17518. function noConfigFile() {
  17519. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17520. try {
  17521. that.setFragment(that._texturePath);
  17522. }
  17523. catch (ex) {
  17524. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17525. }
  17526. }
  17527. var configFileUrl = jsonUrl + "/config.json";
  17528. var xhr = new XMLHttpRequest();
  17529. xhr.open("GET", configFileUrl, true);
  17530. xhr.addEventListener("load", function () {
  17531. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17532. try {
  17533. _this._config = JSON.parse(xhr.response);
  17534. _this.updateShaderUniforms();
  17535. _this.updateTextures();
  17536. _this.setFragment(_this._texturePath + "/custom");
  17537. _this._animate = _this._config.animate;
  17538. _this.refreshRate = _this._config.refreshrate;
  17539. }
  17540. catch (ex) {
  17541. noConfigFile();
  17542. }
  17543. }
  17544. else {
  17545. noConfigFile();
  17546. }
  17547. }, false);
  17548. xhr.addEventListener("error", function () {
  17549. noConfigFile();
  17550. }, false);
  17551. try {
  17552. xhr.send();
  17553. }
  17554. catch (ex) {
  17555. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17556. }
  17557. };
  17558. CustomProceduralTexture.prototype.isReady = function () {
  17559. if (!_super.prototype.isReady.call(this)) {
  17560. return false;
  17561. }
  17562. for (var name in this._textures) {
  17563. var texture = this._textures[name];
  17564. if (!texture.isReady()) {
  17565. return false;
  17566. }
  17567. }
  17568. return true;
  17569. };
  17570. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17571. if (this._animate) {
  17572. this._time += this.getScene().getAnimationRatio() * 0.03;
  17573. this.updateShaderUniforms();
  17574. }
  17575. _super.prototype.render.call(this, useCameraPostProcess);
  17576. };
  17577. CustomProceduralTexture.prototype.updateTextures = function () {
  17578. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17579. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17580. }
  17581. };
  17582. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17583. if (this._config) {
  17584. for (var j = 0; j < this._config.uniforms.length; j++) {
  17585. var uniform = this._config.uniforms[j];
  17586. switch (uniform.type) {
  17587. case "float":
  17588. this.setFloat(uniform.name, uniform.value);
  17589. break;
  17590. case "color3":
  17591. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17592. break;
  17593. case "color4":
  17594. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17595. break;
  17596. case "vector2":
  17597. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17598. break;
  17599. case "vector3":
  17600. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17601. break;
  17602. }
  17603. }
  17604. }
  17605. this.setFloat("time", this._time);
  17606. };
  17607. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17608. get: function () {
  17609. return this._animate;
  17610. },
  17611. set: function (value) {
  17612. this._animate = value;
  17613. },
  17614. enumerable: true,
  17615. configurable: true
  17616. });
  17617. return CustomProceduralTexture;
  17618. })(BABYLON.ProceduralTexture);
  17619. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17620. })(BABYLON || (BABYLON = {}));
  17621. var BABYLON;
  17622. (function (BABYLON) {
  17623. var WoodProceduralTexture = (function (_super) {
  17624. __extends(WoodProceduralTexture, _super);
  17625. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17626. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17627. this._ampScale = 100.0;
  17628. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17629. this.updateShaderUniforms();
  17630. this.refreshRate = 0;
  17631. }
  17632. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17633. this.setFloat("ampScale", this._ampScale);
  17634. this.setColor3("woodColor", this._woodColor);
  17635. };
  17636. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17637. get: function () {
  17638. return this._ampScale;
  17639. },
  17640. set: function (value) {
  17641. this._ampScale = value;
  17642. this.updateShaderUniforms();
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17648. get: function () {
  17649. return this._woodColor;
  17650. },
  17651. set: function (value) {
  17652. this._woodColor = value;
  17653. this.updateShaderUniforms();
  17654. },
  17655. enumerable: true,
  17656. configurable: true
  17657. });
  17658. return WoodProceduralTexture;
  17659. })(BABYLON.ProceduralTexture);
  17660. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17661. var FireProceduralTexture = (function (_super) {
  17662. __extends(FireProceduralTexture, _super);
  17663. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17664. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17665. this._time = 0.0;
  17666. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17667. this._autoGenerateTime = true;
  17668. this._alphaThreshold = 0.5;
  17669. this._fireColors = FireProceduralTexture.RedFireColors;
  17670. this.updateShaderUniforms();
  17671. this.refreshRate = 1;
  17672. }
  17673. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17674. this.setFloat("time", this._time);
  17675. this.setVector2("speed", this._speed);
  17676. this.setColor3("c1", this._fireColors[0]);
  17677. this.setColor3("c2", this._fireColors[1]);
  17678. this.setColor3("c3", this._fireColors[2]);
  17679. this.setColor3("c4", this._fireColors[3]);
  17680. this.setColor3("c5", this._fireColors[4]);
  17681. this.setColor3("c6", this._fireColors[5]);
  17682. this.setFloat("alphaThreshold", this._alphaThreshold);
  17683. };
  17684. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17685. if (this._autoGenerateTime) {
  17686. this._time += this.getScene().getAnimationRatio() * 0.03;
  17687. this.updateShaderUniforms();
  17688. }
  17689. _super.prototype.render.call(this, useCameraPostProcess);
  17690. };
  17691. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17692. get: function () {
  17693. return [
  17694. new BABYLON.Color3(0.5, 0.0, 1.0),
  17695. new BABYLON.Color3(0.9, 0.0, 1.0),
  17696. new BABYLON.Color3(0.2, 0.0, 1.0),
  17697. new BABYLON.Color3(1.0, 0.9, 1.0),
  17698. new BABYLON.Color3(0.1, 0.1, 1.0),
  17699. new BABYLON.Color3(0.9, 0.9, 1.0)
  17700. ];
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17706. get: function () {
  17707. return [
  17708. new BABYLON.Color3(0.5, 1.0, 0.0),
  17709. new BABYLON.Color3(0.5, 1.0, 0.0),
  17710. new BABYLON.Color3(0.3, 0.4, 0.0),
  17711. new BABYLON.Color3(0.5, 1.0, 0.0),
  17712. new BABYLON.Color3(0.2, 0.0, 0.0),
  17713. new BABYLON.Color3(0.5, 1.0, 0.0)
  17714. ];
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17720. get: function () {
  17721. return [
  17722. new BABYLON.Color3(0.5, 0.0, 0.1),
  17723. new BABYLON.Color3(0.9, 0.0, 0.0),
  17724. new BABYLON.Color3(0.2, 0.0, 0.0),
  17725. new BABYLON.Color3(1.0, 0.9, 0.0),
  17726. new BABYLON.Color3(0.1, 0.1, 0.1),
  17727. new BABYLON.Color3(0.9, 0.9, 0.9)
  17728. ];
  17729. },
  17730. enumerable: true,
  17731. configurable: true
  17732. });
  17733. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17734. get: function () {
  17735. return [
  17736. new BABYLON.Color3(0.1, 0.0, 0.5),
  17737. new BABYLON.Color3(0.0, 0.0, 0.5),
  17738. new BABYLON.Color3(0.1, 0.0, 0.2),
  17739. new BABYLON.Color3(0.0, 0.0, 1.0),
  17740. new BABYLON.Color3(0.1, 0.2, 0.3),
  17741. new BABYLON.Color3(0.0, 0.2, 0.9)
  17742. ];
  17743. },
  17744. enumerable: true,
  17745. configurable: true
  17746. });
  17747. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17748. get: function () {
  17749. return this._fireColors;
  17750. },
  17751. set: function (value) {
  17752. this._fireColors = value;
  17753. this.updateShaderUniforms();
  17754. },
  17755. enumerable: true,
  17756. configurable: true
  17757. });
  17758. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17759. get: function () {
  17760. return this._time;
  17761. },
  17762. set: function (value) {
  17763. this._time = value;
  17764. this.updateShaderUniforms();
  17765. },
  17766. enumerable: true,
  17767. configurable: true
  17768. });
  17769. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17770. get: function () {
  17771. return this._speed;
  17772. },
  17773. set: function (value) {
  17774. this._speed = value;
  17775. this.updateShaderUniforms();
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17781. get: function () {
  17782. return this._alphaThreshold;
  17783. },
  17784. set: function (value) {
  17785. this._alphaThreshold = value;
  17786. this.updateShaderUniforms();
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. return FireProceduralTexture;
  17792. })(BABYLON.ProceduralTexture);
  17793. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17794. var CloudProceduralTexture = (function (_super) {
  17795. __extends(CloudProceduralTexture, _super);
  17796. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17797. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17798. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17799. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17800. this.updateShaderUniforms();
  17801. this.refreshRate = 0;
  17802. }
  17803. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17804. this.setColor4("skyColor", this._skyColor);
  17805. this.setColor4("cloudColor", this._cloudColor);
  17806. };
  17807. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17808. get: function () {
  17809. return this._skyColor;
  17810. },
  17811. set: function (value) {
  17812. this._skyColor = value;
  17813. this.updateShaderUniforms();
  17814. },
  17815. enumerable: true,
  17816. configurable: true
  17817. });
  17818. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17819. get: function () {
  17820. return this._cloudColor;
  17821. },
  17822. set: function (value) {
  17823. this._cloudColor = value;
  17824. this.updateShaderUniforms();
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. return CloudProceduralTexture;
  17830. })(BABYLON.ProceduralTexture);
  17831. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17832. var GrassProceduralTexture = (function (_super) {
  17833. __extends(GrassProceduralTexture, _super);
  17834. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17835. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17836. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17837. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17838. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17839. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17840. this._grassColors = [
  17841. new BABYLON.Color3(0.29, 0.38, 0.02),
  17842. new BABYLON.Color3(0.36, 0.49, 0.09),
  17843. new BABYLON.Color3(0.51, 0.6, 0.28)
  17844. ];
  17845. this.updateShaderUniforms();
  17846. this.refreshRate = 0;
  17847. }
  17848. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17849. this.setColor3("herb1Color", this._grassColors[0]);
  17850. this.setColor3("herb2Color", this._grassColors[1]);
  17851. this.setColor3("herb3Color", this._grassColors[2]);
  17852. this.setColor3("groundColor", this._groundColor);
  17853. };
  17854. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17855. get: function () {
  17856. return this._grassColors;
  17857. },
  17858. set: function (value) {
  17859. this._grassColors = value;
  17860. this.updateShaderUniforms();
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17866. get: function () {
  17867. return this._groundColor;
  17868. },
  17869. set: function (value) {
  17870. this.groundColor = value;
  17871. this.updateShaderUniforms();
  17872. },
  17873. enumerable: true,
  17874. configurable: true
  17875. });
  17876. return GrassProceduralTexture;
  17877. })(BABYLON.ProceduralTexture);
  17878. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17879. var RoadProceduralTexture = (function (_super) {
  17880. __extends(RoadProceduralTexture, _super);
  17881. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17882. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17883. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17884. this.updateShaderUniforms();
  17885. this.refreshRate = 0;
  17886. }
  17887. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17888. this.setColor3("roadColor", this._roadColor);
  17889. };
  17890. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17891. get: function () {
  17892. return this._roadColor;
  17893. },
  17894. set: function (value) {
  17895. this._roadColor = value;
  17896. this.updateShaderUniforms();
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. return RoadProceduralTexture;
  17902. })(BABYLON.ProceduralTexture);
  17903. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17904. var BrickProceduralTexture = (function (_super) {
  17905. __extends(BrickProceduralTexture, _super);
  17906. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17907. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17908. this._numberOfBricksHeight = 15;
  17909. this._numberOfBricksWidth = 5;
  17910. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17911. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17912. this.updateShaderUniforms();
  17913. this.refreshRate = 0;
  17914. }
  17915. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17916. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17917. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17918. this.setColor3("brickColor", this._brickColor);
  17919. this.setColor3("jointColor", this._jointColor);
  17920. };
  17921. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17922. get: function () {
  17923. return this._numberOfBricksHeight;
  17924. },
  17925. set: function (value) {
  17926. this._numberOfBricksHeight = value;
  17927. this.updateShaderUniforms();
  17928. },
  17929. enumerable: true,
  17930. configurable: true
  17931. });
  17932. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17933. get: function () {
  17934. return this._numberOfBricksWidth;
  17935. },
  17936. set: function (value) {
  17937. this._numberOfBricksWidth = value;
  17938. this.updateShaderUniforms();
  17939. },
  17940. enumerable: true,
  17941. configurable: true
  17942. });
  17943. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17944. get: function () {
  17945. return this._jointColor;
  17946. },
  17947. set: function (value) {
  17948. this._jointColor = value;
  17949. this.updateShaderUniforms();
  17950. },
  17951. enumerable: true,
  17952. configurable: true
  17953. });
  17954. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17955. get: function () {
  17956. return this._brickColor;
  17957. },
  17958. set: function (value) {
  17959. this._brickColor = value;
  17960. this.updateShaderUniforms();
  17961. },
  17962. enumerable: true,
  17963. configurable: true
  17964. });
  17965. return BrickProceduralTexture;
  17966. })(BABYLON.ProceduralTexture);
  17967. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17968. var MarbleProceduralTexture = (function (_super) {
  17969. __extends(MarbleProceduralTexture, _super);
  17970. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17971. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17972. this._numberOfTilesHeight = 3;
  17973. this._numberOfTilesWidth = 3;
  17974. this._amplitude = 9.0;
  17975. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17976. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17977. this.updateShaderUniforms();
  17978. this.refreshRate = 0;
  17979. }
  17980. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17981. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17982. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17983. this.setFloat("amplitude", this._amplitude);
  17984. this.setColor3("marbleColor", this._marbleColor);
  17985. this.setColor3("jointColor", this._jointColor);
  17986. };
  17987. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17988. get: function () {
  17989. return this._numberOfTilesHeight;
  17990. },
  17991. set: function (value) {
  17992. this._numberOfTilesHeight = value;
  17993. this.updateShaderUniforms();
  17994. },
  17995. enumerable: true,
  17996. configurable: true
  17997. });
  17998. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17999. get: function () {
  18000. return this._numberOfTilesWidth;
  18001. },
  18002. set: function (value) {
  18003. this._numberOfTilesWidth = value;
  18004. this.updateShaderUniforms();
  18005. },
  18006. enumerable: true,
  18007. configurable: true
  18008. });
  18009. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18010. get: function () {
  18011. return this._jointColor;
  18012. },
  18013. set: function (value) {
  18014. this._jointColor = value;
  18015. this.updateShaderUniforms();
  18016. },
  18017. enumerable: true,
  18018. configurable: true
  18019. });
  18020. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18021. get: function () {
  18022. return this._marbleColor;
  18023. },
  18024. set: function (value) {
  18025. this._marbleColor = value;
  18026. this.updateShaderUniforms();
  18027. },
  18028. enumerable: true,
  18029. configurable: true
  18030. });
  18031. return MarbleProceduralTexture;
  18032. })(BABYLON.ProceduralTexture);
  18033. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18034. })(BABYLON || (BABYLON = {}));
  18035. var BABYLON;
  18036. (function (BABYLON) {
  18037. var EffectFallbacks = (function () {
  18038. function EffectFallbacks() {
  18039. this._defines = {};
  18040. this._currentRank = 32;
  18041. this._maxRank = -1;
  18042. }
  18043. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18044. if (!this._defines[rank]) {
  18045. if (rank < this._currentRank) {
  18046. this._currentRank = rank;
  18047. }
  18048. if (rank > this._maxRank) {
  18049. this._maxRank = rank;
  18050. }
  18051. this._defines[rank] = new Array();
  18052. }
  18053. this._defines[rank].push(define);
  18054. };
  18055. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18056. get: function () {
  18057. return this._currentRank <= this._maxRank;
  18058. },
  18059. enumerable: true,
  18060. configurable: true
  18061. });
  18062. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18063. var currentFallbacks = this._defines[this._currentRank];
  18064. for (var index = 0; index < currentFallbacks.length; index++) {
  18065. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18066. }
  18067. this._currentRank++;
  18068. return currentDefines;
  18069. };
  18070. return EffectFallbacks;
  18071. })();
  18072. BABYLON.EffectFallbacks = EffectFallbacks;
  18073. var Effect = (function () {
  18074. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18075. var _this = this;
  18076. this._isReady = false;
  18077. this._compilationError = "";
  18078. this._valueCache = [];
  18079. this._engine = engine;
  18080. this.name = baseName;
  18081. this.defines = defines;
  18082. this._uniformsNames = uniformsNames.concat(samplers);
  18083. this._samplers = samplers;
  18084. this._attributesNames = attributesNames;
  18085. this.onError = onError;
  18086. this.onCompiled = onCompiled;
  18087. var vertexSource;
  18088. var fragmentSource;
  18089. if (baseName.vertexElement) {
  18090. vertexSource = document.getElementById(baseName.vertexElement);
  18091. if (!vertexSource) {
  18092. vertexSource = baseName.vertexElement;
  18093. }
  18094. }
  18095. else {
  18096. vertexSource = baseName.vertex || baseName;
  18097. }
  18098. if (baseName.fragmentElement) {
  18099. fragmentSource = document.getElementById(baseName.fragmentElement);
  18100. if (!fragmentSource) {
  18101. fragmentSource = baseName.fragmentElement;
  18102. }
  18103. }
  18104. else {
  18105. fragmentSource = baseName.fragment || baseName;
  18106. }
  18107. this._loadVertexShader(vertexSource, function (vertexCode) {
  18108. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18109. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18110. });
  18111. });
  18112. }
  18113. // Properties
  18114. Effect.prototype.isReady = function () {
  18115. return this._isReady;
  18116. };
  18117. Effect.prototype.getProgram = function () {
  18118. return this._program;
  18119. };
  18120. Effect.prototype.getAttributesNames = function () {
  18121. return this._attributesNames;
  18122. };
  18123. Effect.prototype.getAttributeLocation = function (index) {
  18124. return this._attributes[index];
  18125. };
  18126. Effect.prototype.getAttributeLocationByName = function (name) {
  18127. var index = this._attributesNames.indexOf(name);
  18128. return this._attributes[index];
  18129. };
  18130. Effect.prototype.getAttributesCount = function () {
  18131. return this._attributes.length;
  18132. };
  18133. Effect.prototype.getUniformIndex = function (uniformName) {
  18134. return this._uniformsNames.indexOf(uniformName);
  18135. };
  18136. Effect.prototype.getUniform = function (uniformName) {
  18137. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18138. };
  18139. Effect.prototype.getSamplers = function () {
  18140. return this._samplers;
  18141. };
  18142. Effect.prototype.getCompilationError = function () {
  18143. return this._compilationError;
  18144. };
  18145. // Methods
  18146. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18147. // DOM element ?
  18148. if (vertex instanceof HTMLElement) {
  18149. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18150. callback(vertexCode);
  18151. return;
  18152. }
  18153. // Is in local store ?
  18154. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18155. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18156. return;
  18157. }
  18158. var vertexShaderUrl;
  18159. if (vertex[0] === "." || vertex[0] === "/") {
  18160. vertexShaderUrl = vertex;
  18161. }
  18162. else {
  18163. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18164. }
  18165. // Vertex shader
  18166. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18167. };
  18168. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18169. // DOM element ?
  18170. if (fragment instanceof HTMLElement) {
  18171. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18172. callback(fragmentCode);
  18173. return;
  18174. }
  18175. // Is in local store ?
  18176. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18177. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18178. return;
  18179. }
  18180. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18181. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18182. return;
  18183. }
  18184. var fragmentShaderUrl;
  18185. if (fragment[0] === "." || fragment[0] === "/") {
  18186. fragmentShaderUrl = fragment;
  18187. }
  18188. else {
  18189. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18190. }
  18191. // Fragment shader
  18192. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18193. };
  18194. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18195. try {
  18196. var engine = this._engine;
  18197. if (!engine.getCaps().highPrecisionShaderSupported) {
  18198. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18199. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18200. }
  18201. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18202. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18203. this._attributes = engine.getAttributes(this._program, attributesNames);
  18204. for (var index = 0; index < this._samplers.length; index++) {
  18205. var sampler = this.getUniform(this._samplers[index]);
  18206. if (sampler == null) {
  18207. this._samplers.splice(index, 1);
  18208. index--;
  18209. }
  18210. }
  18211. engine.bindSamplers(this);
  18212. this._isReady = true;
  18213. if (this.onCompiled) {
  18214. this.onCompiled(this);
  18215. }
  18216. }
  18217. catch (e) {
  18218. // Is it a problem with precision?
  18219. if (e.message.indexOf("highp") !== -1) {
  18220. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18221. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18222. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18223. return;
  18224. }
  18225. // Let's go through fallbacks then
  18226. if (fallbacks && fallbacks.isMoreFallbacks) {
  18227. defines = fallbacks.reduce(defines);
  18228. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18229. }
  18230. else {
  18231. BABYLON.Tools.Error("Unable to compile effect: ");
  18232. if (this.name.vertexElement) {
  18233. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18234. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18235. }
  18236. else if (this.name.vertex) {
  18237. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18238. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18239. }
  18240. else {
  18241. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18242. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18243. }
  18244. BABYLON.Tools.Error("Defines: " + defines);
  18245. BABYLON.Tools.Error("Error: " + e.message);
  18246. this._compilationError = e.message;
  18247. if (this.onError) {
  18248. this.onError(this, this._compilationError);
  18249. }
  18250. }
  18251. }
  18252. };
  18253. Effect.prototype._bindTexture = function (channel, texture) {
  18254. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18255. };
  18256. Effect.prototype.setTexture = function (channel, texture) {
  18257. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18258. };
  18259. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18260. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18261. };
  18262. //public _cacheMatrix(uniformName, matrix) {
  18263. // if (!this._valueCache[uniformName]) {
  18264. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18265. // }
  18266. // for (var index = 0; index < 16; index++) {
  18267. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18268. // }
  18269. //};
  18270. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18271. if (!this._valueCache[uniformName]) {
  18272. this._valueCache[uniformName] = [x, y];
  18273. return;
  18274. }
  18275. this._valueCache[uniformName][0] = x;
  18276. this._valueCache[uniformName][1] = y;
  18277. };
  18278. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18279. if (!this._valueCache[uniformName]) {
  18280. this._valueCache[uniformName] = [x, y, z];
  18281. return;
  18282. }
  18283. this._valueCache[uniformName][0] = x;
  18284. this._valueCache[uniformName][1] = y;
  18285. this._valueCache[uniformName][2] = z;
  18286. };
  18287. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18288. if (!this._valueCache[uniformName]) {
  18289. this._valueCache[uniformName] = [x, y, z, w];
  18290. return;
  18291. }
  18292. this._valueCache[uniformName][0] = x;
  18293. this._valueCache[uniformName][1] = y;
  18294. this._valueCache[uniformName][2] = z;
  18295. this._valueCache[uniformName][3] = w;
  18296. };
  18297. Effect.prototype.setArray = function (uniformName, array) {
  18298. this._engine.setArray(this.getUniform(uniformName), array);
  18299. return this;
  18300. };
  18301. Effect.prototype.setArray2 = function (uniformName, array) {
  18302. this._engine.setArray2(this.getUniform(uniformName), array);
  18303. return this;
  18304. };
  18305. Effect.prototype.setArray3 = function (uniformName, array) {
  18306. this._engine.setArray3(this.getUniform(uniformName), array);
  18307. return this;
  18308. };
  18309. Effect.prototype.setArray4 = function (uniformName, array) {
  18310. this._engine.setArray4(this.getUniform(uniformName), array);
  18311. return this;
  18312. };
  18313. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18314. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18315. return this;
  18316. };
  18317. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18318. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18319. // return;
  18320. //this._cacheMatrix(uniformName, matrix);
  18321. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18322. return this;
  18323. };
  18324. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18325. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18326. return this;
  18327. };
  18328. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18329. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18330. return this;
  18331. };
  18332. Effect.prototype.setFloat = function (uniformName, value) {
  18333. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18334. return this;
  18335. this._valueCache[uniformName] = value;
  18336. this._engine.setFloat(this.getUniform(uniformName), value);
  18337. return this;
  18338. };
  18339. Effect.prototype.setBool = function (uniformName, bool) {
  18340. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18341. return this;
  18342. this._valueCache[uniformName] = bool;
  18343. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18344. return this;
  18345. };
  18346. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18347. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18348. return this;
  18349. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18350. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18351. return this;
  18352. };
  18353. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18354. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18355. return this;
  18356. this._cacheFloat2(uniformName, x, y);
  18357. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18358. return this;
  18359. };
  18360. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18361. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18362. return this;
  18363. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18364. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18365. return this;
  18366. };
  18367. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18368. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18369. return this;
  18370. this._cacheFloat3(uniformName, x, y, z);
  18371. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18372. return this;
  18373. };
  18374. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18375. 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)
  18376. return this;
  18377. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18378. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18379. return this;
  18380. };
  18381. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18382. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18383. return this;
  18384. this._cacheFloat4(uniformName, x, y, z, w);
  18385. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18386. return this;
  18387. };
  18388. Effect.prototype.setColor3 = function (uniformName, color3) {
  18389. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18390. return this;
  18391. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18392. this._engine.setColor3(this.getUniform(uniformName), color3);
  18393. return this;
  18394. };
  18395. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18396. 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)
  18397. return this;
  18398. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18399. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18400. return this;
  18401. };
  18402. // Statics
  18403. Effect.ShadersStore = {};
  18404. return Effect;
  18405. })();
  18406. BABYLON.Effect = Effect;
  18407. })(BABYLON || (BABYLON = {}));
  18408. var BABYLON;
  18409. (function (BABYLON) {
  18410. var Material = (function () {
  18411. function Material(name, scene, doNotAdd) {
  18412. this.name = name;
  18413. this.checkReadyOnEveryCall = true;
  18414. this.checkReadyOnlyOnce = false;
  18415. this.state = "";
  18416. this.alpha = 1.0;
  18417. this.backFaceCulling = true;
  18418. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18419. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18420. this.disableDepthWrite = false;
  18421. this._wasPreviouslyReady = false;
  18422. this._fillMode = Material.TriangleFillMode;
  18423. this.pointSize = 1.0;
  18424. this.zOffset = 0;
  18425. this.id = name;
  18426. this._scene = scene;
  18427. if (!doNotAdd) {
  18428. scene.materials.push(this);
  18429. }
  18430. }
  18431. Object.defineProperty(Material, "TriangleFillMode", {
  18432. get: function () {
  18433. return Material._TriangleFillMode;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. Object.defineProperty(Material, "WireFrameFillMode", {
  18439. get: function () {
  18440. return Material._WireFrameFillMode;
  18441. },
  18442. enumerable: true,
  18443. configurable: true
  18444. });
  18445. Object.defineProperty(Material, "PointFillMode", {
  18446. get: function () {
  18447. return Material._PointFillMode;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18453. get: function () {
  18454. return Material._ClockWiseSideOrientation;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18460. get: function () {
  18461. return Material._CounterClockWiseSideOrientation;
  18462. },
  18463. enumerable: true,
  18464. configurable: true
  18465. });
  18466. Object.defineProperty(Material.prototype, "wireframe", {
  18467. get: function () {
  18468. return this._fillMode === Material.WireFrameFillMode;
  18469. },
  18470. set: function (value) {
  18471. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. Object.defineProperty(Material.prototype, "pointsCloud", {
  18477. get: function () {
  18478. return this._fillMode === Material.PointFillMode;
  18479. },
  18480. set: function (value) {
  18481. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. Object.defineProperty(Material.prototype, "fillMode", {
  18487. get: function () {
  18488. return this._fillMode;
  18489. },
  18490. set: function (value) {
  18491. this._fillMode = value;
  18492. },
  18493. enumerable: true,
  18494. configurable: true
  18495. });
  18496. Material.prototype.isReady = function (mesh, useInstances) {
  18497. return true;
  18498. };
  18499. Material.prototype.getEffect = function () {
  18500. return this._effect;
  18501. };
  18502. Material.prototype.getScene = function () {
  18503. return this._scene;
  18504. };
  18505. Material.prototype.needAlphaBlending = function () {
  18506. return (this.alpha < 1.0);
  18507. };
  18508. Material.prototype.needAlphaTesting = function () {
  18509. return false;
  18510. };
  18511. Material.prototype.getAlphaTestTexture = function () {
  18512. return null;
  18513. };
  18514. Material.prototype.trackCreation = function (onCompiled, onError) {
  18515. };
  18516. Material.prototype._preBind = function () {
  18517. var engine = this._scene.getEngine();
  18518. engine.enableEffect(this._effect);
  18519. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18520. };
  18521. Material.prototype.bind = function (world, mesh) {
  18522. this._scene._cachedMaterial = this;
  18523. if (this.onBind) {
  18524. this.onBind(this, mesh);
  18525. }
  18526. if (this.disableDepthWrite) {
  18527. var engine = this._scene.getEngine();
  18528. this._cachedDepthWriteState = engine.getDepthWrite();
  18529. engine.setDepthWrite(false);
  18530. }
  18531. };
  18532. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18533. };
  18534. Material.prototype.unbind = function () {
  18535. if (this.disableDepthWrite) {
  18536. var engine = this._scene.getEngine();
  18537. engine.setDepthWrite(this._cachedDepthWriteState);
  18538. }
  18539. };
  18540. Material.prototype.clone = function (name) {
  18541. return null;
  18542. };
  18543. Material.prototype.dispose = function (forceDisposeEffect) {
  18544. // Remove from scene
  18545. var index = this._scene.materials.indexOf(this);
  18546. this._scene.materials.splice(index, 1);
  18547. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18548. if (forceDisposeEffect && this._effect) {
  18549. this._scene.getEngine()._releaseEffect(this._effect);
  18550. this._effect = null;
  18551. }
  18552. // Callback
  18553. if (this.onDispose) {
  18554. this.onDispose();
  18555. }
  18556. };
  18557. Material._TriangleFillMode = 0;
  18558. Material._WireFrameFillMode = 1;
  18559. Material._PointFillMode = 2;
  18560. Material._ClockWiseSideOrientation = 0;
  18561. Material._CounterClockWiseSideOrientation = 1;
  18562. return Material;
  18563. })();
  18564. BABYLON.Material = Material;
  18565. })(BABYLON || (BABYLON = {}));
  18566. var BABYLON;
  18567. (function (BABYLON) {
  18568. var maxSimultaneousLights = 4;
  18569. var FresnelParameters = (function () {
  18570. function FresnelParameters() {
  18571. this.isEnabled = true;
  18572. this.leftColor = BABYLON.Color3.White();
  18573. this.rightColor = BABYLON.Color3.Black();
  18574. this.bias = 0;
  18575. this.power = 1;
  18576. }
  18577. return FresnelParameters;
  18578. })();
  18579. BABYLON.FresnelParameters = FresnelParameters;
  18580. var StandardMaterialDefines = (function () {
  18581. function StandardMaterialDefines() {
  18582. this.DIFFUSE = false;
  18583. this.AMBIENT = false;
  18584. this.OPACITY = false;
  18585. this.OPACITYRGB = false;
  18586. this.REFLECTION = false;
  18587. this.EMISSIVE = false;
  18588. this.SPECULAR = false;
  18589. this.BUMP = false;
  18590. this.SPECULAROVERALPHA = false;
  18591. this.CLIPPLANE = false;
  18592. this.ALPHATEST = false;
  18593. this.ALPHAFROMDIFFUSE = false;
  18594. this.POINTSIZE = false;
  18595. this.FOG = false;
  18596. this.LIGHT0 = false;
  18597. this.LIGHT1 = false;
  18598. this.LIGHT2 = false;
  18599. this.LIGHT3 = false;
  18600. this.SPOTLIGHT0 = false;
  18601. this.SPOTLIGHT1 = false;
  18602. this.SPOTLIGHT2 = false;
  18603. this.SPOTLIGHT3 = false;
  18604. this.HEMILIGHT0 = false;
  18605. this.HEMILIGHT1 = false;
  18606. this.HEMILIGHT2 = false;
  18607. this.HEMILIGHT3 = false;
  18608. this.POINTDIRLIGHT0 = false;
  18609. this.POINTDIRLIGHT1 = false;
  18610. this.POINTDIRLIGHT2 = false;
  18611. this.POINTDIRLIGHT3 = false;
  18612. this.SPECULARTERM = false;
  18613. this.SHADOW0 = false;
  18614. this.SHADOW1 = false;
  18615. this.SHADOW2 = false;
  18616. this.SHADOW3 = false;
  18617. this.SHADOWS = false;
  18618. this.SHADOWVSM0 = false;
  18619. this.SHADOWVSM1 = false;
  18620. this.SHADOWVSM2 = false;
  18621. this.SHADOWVSM3 = false;
  18622. this.SHADOWPCF0 = false;
  18623. this.SHADOWPCF1 = false;
  18624. this.SHADOWPCF2 = false;
  18625. this.SHADOWPCF3 = false;
  18626. this.DIFFUSEFRESNEL = false;
  18627. this.OPACITYFRESNEL = false;
  18628. this.REFLECTIONFRESNEL = false;
  18629. this.EMISSIVEFRESNEL = false;
  18630. this.FRESNEL = false;
  18631. this.NORMAL = false;
  18632. this.UV1 = false;
  18633. this.UV2 = false;
  18634. this.VERTEXCOLOR = false;
  18635. this.VERTEXALPHA = false;
  18636. this.BONES = false;
  18637. this.BONES4 = false;
  18638. this.BonesPerMesh = 0;
  18639. this.INSTANCES = false;
  18640. this.GLOSSINESS = false;
  18641. this.ROUGHNESS = false;
  18642. this.EMISSIVEASILLUMINATION = false;
  18643. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18644. this.LIGHTMAP = false;
  18645. this._keys = Object.keys(this);
  18646. }
  18647. StandardMaterialDefines.prototype.isEqual = function (other) {
  18648. for (var index = 0; index < this._keys.length; index++) {
  18649. var prop = this._keys[index];
  18650. if (this[prop] !== other[prop]) {
  18651. return false;
  18652. }
  18653. }
  18654. return true;
  18655. };
  18656. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18657. for (var index = 0; index < this._keys.length; index++) {
  18658. var prop = this._keys[index];
  18659. other[prop] = this[prop];
  18660. }
  18661. };
  18662. StandardMaterialDefines.prototype.reset = function () {
  18663. for (var index = 0; index < this._keys.length; index++) {
  18664. var prop = this._keys[index];
  18665. if (prop === "BonesPerMesh") {
  18666. this[prop] = 0;
  18667. continue;
  18668. }
  18669. this[prop] = false;
  18670. }
  18671. };
  18672. StandardMaterialDefines.prototype.toString = function () {
  18673. var result = "";
  18674. for (var index = 0; index < this._keys.length; index++) {
  18675. var prop = this._keys[index];
  18676. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18677. result += "#define BonesPerMesh " + this[prop] + "\n";
  18678. continue;
  18679. }
  18680. if (this[prop]) {
  18681. result += "#define " + prop + "\n";
  18682. }
  18683. }
  18684. return result;
  18685. };
  18686. return StandardMaterialDefines;
  18687. })();
  18688. var StandardMaterial = (function (_super) {
  18689. __extends(StandardMaterial, _super);
  18690. function StandardMaterial(name, scene) {
  18691. var _this = this;
  18692. _super.call(this, name, scene);
  18693. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18694. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18695. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18696. this.specularPower = 64;
  18697. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18698. this.useAlphaFromDiffuseTexture = false;
  18699. this.useEmissiveAsIllumination = false;
  18700. this.useReflectionFresnelFromSpecular = false;
  18701. this.useSpecularOverAlpha = true;
  18702. this.fogEnabled = true;
  18703. this.roughness = 0;
  18704. this.lightmapThreshold = 0;
  18705. this.useGlossinessFromSpecularMapAlpha = false;
  18706. this._renderTargets = new BABYLON.SmartArray(16);
  18707. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18708. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18709. this._scaledDiffuse = new BABYLON.Color3();
  18710. this._scaledSpecular = new BABYLON.Color3();
  18711. this._defines = new StandardMaterialDefines();
  18712. this._cachedDefines = new StandardMaterialDefines();
  18713. this._cachedDefines.BonesPerMesh = -1;
  18714. this.getRenderTargetTextures = function () {
  18715. _this._renderTargets.reset();
  18716. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18717. _this._renderTargets.push(_this.reflectionTexture);
  18718. }
  18719. return _this._renderTargets;
  18720. };
  18721. }
  18722. StandardMaterial.prototype.needAlphaBlending = function () {
  18723. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18724. };
  18725. StandardMaterial.prototype.needAlphaTesting = function () {
  18726. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18727. };
  18728. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18729. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18730. };
  18731. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18732. return this.diffuseTexture;
  18733. };
  18734. // Methods
  18735. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18736. if (this.checkReadyOnlyOnce) {
  18737. if (this._wasPreviouslyReady) {
  18738. return true;
  18739. }
  18740. }
  18741. var scene = this.getScene();
  18742. if (!this.checkReadyOnEveryCall) {
  18743. if (this._renderId === scene.getRenderId()) {
  18744. return true;
  18745. }
  18746. }
  18747. var engine = scene.getEngine();
  18748. var needNormals = false;
  18749. var needUVs = false;
  18750. this._defines.reset();
  18751. // Textures
  18752. if (scene.texturesEnabled) {
  18753. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18754. if (!this.diffuseTexture.isReady()) {
  18755. return false;
  18756. }
  18757. else {
  18758. needUVs = true;
  18759. this._defines.DIFFUSE = true;
  18760. }
  18761. }
  18762. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18763. if (!this.ambientTexture.isReady()) {
  18764. return false;
  18765. }
  18766. else {
  18767. needUVs = true;
  18768. this._defines.AMBIENT = true;
  18769. }
  18770. }
  18771. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18772. if (!this.opacityTexture.isReady()) {
  18773. return false;
  18774. }
  18775. else {
  18776. needUVs = true;
  18777. this._defines.OPACITY = true;
  18778. if (this.opacityTexture.getAlphaFromRGB) {
  18779. this._defines.OPACITYRGB = true;
  18780. }
  18781. }
  18782. }
  18783. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18784. if (!this.reflectionTexture.isReady()) {
  18785. return false;
  18786. }
  18787. else {
  18788. needNormals = true;
  18789. needUVs = true;
  18790. this._defines.REFLECTION = true;
  18791. if (this.roughness > 0) {
  18792. this._defines.ROUGHNESS = true;
  18793. }
  18794. }
  18795. }
  18796. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18797. if (!this.emissiveTexture.isReady()) {
  18798. return false;
  18799. }
  18800. else {
  18801. needUVs = true;
  18802. this._defines.EMISSIVE = true;
  18803. }
  18804. }
  18805. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18806. if (!this.lightmapTexture.isReady()) {
  18807. return false;
  18808. }
  18809. else {
  18810. needUVs = true;
  18811. this._defines.LIGHTMAP = true;
  18812. }
  18813. }
  18814. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18815. if (!this.specularTexture.isReady()) {
  18816. return false;
  18817. }
  18818. else {
  18819. needUVs = true;
  18820. this._defines.SPECULAR = true;
  18821. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18822. }
  18823. }
  18824. }
  18825. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18826. if (!this.bumpTexture.isReady()) {
  18827. return false;
  18828. }
  18829. else {
  18830. needUVs = true;
  18831. this._defines.BUMP = true;
  18832. }
  18833. }
  18834. // Effect
  18835. if (scene.clipPlane) {
  18836. this._defines.CLIPPLANE = true;
  18837. }
  18838. if (engine.getAlphaTesting()) {
  18839. this._defines.ALPHATEST = true;
  18840. }
  18841. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18842. this._defines.ALPHAFROMDIFFUSE = true;
  18843. }
  18844. if (this.useEmissiveAsIllumination) {
  18845. this._defines.EMISSIVEASILLUMINATION = true;
  18846. }
  18847. if (this.useReflectionFresnelFromSpecular) {
  18848. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18849. }
  18850. // Point size
  18851. if (this.pointsCloud || scene.forcePointsCloud) {
  18852. this._defines.POINTSIZE = true;
  18853. }
  18854. // Fog
  18855. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18856. this._defines.FOG = true;
  18857. }
  18858. var lightIndex = 0;
  18859. if (scene.lightsEnabled) {
  18860. for (var index = 0; index < scene.lights.length; index++) {
  18861. var light = scene.lights[index];
  18862. if (!light.isEnabled()) {
  18863. continue;
  18864. }
  18865. // Excluded check
  18866. if (light._excludedMeshesIds.length > 0) {
  18867. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18868. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18869. if (excludedMesh) {
  18870. light.excludedMeshes.push(excludedMesh);
  18871. }
  18872. }
  18873. light._excludedMeshesIds = [];
  18874. }
  18875. // Included check
  18876. if (light._includedOnlyMeshesIds.length > 0) {
  18877. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18878. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18879. if (includedOnlyMesh) {
  18880. light.includedOnlyMeshes.push(includedOnlyMesh);
  18881. }
  18882. }
  18883. light._includedOnlyMeshesIds = [];
  18884. }
  18885. if (!light.canAffectMesh(mesh)) {
  18886. continue;
  18887. }
  18888. needNormals = true;
  18889. this._defines["LIGHT" + lightIndex] = true;
  18890. var type;
  18891. if (light instanceof BABYLON.SpotLight) {
  18892. type = "SPOTLIGHT" + lightIndex;
  18893. }
  18894. else if (light instanceof BABYLON.HemisphericLight) {
  18895. type = "HEMILIGHT" + lightIndex;
  18896. }
  18897. else {
  18898. type = "POINTDIRLIGHT" + lightIndex;
  18899. }
  18900. this._defines[type] = true;
  18901. // Specular
  18902. if (!light.specular.equalsFloats(0, 0, 0)) {
  18903. this._defines.SPECULARTERM = true;
  18904. }
  18905. // Shadows
  18906. if (scene.shadowsEnabled) {
  18907. var shadowGenerator = light.getShadowGenerator();
  18908. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18909. this._defines["SHADOW" + lightIndex] = true;
  18910. this._defines.SHADOWS = true;
  18911. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18912. this._defines["SHADOWVSM" + lightIndex] = true;
  18913. }
  18914. if (shadowGenerator.usePoissonSampling) {
  18915. this._defines["SHADOWPCF" + lightIndex] = true;
  18916. }
  18917. }
  18918. }
  18919. lightIndex++;
  18920. if (lightIndex === maxSimultaneousLights)
  18921. break;
  18922. }
  18923. }
  18924. if (StandardMaterial.FresnelEnabled) {
  18925. // Fresnel
  18926. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18927. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18928. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18929. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18930. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18931. this._defines.DIFFUSEFRESNEL = true;
  18932. }
  18933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18934. this._defines.OPACITYFRESNEL = true;
  18935. }
  18936. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18937. this._defines.REFLECTIONFRESNEL = true;
  18938. }
  18939. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18940. this._defines.EMISSIVEFRESNEL = true;
  18941. }
  18942. needNormals = true;
  18943. this._defines.FRESNEL = true;
  18944. }
  18945. }
  18946. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18947. this._defines.SPECULAROVERALPHA = true;
  18948. }
  18949. // Attribs
  18950. if (mesh) {
  18951. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18952. this._defines.NORMAL = true;
  18953. }
  18954. if (needUVs) {
  18955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18956. this._defines.UV1 = true;
  18957. }
  18958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18959. this._defines.UV2 = true;
  18960. }
  18961. }
  18962. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18963. this._defines.VERTEXCOLOR = true;
  18964. if (mesh.hasVertexAlpha) {
  18965. this._defines.VERTEXALPHA = true;
  18966. }
  18967. }
  18968. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18969. this._defines.BONES = true;
  18970. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18971. this._defines.BONES4 = true;
  18972. }
  18973. // Instances
  18974. if (useInstances) {
  18975. this._defines.INSTANCES = true;
  18976. }
  18977. }
  18978. // Get correct effect
  18979. if (!this._defines.isEqual(this._cachedDefines)) {
  18980. this._defines.cloneTo(this._cachedDefines);
  18981. scene.resetCachedMaterial();
  18982. // Fallbacks
  18983. var fallbacks = new BABYLON.EffectFallbacks();
  18984. if (this._defines.REFLECTION) {
  18985. fallbacks.addFallback(0, "REFLECTION");
  18986. }
  18987. if (this._defines.SPECULAR) {
  18988. fallbacks.addFallback(0, "SPECULAR");
  18989. }
  18990. if (this._defines.BUMP) {
  18991. fallbacks.addFallback(0, "BUMP");
  18992. }
  18993. if (this._defines.SPECULAROVERALPHA) {
  18994. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18995. }
  18996. if (this._defines.FOG) {
  18997. fallbacks.addFallback(1, "FOG");
  18998. }
  18999. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19000. if (!this._defines["LIGHT" + lightIndex]) {
  19001. continue;
  19002. }
  19003. if (lightIndex > 0) {
  19004. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19005. }
  19006. if (this._defines["SHADOW" + lightIndex]) {
  19007. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19008. }
  19009. if (this._defines["SHADOWPCF" + lightIndex]) {
  19010. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19011. }
  19012. if (this._defines["SHADOWVSM" + lightIndex]) {
  19013. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19014. }
  19015. }
  19016. if (this._defines.SPECULARTERM) {
  19017. fallbacks.addFallback(0, "SPECULARTERM");
  19018. }
  19019. if (this._defines.DIFFUSEFRESNEL) {
  19020. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19021. }
  19022. if (this._defines.OPACITYFRESNEL) {
  19023. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19024. }
  19025. if (this._defines.REFLECTIONFRESNEL) {
  19026. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19027. }
  19028. if (this._defines.EMISSIVEFRESNEL) {
  19029. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19030. }
  19031. if (this._defines.FRESNEL) {
  19032. fallbacks.addFallback(4, "FRESNEL");
  19033. }
  19034. if (this._defines.BONES4) {
  19035. fallbacks.addFallback(0, "BONES4");
  19036. }
  19037. //Attributes
  19038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19039. if (this._defines.NORMAL) {
  19040. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19041. }
  19042. if (this._defines.UV1) {
  19043. attribs.push(BABYLON.VertexBuffer.UVKind);
  19044. }
  19045. if (this._defines.UV2) {
  19046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19047. }
  19048. if (this._defines.VERTEXCOLOR) {
  19049. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19050. }
  19051. if (this._defines.BONES) {
  19052. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19053. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19054. }
  19055. if (this._defines.INSTANCES) {
  19056. attribs.push("world0");
  19057. attribs.push("world1");
  19058. attribs.push("world2");
  19059. attribs.push("world3");
  19060. }
  19061. // Legacy browser patch
  19062. var shaderName = "default";
  19063. if (!scene.getEngine().getCaps().standardDerivatives) {
  19064. shaderName = "legacydefault";
  19065. }
  19066. var join = this._defines.toString();
  19067. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19068. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19069. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19070. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19071. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19072. "vFogInfos", "vFogColor", "pointSize",
  19073. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19074. "mBones",
  19075. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19076. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19077. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19078. "roughness"
  19079. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19080. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19081. ], join, fallbacks, this.onCompiled, this.onError);
  19082. }
  19083. if (!this._effect.isReady()) {
  19084. return false;
  19085. }
  19086. this._renderId = scene.getRenderId();
  19087. this._wasPreviouslyReady = true;
  19088. return true;
  19089. };
  19090. StandardMaterial.prototype.unbind = function () {
  19091. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19092. this._effect.setTexture("reflection2DSampler", null);
  19093. }
  19094. _super.prototype.unbind.call(this);
  19095. };
  19096. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19097. this._effect.setMatrix("world", world);
  19098. };
  19099. StandardMaterial.prototype.bind = function (world, mesh) {
  19100. var scene = this.getScene();
  19101. // Matrices
  19102. this.bindOnlyWorldMatrix(world);
  19103. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19104. // Bones
  19105. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19106. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19107. }
  19108. if (scene.getCachedMaterial() !== this) {
  19109. if (StandardMaterial.FresnelEnabled) {
  19110. // Fresnel
  19111. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19112. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19113. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19114. }
  19115. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19116. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19117. }
  19118. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19119. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19120. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19121. }
  19122. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19123. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19124. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19125. }
  19126. }
  19127. // Textures
  19128. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19129. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19130. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19131. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19132. }
  19133. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19134. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19135. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19136. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19137. }
  19138. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19139. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19140. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19141. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19142. }
  19143. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19144. if (this.reflectionTexture.isCube) {
  19145. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19146. if (this._defines.ROUGHNESS) {
  19147. this._effect.setFloat("roughness", this.roughness);
  19148. }
  19149. }
  19150. else {
  19151. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19152. }
  19153. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19154. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19155. }
  19156. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19157. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19158. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19159. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19160. }
  19161. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19162. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19163. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19164. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19165. }
  19166. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19167. this._effect.setTexture("specularSampler", this.specularTexture);
  19168. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19169. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19170. }
  19171. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19172. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19173. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19174. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19175. }
  19176. // Clip plane
  19177. if (scene.clipPlane) {
  19178. var clipPlane = scene.clipPlane;
  19179. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19180. }
  19181. // Point size
  19182. if (this.pointsCloud) {
  19183. this._effect.setFloat("pointSize", this.pointSize);
  19184. }
  19185. // Colors
  19186. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19187. // Scaling down color according to emissive
  19188. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19189. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19190. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19191. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19192. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19193. if (this._defines.SPECULARTERM) {
  19194. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19195. }
  19196. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19197. }
  19198. // Scaling down color according to emissive
  19199. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19200. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19201. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19202. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19203. if (scene.lightsEnabled) {
  19204. var lightIndex = 0;
  19205. for (var index = 0; index < scene.lights.length; index++) {
  19206. var light = scene.lights[index];
  19207. if (!light.isEnabled()) {
  19208. continue;
  19209. }
  19210. if (!light.canAffectMesh(mesh)) {
  19211. continue;
  19212. }
  19213. if (light instanceof BABYLON.PointLight) {
  19214. // Point Light
  19215. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19216. }
  19217. else if (light instanceof BABYLON.DirectionalLight) {
  19218. // Directional Light
  19219. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19220. }
  19221. else if (light instanceof BABYLON.SpotLight) {
  19222. // Spot Light
  19223. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19224. }
  19225. else if (light instanceof BABYLON.HemisphericLight) {
  19226. // Hemispheric Light
  19227. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19228. }
  19229. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19230. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19231. if (this._defines.SPECULARTERM) {
  19232. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19233. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19234. }
  19235. // Shadows
  19236. if (scene.shadowsEnabled) {
  19237. var shadowGenerator = light.getShadowGenerator();
  19238. if (mesh.receiveShadows && shadowGenerator) {
  19239. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19240. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19241. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19242. }
  19243. }
  19244. lightIndex++;
  19245. if (lightIndex === maxSimultaneousLights)
  19246. break;
  19247. }
  19248. }
  19249. // View
  19250. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19251. this._effect.setMatrix("view", scene.getViewMatrix());
  19252. }
  19253. // Fog
  19254. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19255. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19256. this._effect.setColor3("vFogColor", scene.fogColor);
  19257. }
  19258. _super.prototype.bind.call(this, world, mesh);
  19259. };
  19260. StandardMaterial.prototype.getAnimatables = function () {
  19261. var results = [];
  19262. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19263. results.push(this.diffuseTexture);
  19264. }
  19265. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19266. results.push(this.ambientTexture);
  19267. }
  19268. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19269. results.push(this.opacityTexture);
  19270. }
  19271. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19272. results.push(this.reflectionTexture);
  19273. }
  19274. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19275. results.push(this.emissiveTexture);
  19276. }
  19277. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19278. results.push(this.specularTexture);
  19279. }
  19280. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19281. results.push(this.bumpTexture);
  19282. }
  19283. return results;
  19284. };
  19285. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19286. if (this.diffuseTexture) {
  19287. this.diffuseTexture.dispose();
  19288. }
  19289. if (this.ambientTexture) {
  19290. this.ambientTexture.dispose();
  19291. }
  19292. if (this.opacityTexture) {
  19293. this.opacityTexture.dispose();
  19294. }
  19295. if (this.reflectionTexture) {
  19296. this.reflectionTexture.dispose();
  19297. }
  19298. if (this.emissiveTexture) {
  19299. this.emissiveTexture.dispose();
  19300. }
  19301. if (this.specularTexture) {
  19302. this.specularTexture.dispose();
  19303. }
  19304. if (this.bumpTexture) {
  19305. this.bumpTexture.dispose();
  19306. }
  19307. _super.prototype.dispose.call(this, forceDisposeEffect);
  19308. };
  19309. StandardMaterial.prototype.clone = function (name) {
  19310. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19311. // Base material
  19312. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19313. newStandardMaterial.alpha = this.alpha;
  19314. newStandardMaterial.fillMode = this.fillMode;
  19315. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19316. // Standard material
  19317. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19318. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19319. }
  19320. if (this.ambientTexture && this.ambientTexture.clone) {
  19321. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19322. }
  19323. if (this.opacityTexture && this.opacityTexture.clone) {
  19324. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19325. }
  19326. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19327. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19328. }
  19329. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19330. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19331. }
  19332. if (this.specularTexture && this.specularTexture.clone) {
  19333. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19334. }
  19335. if (this.bumpTexture && this.bumpTexture.clone) {
  19336. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19337. }
  19338. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19339. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19340. newStandardMaterial.specularColor = this.specularColor.clone();
  19341. newStandardMaterial.specularPower = this.specularPower;
  19342. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19343. return newStandardMaterial;
  19344. };
  19345. // Statics
  19346. // Flags used to enable or disable a type of texture for all Standard Materials
  19347. StandardMaterial.DiffuseTextureEnabled = true;
  19348. StandardMaterial.AmbientTextureEnabled = true;
  19349. StandardMaterial.OpacityTextureEnabled = true;
  19350. StandardMaterial.ReflectionTextureEnabled = true;
  19351. StandardMaterial.EmissiveTextureEnabled = true;
  19352. StandardMaterial.SpecularTextureEnabled = true;
  19353. StandardMaterial.BumpTextureEnabled = true;
  19354. StandardMaterial.FresnelEnabled = true;
  19355. StandardMaterial.LightmapEnabled = true;
  19356. return StandardMaterial;
  19357. })(BABYLON.Material);
  19358. BABYLON.StandardMaterial = StandardMaterial;
  19359. })(BABYLON || (BABYLON = {}));
  19360. var BABYLON;
  19361. (function (BABYLON) {
  19362. var MultiMaterial = (function (_super) {
  19363. __extends(MultiMaterial, _super);
  19364. function MultiMaterial(name, scene) {
  19365. _super.call(this, name, scene, true);
  19366. this.subMaterials = new Array();
  19367. scene.multiMaterials.push(this);
  19368. }
  19369. // Properties
  19370. MultiMaterial.prototype.getSubMaterial = function (index) {
  19371. if (index < 0 || index >= this.subMaterials.length) {
  19372. return this.getScene().defaultMaterial;
  19373. }
  19374. return this.subMaterials[index];
  19375. };
  19376. // Methods
  19377. MultiMaterial.prototype.isReady = function (mesh) {
  19378. for (var index = 0; index < this.subMaterials.length; index++) {
  19379. var subMaterial = this.subMaterials[index];
  19380. if (subMaterial) {
  19381. if (!this.subMaterials[index].isReady(mesh)) {
  19382. return false;
  19383. }
  19384. }
  19385. }
  19386. return true;
  19387. };
  19388. MultiMaterial.prototype.clone = function (name) {
  19389. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19390. for (var index = 0; index < this.subMaterials.length; index++) {
  19391. var subMaterial = this.subMaterials[index];
  19392. newMultiMaterial.subMaterials.push(subMaterial);
  19393. }
  19394. return newMultiMaterial;
  19395. };
  19396. return MultiMaterial;
  19397. })(BABYLON.Material);
  19398. BABYLON.MultiMaterial = MultiMaterial;
  19399. })(BABYLON || (BABYLON = {}));
  19400. var BABYLON;
  19401. (function (BABYLON) {
  19402. var SceneLoader = (function () {
  19403. function SceneLoader() {
  19404. }
  19405. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19406. get: function () {
  19407. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19408. },
  19409. set: function (value) {
  19410. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19411. },
  19412. enumerable: true,
  19413. configurable: true
  19414. });
  19415. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19416. get: function () {
  19417. return SceneLoader._ShowLoadingScreen;
  19418. },
  19419. set: function (value) {
  19420. SceneLoader._ShowLoadingScreen = value;
  19421. },
  19422. enumerable: true,
  19423. configurable: true
  19424. });
  19425. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19426. var dotPosition = sceneFilename.lastIndexOf(".");
  19427. var queryStringPosition = sceneFilename.indexOf("?");
  19428. if (queryStringPosition === -1) {
  19429. queryStringPosition = sceneFilename.length;
  19430. }
  19431. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19432. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19433. var plugin = this._registeredPlugins[index];
  19434. if (plugin.extensions.indexOf(extension) !== -1) {
  19435. return plugin;
  19436. }
  19437. }
  19438. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19439. };
  19440. // Public functions
  19441. SceneLoader.RegisterPlugin = function (plugin) {
  19442. plugin.extensions = plugin.extensions.toLowerCase();
  19443. SceneLoader._registeredPlugins.push(plugin);
  19444. };
  19445. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19446. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19447. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19448. return;
  19449. }
  19450. var loadingToken = {};
  19451. scene._addPendingData(loadingToken);
  19452. var manifestChecked = function (success) {
  19453. scene.database = database;
  19454. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19455. var importMeshFromData = function (data) {
  19456. var meshes = [];
  19457. var particleSystems = [];
  19458. var skeletons = [];
  19459. try {
  19460. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19461. if (onerror) {
  19462. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19463. }
  19464. scene._removePendingData(loadingToken);
  19465. return;
  19466. }
  19467. }
  19468. catch (e) {
  19469. if (onerror) {
  19470. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19471. }
  19472. scene._removePendingData(loadingToken);
  19473. return;
  19474. }
  19475. if (onsuccess) {
  19476. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19477. onsuccess(meshes, particleSystems, skeletons);
  19478. scene._removePendingData(loadingToken);
  19479. }
  19480. };
  19481. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19482. // Direct load
  19483. importMeshFromData(sceneFilename.substr(5));
  19484. return;
  19485. }
  19486. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19487. importMeshFromData(data);
  19488. }, progressCallBack, database);
  19489. };
  19490. if (scene.getEngine().enableOfflineSupport) {
  19491. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19492. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19493. }
  19494. else {
  19495. manifestChecked(true);
  19496. }
  19497. };
  19498. /**
  19499. * Load a scene
  19500. * @param rootUrl a string that defines the root url for scene and resources
  19501. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19502. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19503. */
  19504. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19505. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19506. };
  19507. /**
  19508. * Append a scene
  19509. * @param rootUrl a string that defines the root url for scene and resources
  19510. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19511. * @param scene is the instance of BABYLON.Scene to append to
  19512. */
  19513. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19514. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19515. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19516. return;
  19517. }
  19518. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19519. var database;
  19520. var loadingToken = {};
  19521. scene._addPendingData(loadingToken);
  19522. if (SceneLoader.ShowLoadingScreen) {
  19523. scene.getEngine().displayLoadingUI();
  19524. }
  19525. var loadSceneFromData = function (data) {
  19526. scene.database = database;
  19527. if (!plugin.load(scene, data, rootUrl)) {
  19528. if (onerror) {
  19529. onerror(scene);
  19530. }
  19531. scene._removePendingData(loadingToken);
  19532. scene.getEngine().hideLoadingUI();
  19533. return;
  19534. }
  19535. if (onsuccess) {
  19536. onsuccess(scene);
  19537. }
  19538. scene._removePendingData(loadingToken);
  19539. if (SceneLoader.ShowLoadingScreen) {
  19540. scene.executeWhenReady(function () {
  19541. scene.getEngine().hideLoadingUI();
  19542. });
  19543. }
  19544. };
  19545. var manifestChecked = function (success) {
  19546. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19547. };
  19548. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19549. // Direct load
  19550. loadSceneFromData(sceneFilename.substr(5));
  19551. return;
  19552. }
  19553. if (rootUrl.indexOf("file:") === -1) {
  19554. if (scene.getEngine().enableOfflineSupport) {
  19555. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19556. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19557. }
  19558. else {
  19559. manifestChecked(true);
  19560. }
  19561. }
  19562. else {
  19563. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19564. }
  19565. };
  19566. // Flags
  19567. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19568. SceneLoader._ShowLoadingScreen = true;
  19569. // Members
  19570. SceneLoader._registeredPlugins = new Array();
  19571. return SceneLoader;
  19572. })();
  19573. BABYLON.SceneLoader = SceneLoader;
  19574. ;
  19575. })(BABYLON || (BABYLON = {}));
  19576. var BABYLON;
  19577. (function (BABYLON) {
  19578. var Internals;
  19579. (function (Internals) {
  19580. var checkColors4 = function (colors, count) {
  19581. // Check if color3 was used
  19582. if (colors.length === count * 3) {
  19583. var colors4 = [];
  19584. for (var index = 0; index < colors.length; index += 3) {
  19585. var newIndex = (index / 3) * 4;
  19586. colors4[newIndex] = colors[index];
  19587. colors4[newIndex + 1] = colors[index + 1];
  19588. colors4[newIndex + 2] = colors[index + 2];
  19589. colors4[newIndex + 3] = 1.0;
  19590. }
  19591. return colors4;
  19592. }
  19593. return colors;
  19594. };
  19595. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19596. var texture = null;
  19597. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19598. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19599. texture.name = parsedTexture.name;
  19600. texture.hasAlpha = parsedTexture.hasAlpha;
  19601. texture.level = parsedTexture.level;
  19602. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19603. }
  19604. return texture;
  19605. };
  19606. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19607. if (parsedTexture.isCube) {
  19608. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19609. }
  19610. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19611. return null;
  19612. }
  19613. var texture;
  19614. if (parsedTexture.mirrorPlane) {
  19615. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19616. texture._waitingRenderList = parsedTexture.renderList;
  19617. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19618. }
  19619. else if (parsedTexture.isRenderTarget) {
  19620. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19621. texture._waitingRenderList = parsedTexture.renderList;
  19622. }
  19623. else {
  19624. if (parsedTexture.base64String) {
  19625. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19626. }
  19627. else {
  19628. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19629. }
  19630. }
  19631. texture.name = parsedTexture.name;
  19632. texture.hasAlpha = parsedTexture.hasAlpha;
  19633. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19634. texture.level = parsedTexture.level;
  19635. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19636. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19637. texture.uOffset = parsedTexture.uOffset;
  19638. texture.vOffset = parsedTexture.vOffset;
  19639. texture.uScale = parsedTexture.uScale;
  19640. texture.vScale = parsedTexture.vScale;
  19641. texture.uAng = parsedTexture.uAng;
  19642. texture.vAng = parsedTexture.vAng;
  19643. texture.wAng = parsedTexture.wAng;
  19644. texture.wrapU = parsedTexture.wrapU;
  19645. texture.wrapV = parsedTexture.wrapV;
  19646. // Animations
  19647. if (parsedTexture.animations) {
  19648. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19649. var parsedAnimation = parsedTexture.animations[animationIndex];
  19650. texture.animations.push(parseAnimation(parsedAnimation));
  19651. }
  19652. }
  19653. return texture;
  19654. };
  19655. var parseSkeleton = function (parsedSkeleton, scene) {
  19656. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19657. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19658. var parsedBone = parsedSkeleton.bones[index];
  19659. var parentBone = null;
  19660. if (parsedBone.parentBoneIndex > -1) {
  19661. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19662. }
  19663. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19664. if (parsedBone.animation) {
  19665. bone.animations.push(parseAnimation(parsedBone.animation));
  19666. }
  19667. }
  19668. return skeleton;
  19669. };
  19670. var parseFresnelParameters = function (parsedFresnelParameters) {
  19671. var fresnelParameters = new BABYLON.FresnelParameters();
  19672. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19673. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19674. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19675. fresnelParameters.bias = parsedFresnelParameters.bias;
  19676. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19677. return fresnelParameters;
  19678. };
  19679. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19680. var material;
  19681. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19682. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19683. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19684. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19685. material.specularPower = parsedMaterial.specularPower;
  19686. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19687. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19688. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19689. material.alpha = parsedMaterial.alpha;
  19690. material.id = parsedMaterial.id;
  19691. if (parsedMaterial.disableDepthWrite) {
  19692. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19693. }
  19694. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19695. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19696. material.wireframe = parsedMaterial.wireframe;
  19697. if (parsedMaterial.diffuseTexture) {
  19698. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19699. }
  19700. if (parsedMaterial.diffuseFresnelParameters) {
  19701. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19702. }
  19703. if (parsedMaterial.ambientTexture) {
  19704. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19705. }
  19706. if (parsedMaterial.opacityTexture) {
  19707. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19708. }
  19709. if (parsedMaterial.opacityFresnelParameters) {
  19710. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19711. }
  19712. if (parsedMaterial.reflectionTexture) {
  19713. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19714. }
  19715. if (parsedMaterial.reflectionFresnelParameters) {
  19716. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19717. }
  19718. if (parsedMaterial.emissiveTexture) {
  19719. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19720. }
  19721. if (parsedMaterial.lightmapTexture) {
  19722. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19723. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19724. }
  19725. if (parsedMaterial.emissiveFresnelParameters) {
  19726. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19727. }
  19728. if (parsedMaterial.specularTexture) {
  19729. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19730. }
  19731. if (parsedMaterial.bumpTexture) {
  19732. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19733. }
  19734. if (parsedMaterial.checkReadyOnlyOnce) {
  19735. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19736. }
  19737. return material;
  19738. };
  19739. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19740. for (var index = 0; index < parsedData.materials.length; index++) {
  19741. var parsedMaterial = parsedData.materials[index];
  19742. if (parsedMaterial.id === id) {
  19743. return parseMaterial(parsedMaterial, scene, rootUrl);
  19744. }
  19745. }
  19746. return null;
  19747. };
  19748. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19749. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19750. multiMaterial.id = parsedMultiMaterial.id;
  19751. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19752. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19753. var subMatId = parsedMultiMaterial.materials[matIndex];
  19754. if (subMatId) {
  19755. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19756. }
  19757. else {
  19758. multiMaterial.subMaterials.push(null);
  19759. }
  19760. }
  19761. return multiMaterial;
  19762. };
  19763. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19764. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19765. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19766. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19767. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19768. var parsedFlare = parsedLensFlareSystem.flares[index];
  19769. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19770. }
  19771. return lensFlareSystem;
  19772. };
  19773. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19774. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19775. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19776. if (parsedParticleSystem.textureName) {
  19777. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19778. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19779. }
  19780. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19781. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19782. particleSystem.minSize = parsedParticleSystem.minSize;
  19783. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19784. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19785. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19786. particleSystem.emitter = emitter;
  19787. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19788. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19789. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19790. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19791. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19792. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19793. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19794. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19795. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19796. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19797. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19798. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19799. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19800. particleSystem.start();
  19801. return particleSystem;
  19802. };
  19803. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19804. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19805. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19806. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19807. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19808. shadowGenerator.getShadowMap().renderList.push(mesh);
  19809. }
  19810. if (parsedShadowGenerator.usePoissonSampling) {
  19811. shadowGenerator.usePoissonSampling = true;
  19812. }
  19813. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19814. shadowGenerator.useVarianceShadowMap = true;
  19815. }
  19816. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19817. shadowGenerator.useBlurVarianceShadowMap = true;
  19818. if (parsedShadowGenerator.blurScale) {
  19819. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19820. }
  19821. if (parsedShadowGenerator.blurBoxOffset) {
  19822. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19823. }
  19824. }
  19825. if (parsedShadowGenerator.bias !== undefined) {
  19826. shadowGenerator.bias = parsedShadowGenerator.bias;
  19827. }
  19828. return shadowGenerator;
  19829. };
  19830. var parseAnimation = function (parsedAnimation) {
  19831. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19832. var dataType = parsedAnimation.dataType;
  19833. var keys = [];
  19834. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19835. var key = parsedAnimation.keys[index];
  19836. var data;
  19837. switch (dataType) {
  19838. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19839. data = key.values[0];
  19840. break;
  19841. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19842. data = BABYLON.Quaternion.FromArray(key.values);
  19843. break;
  19844. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19845. data = BABYLON.Matrix.FromArray(key.values);
  19846. break;
  19847. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19848. default:
  19849. data = BABYLON.Vector3.FromArray(key.values);
  19850. break;
  19851. }
  19852. keys.push({
  19853. frame: key.frame,
  19854. value: data
  19855. });
  19856. }
  19857. animation.setKeys(keys);
  19858. return animation;
  19859. };
  19860. var parseLight = function (parsedLight, scene) {
  19861. var light;
  19862. switch (parsedLight.type) {
  19863. case 0:
  19864. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19865. break;
  19866. case 1:
  19867. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19868. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19869. break;
  19870. case 2:
  19871. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19872. break;
  19873. case 3:
  19874. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19875. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19876. break;
  19877. }
  19878. light.id = parsedLight.id;
  19879. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19880. if (parsedLight.intensity !== undefined) {
  19881. light.intensity = parsedLight.intensity;
  19882. }
  19883. if (parsedLight.range) {
  19884. light.range = parsedLight.range;
  19885. }
  19886. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19887. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19888. if (parsedLight.excludedMeshesIds) {
  19889. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19890. }
  19891. // Parent
  19892. if (parsedLight.parentId) {
  19893. light._waitingParentId = parsedLight.parentId;
  19894. }
  19895. if (parsedLight.includedOnlyMeshesIds) {
  19896. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19897. }
  19898. // Animations
  19899. if (parsedLight.animations) {
  19900. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19901. var parsedAnimation = parsedLight.animations[animationIndex];
  19902. light.animations.push(parseAnimation(parsedAnimation));
  19903. }
  19904. }
  19905. if (parsedLight.autoAnimate) {
  19906. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19907. }
  19908. };
  19909. var parseCamera = function (parsedCamera, scene) {
  19910. var camera;
  19911. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19912. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19913. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19914. var alpha = parsedCamera.alpha;
  19915. var beta = parsedCamera.beta;
  19916. var radius = parsedCamera.radius;
  19917. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19918. var interaxial_distance = parsedCamera.interaxial_distance;
  19919. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19920. }
  19921. else {
  19922. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19923. }
  19924. }
  19925. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19926. interaxial_distance = parsedCamera.interaxial_distance;
  19927. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19928. }
  19929. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19930. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19931. }
  19932. else if (parsedCamera.type === "FollowCamera") {
  19933. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19934. camera.heightOffset = parsedCamera.heightOffset;
  19935. camera.radius = parsedCamera.radius;
  19936. camera.rotationOffset = parsedCamera.rotationOffset;
  19937. if (lockedTargetMesh)
  19938. camera.target = lockedTargetMesh;
  19939. }
  19940. else if (parsedCamera.type === "GamepadCamera") {
  19941. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19942. }
  19943. else if (parsedCamera.type === "TouchCamera") {
  19944. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19945. }
  19946. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19947. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19948. }
  19949. else if (parsedCamera.type === "WebVRFreeCamera") {
  19950. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19951. }
  19952. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19953. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19954. }
  19955. else {
  19956. // Free Camera is the default value
  19957. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19958. }
  19959. // apply 3d rig, when found
  19960. if (parsedCamera.cameraRigMode) {
  19961. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19962. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19963. }
  19964. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19965. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19966. camera.lockedTarget = lockedTargetMesh;
  19967. }
  19968. camera.id = parsedCamera.id;
  19969. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19970. // Parent
  19971. if (parsedCamera.parentId) {
  19972. camera._waitingParentId = parsedCamera.parentId;
  19973. }
  19974. // Target
  19975. if (parsedCamera.target) {
  19976. if (camera.setTarget) {
  19977. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19978. }
  19979. else {
  19980. //For ArcRotate
  19981. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19982. }
  19983. }
  19984. else {
  19985. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19986. }
  19987. camera.fov = parsedCamera.fov;
  19988. camera.minZ = parsedCamera.minZ;
  19989. camera.maxZ = parsedCamera.maxZ;
  19990. camera.speed = parsedCamera.speed;
  19991. camera.inertia = parsedCamera.inertia;
  19992. camera.checkCollisions = parsedCamera.checkCollisions;
  19993. camera.applyGravity = parsedCamera.applyGravity;
  19994. if (parsedCamera.ellipsoid) {
  19995. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19996. }
  19997. // Animations
  19998. if (parsedCamera.animations) {
  19999. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20000. var parsedAnimation = parsedCamera.animations[animationIndex];
  20001. camera.animations.push(parseAnimation(parsedAnimation));
  20002. }
  20003. }
  20004. if (parsedCamera.autoAnimate) {
  20005. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20006. }
  20007. // Layer Mask
  20008. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20009. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20010. }
  20011. else {
  20012. camera.layerMask = 0x0FFFFFFF;
  20013. }
  20014. return camera;
  20015. };
  20016. var parseGeometry = function (parsedGeometry, scene) {
  20017. var id = parsedGeometry.id;
  20018. return scene.getGeometryByID(id);
  20019. };
  20020. var parseBox = function (parsedBox, scene) {
  20021. if (parseGeometry(parsedBox, scene)) {
  20022. return null; // null since geometry could be something else than a box...
  20023. }
  20024. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20025. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20026. scene.pushGeometry(box, true);
  20027. return box;
  20028. };
  20029. var parseSphere = function (parsedSphere, scene) {
  20030. if (parseGeometry(parsedSphere, scene)) {
  20031. return null; // null since geometry could be something else than a sphere...
  20032. }
  20033. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20034. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20035. scene.pushGeometry(sphere, true);
  20036. return sphere;
  20037. };
  20038. var parseCylinder = function (parsedCylinder, scene) {
  20039. if (parseGeometry(parsedCylinder, scene)) {
  20040. return null; // null since geometry could be something else than a cylinder...
  20041. }
  20042. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20043. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20044. scene.pushGeometry(cylinder, true);
  20045. return cylinder;
  20046. };
  20047. var parseTorus = function (parsedTorus, scene) {
  20048. if (parseGeometry(parsedTorus, scene)) {
  20049. return null; // null since geometry could be something else than a torus...
  20050. }
  20051. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20052. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20053. scene.pushGeometry(torus, true);
  20054. return torus;
  20055. };
  20056. var parseGround = function (parsedGround, scene) {
  20057. if (parseGeometry(parsedGround, scene)) {
  20058. return null; // null since geometry could be something else than a ground...
  20059. }
  20060. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20061. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20062. scene.pushGeometry(ground, true);
  20063. return ground;
  20064. };
  20065. var parsePlane = function (parsedPlane, scene) {
  20066. if (parseGeometry(parsedPlane, scene)) {
  20067. return null; // null since geometry could be something else than a plane...
  20068. }
  20069. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20070. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20071. scene.pushGeometry(plane, true);
  20072. return plane;
  20073. };
  20074. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20075. if (parseGeometry(parsedTorusKnot, scene)) {
  20076. return null; // null since geometry could be something else than a torusKnot...
  20077. }
  20078. 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);
  20079. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20080. scene.pushGeometry(torusKnot, true);
  20081. return torusKnot;
  20082. };
  20083. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20084. if (parseGeometry(parsedVertexData, scene)) {
  20085. return null; // null since geometry could be a primitive
  20086. }
  20087. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20088. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20089. if (parsedVertexData.delayLoadingFile) {
  20090. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20091. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20092. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20093. geometry._delayInfo = [];
  20094. if (parsedVertexData.hasUVs) {
  20095. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20096. }
  20097. if (parsedVertexData.hasUVs2) {
  20098. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20099. }
  20100. if (parsedVertexData.hasUVs3) {
  20101. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20102. }
  20103. if (parsedVertexData.hasUVs4) {
  20104. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20105. }
  20106. if (parsedVertexData.hasUVs5) {
  20107. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20108. }
  20109. if (parsedVertexData.hasUVs6) {
  20110. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20111. }
  20112. if (parsedVertexData.hasColors) {
  20113. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20114. }
  20115. if (parsedVertexData.hasMatricesIndices) {
  20116. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20117. }
  20118. if (parsedVertexData.hasMatricesWeights) {
  20119. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20120. }
  20121. geometry._delayLoadingFunction = importVertexData;
  20122. }
  20123. else {
  20124. importVertexData(parsedVertexData, geometry);
  20125. }
  20126. scene.pushGeometry(geometry, true);
  20127. return geometry;
  20128. };
  20129. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20130. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20131. mesh.id = parsedMesh.id;
  20132. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20133. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20134. if (parsedMesh.rotationQuaternion) {
  20135. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20136. }
  20137. else if (parsedMesh.rotation) {
  20138. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20139. }
  20140. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20141. if (parsedMesh.localMatrix) {
  20142. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20143. }
  20144. else if (parsedMesh.pivotMatrix) {
  20145. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20146. }
  20147. mesh.setEnabled(parsedMesh.isEnabled);
  20148. mesh.isVisible = parsedMesh.isVisible;
  20149. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20150. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20151. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20152. if (parsedMesh.applyFog !== undefined) {
  20153. mesh.applyFog = parsedMesh.applyFog;
  20154. }
  20155. if (parsedMesh.pickable !== undefined) {
  20156. mesh.isPickable = parsedMesh.pickable;
  20157. }
  20158. if (parsedMesh.alphaIndex !== undefined) {
  20159. mesh.alphaIndex = parsedMesh.alphaIndex;
  20160. }
  20161. mesh.receiveShadows = parsedMesh.receiveShadows;
  20162. mesh.billboardMode = parsedMesh.billboardMode;
  20163. if (parsedMesh.visibility !== undefined) {
  20164. mesh.visibility = parsedMesh.visibility;
  20165. }
  20166. mesh.checkCollisions = parsedMesh.checkCollisions;
  20167. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20168. // freezeWorldMatrix
  20169. if (parsedMesh.freezeWorldMatrix) {
  20170. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20171. }
  20172. // Parent
  20173. if (parsedMesh.parentId) {
  20174. mesh._waitingParentId = parsedMesh.parentId;
  20175. }
  20176. // Actions
  20177. if (parsedMesh.actions !== undefined) {
  20178. mesh._waitingActions = parsedMesh.actions;
  20179. }
  20180. // Geometry
  20181. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20182. if (parsedMesh.delayLoadingFile) {
  20183. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20184. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20185. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20186. if (parsedMesh._binaryInfo) {
  20187. mesh._binaryInfo = parsedMesh._binaryInfo;
  20188. }
  20189. mesh._delayInfo = [];
  20190. if (parsedMesh.hasUVs) {
  20191. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20192. }
  20193. if (parsedMesh.hasUVs2) {
  20194. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20195. }
  20196. if (parsedMesh.hasUVs3) {
  20197. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20198. }
  20199. if (parsedMesh.hasUVs4) {
  20200. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20201. }
  20202. if (parsedMesh.hasUVs5) {
  20203. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20204. }
  20205. if (parsedMesh.hasUVs6) {
  20206. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20207. }
  20208. if (parsedMesh.hasColors) {
  20209. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20210. }
  20211. if (parsedMesh.hasMatricesIndices) {
  20212. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20213. }
  20214. if (parsedMesh.hasMatricesWeights) {
  20215. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20216. }
  20217. mesh._delayLoadingFunction = importGeometry;
  20218. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20219. mesh._checkDelayState();
  20220. }
  20221. }
  20222. else {
  20223. importGeometry(parsedMesh, mesh);
  20224. }
  20225. // Material
  20226. if (parsedMesh.materialId) {
  20227. mesh.setMaterialByID(parsedMesh.materialId);
  20228. }
  20229. else {
  20230. mesh.material = null;
  20231. }
  20232. // Skeleton
  20233. if (parsedMesh.skeletonId > -1) {
  20234. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20235. }
  20236. // Physics
  20237. if (parsedMesh.physicsImpostor) {
  20238. if (!scene.isPhysicsEnabled()) {
  20239. scene.enablePhysics();
  20240. }
  20241. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20242. }
  20243. // Animations
  20244. if (parsedMesh.animations) {
  20245. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20246. var parsedAnimation = parsedMesh.animations[animationIndex];
  20247. mesh.animations.push(parseAnimation(parsedAnimation));
  20248. }
  20249. }
  20250. if (parsedMesh.autoAnimate) {
  20251. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20252. }
  20253. // Layer Mask
  20254. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20255. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20256. }
  20257. else {
  20258. mesh.layerMask = 0x0FFFFFFF;
  20259. }
  20260. // Instances
  20261. if (parsedMesh.instances) {
  20262. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20263. var parsedInstance = parsedMesh.instances[index];
  20264. var instance = mesh.createInstance(parsedInstance.name);
  20265. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20266. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20267. if (parsedInstance.rotationQuaternion) {
  20268. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20269. }
  20270. else if (parsedInstance.rotation) {
  20271. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20272. }
  20273. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20274. instance.checkCollisions = mesh.checkCollisions;
  20275. if (parsedMesh.animations) {
  20276. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20277. parsedAnimation = parsedMesh.animations[animationIndex];
  20278. instance.animations.push(parseAnimation(parsedAnimation));
  20279. }
  20280. }
  20281. }
  20282. }
  20283. return mesh;
  20284. };
  20285. var parseActions = function (parsedActions, object, scene) {
  20286. var actionManager = new BABYLON.ActionManager(scene);
  20287. if (object === null)
  20288. scene.actionManager = actionManager;
  20289. else
  20290. object.actionManager = actionManager;
  20291. // instanciate a new object
  20292. var instanciate = function (name, params) {
  20293. var newInstance = Object.create(BABYLON[name].prototype);
  20294. newInstance.constructor.apply(newInstance, params);
  20295. return newInstance;
  20296. };
  20297. var parseParameter = function (name, value, target, propertyPath) {
  20298. if (propertyPath === null) {
  20299. // String, boolean or float
  20300. var floatValue = parseFloat(value);
  20301. if (value === "true" || value === "false")
  20302. return value === "true";
  20303. else
  20304. return isNaN(floatValue) ? value : floatValue;
  20305. }
  20306. var effectiveTarget = propertyPath.split(".");
  20307. var values = value.split(",");
  20308. // Get effective Target
  20309. for (var i = 0; i < effectiveTarget.length; i++) {
  20310. target = target[effectiveTarget[i]];
  20311. }
  20312. // Return appropriate value with its type
  20313. if (typeof (target) === "boolean")
  20314. return values[0] === "true";
  20315. if (typeof (target) === "string")
  20316. return values[0];
  20317. // Parameters with multiple values such as Vector3 etc.
  20318. var split = new Array();
  20319. for (var i = 0; i < values.length; i++)
  20320. split.push(parseFloat(values[i]));
  20321. if (target instanceof BABYLON.Vector3)
  20322. return BABYLON.Vector3.FromArray(split);
  20323. if (target instanceof BABYLON.Vector4)
  20324. return BABYLON.Vector4.FromArray(split);
  20325. if (target instanceof BABYLON.Color3)
  20326. return BABYLON.Color3.FromArray(split);
  20327. if (target instanceof BABYLON.Color4)
  20328. return BABYLON.Color4.FromArray(split);
  20329. return parseFloat(values[0]);
  20330. };
  20331. // traverse graph per trigger
  20332. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20333. if (combineArray === void 0) { combineArray = null; }
  20334. if (parsedAction.detached)
  20335. return;
  20336. var parameters = new Array();
  20337. var target = null;
  20338. var propertyPath = null;
  20339. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20340. // Parameters
  20341. if (parsedAction.type === 2)
  20342. parameters.push(actionManager);
  20343. else
  20344. parameters.push(trigger);
  20345. if (combine) {
  20346. var actions = new Array();
  20347. for (var j = 0; j < parsedAction.combine.length; j++) {
  20348. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20349. }
  20350. parameters.push(actions);
  20351. }
  20352. else {
  20353. for (var i = 0; i < parsedAction.properties.length; i++) {
  20354. var value = parsedAction.properties[i].value;
  20355. var name = parsedAction.properties[i].name;
  20356. var targetType = parsedAction.properties[i].targetType;
  20357. if (name === "target")
  20358. if (targetType !== null && targetType === "SceneProperties")
  20359. value = target = scene;
  20360. else
  20361. value = target = scene.getNodeByName(value);
  20362. else if (name === "parent")
  20363. value = scene.getNodeByName(value);
  20364. else if (name === "sound")
  20365. value = scene.getSoundByName(value);
  20366. else if (name !== "propertyPath") {
  20367. if (parsedAction.type === 2 && name === "operator")
  20368. value = BABYLON.ValueCondition[value];
  20369. else
  20370. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20371. }
  20372. else {
  20373. propertyPath = value;
  20374. }
  20375. parameters.push(value);
  20376. }
  20377. }
  20378. if (combineArray === null) {
  20379. parameters.push(condition);
  20380. }
  20381. else {
  20382. parameters.push(null);
  20383. }
  20384. // If interpolate value action
  20385. if (parsedAction.name === "InterpolateValueAction") {
  20386. var param = parameters[parameters.length - 2];
  20387. parameters[parameters.length - 1] = param;
  20388. parameters[parameters.length - 2] = condition;
  20389. }
  20390. // Action or condition(s) and not CombineAction
  20391. var newAction = instanciate(parsedAction.name, parameters);
  20392. if (combineArray === null) {
  20393. if (newAction instanceof BABYLON.Condition) {
  20394. condition = newAction;
  20395. newAction = action;
  20396. }
  20397. else {
  20398. condition = null;
  20399. if (action)
  20400. action.then(newAction);
  20401. else
  20402. actionManager.registerAction(newAction);
  20403. }
  20404. }
  20405. else {
  20406. combineArray.push(newAction);
  20407. }
  20408. for (var i = 0; i < parsedAction.children.length; i++)
  20409. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20410. };
  20411. // triggers
  20412. for (var i = 0; i < parsedActions.children.length; i++) {
  20413. var triggerParams;
  20414. var trigger = parsedActions.children[i];
  20415. if (trigger.properties.length > 0) {
  20416. var param = trigger.properties[0].value;
  20417. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20418. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20419. }
  20420. else
  20421. triggerParams = BABYLON.ActionManager[trigger.name];
  20422. for (var j = 0; j < trigger.children.length; j++) {
  20423. if (!trigger.detached)
  20424. traverse(trigger.children[j], triggerParams, null, null);
  20425. }
  20426. }
  20427. };
  20428. var parseSound = function (parsedSound, scene, rootUrl) {
  20429. var soundName = parsedSound.name;
  20430. var soundUrl = rootUrl + soundName;
  20431. var options = {
  20432. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20433. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20434. rolloffFactor: parsedSound.rolloffFactor,
  20435. refDistance: parsedSound.refDistance,
  20436. distanceModel: parsedSound.distanceModel,
  20437. playbackRate: parsedSound.playbackRate
  20438. };
  20439. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20440. scene._addPendingData(newSound);
  20441. if (parsedSound.position) {
  20442. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20443. newSound.setPosition(soundPosition);
  20444. }
  20445. if (parsedSound.isDirectional) {
  20446. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20447. if (parsedSound.localDirectionToMesh) {
  20448. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20449. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20450. }
  20451. }
  20452. if (parsedSound.connectedMeshId) {
  20453. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20454. if (connectedMesh) {
  20455. newSound.attachToMesh(connectedMesh);
  20456. }
  20457. }
  20458. };
  20459. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20460. names = (names instanceof Array) ? names : [names];
  20461. for (var i in names) {
  20462. if (mesh.name === names[i]) {
  20463. hierarchyIds.push(mesh.id);
  20464. return true;
  20465. }
  20466. }
  20467. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20468. hierarchyIds.push(mesh.id);
  20469. return true;
  20470. }
  20471. return false;
  20472. };
  20473. var importVertexData = function (parsedVertexData, geometry) {
  20474. var vertexData = new BABYLON.VertexData();
  20475. // positions
  20476. var positions = parsedVertexData.positions;
  20477. if (positions) {
  20478. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20479. }
  20480. // normals
  20481. var normals = parsedVertexData.normals;
  20482. if (normals) {
  20483. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20484. }
  20485. // uvs
  20486. var uvs = parsedVertexData.uvs;
  20487. if (uvs) {
  20488. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20489. }
  20490. // uv2s
  20491. var uv2s = parsedVertexData.uv2s;
  20492. if (uv2s) {
  20493. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20494. }
  20495. // uv3s
  20496. var uv3s = parsedVertexData.uv3s;
  20497. if (uv3s) {
  20498. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20499. }
  20500. // uv4s
  20501. var uv4s = parsedVertexData.uv4s;
  20502. if (uv4s) {
  20503. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20504. }
  20505. // uv5s
  20506. var uv5s = parsedVertexData.uv5s;
  20507. if (uv5s) {
  20508. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20509. }
  20510. // uv6s
  20511. var uv6s = parsedVertexData.uv6s;
  20512. if (uv6s) {
  20513. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20514. }
  20515. // colors
  20516. var colors = parsedVertexData.colors;
  20517. if (colors) {
  20518. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20519. }
  20520. // matricesIndices
  20521. var matricesIndices = parsedVertexData.matricesIndices;
  20522. if (matricesIndices) {
  20523. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20524. }
  20525. // matricesWeights
  20526. var matricesWeights = parsedVertexData.matricesWeights;
  20527. if (matricesWeights) {
  20528. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20529. }
  20530. // indices
  20531. var indices = parsedVertexData.indices;
  20532. if (indices) {
  20533. vertexData.indices = indices;
  20534. }
  20535. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20536. };
  20537. var importGeometry = function (parsedGeometry, mesh) {
  20538. var scene = mesh.getScene();
  20539. // Geometry
  20540. var geometryId = parsedGeometry.geometryId;
  20541. if (geometryId) {
  20542. var geometry = scene.getGeometryByID(geometryId);
  20543. if (geometry) {
  20544. geometry.applyToMesh(mesh);
  20545. }
  20546. }
  20547. else if (parsedGeometry instanceof ArrayBuffer) {
  20548. var binaryInfo = mesh._binaryInfo;
  20549. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20550. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20551. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20552. }
  20553. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20554. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20555. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20556. }
  20557. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20558. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20559. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20560. }
  20561. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20562. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20563. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20564. }
  20565. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20566. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20567. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20568. }
  20569. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20570. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20571. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20572. }
  20573. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20574. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20575. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20576. }
  20577. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20578. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20579. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20580. }
  20581. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20582. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20583. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20584. }
  20585. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20586. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20587. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20588. }
  20589. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20590. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20591. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20592. }
  20593. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20594. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20595. mesh.setIndices(indicesData);
  20596. }
  20597. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20598. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20599. mesh.subMeshes = [];
  20600. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20601. var materialIndex = subMeshesData[(i * 5) + 0];
  20602. var verticesStart = subMeshesData[(i * 5) + 1];
  20603. var verticesCount = subMeshesData[(i * 5) + 2];
  20604. var indexStart = subMeshesData[(i * 5) + 3];
  20605. var indexCount = subMeshesData[(i * 5) + 4];
  20606. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20607. }
  20608. }
  20609. }
  20610. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20611. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20612. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20613. if (parsedGeometry.uvs) {
  20614. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20615. }
  20616. if (parsedGeometry.uvs2) {
  20617. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20618. }
  20619. if (parsedGeometry.uvs3) {
  20620. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20621. }
  20622. if (parsedGeometry.uvs4) {
  20623. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20624. }
  20625. if (parsedGeometry.uvs5) {
  20626. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20627. }
  20628. if (parsedGeometry.uvs6) {
  20629. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20630. }
  20631. if (parsedGeometry.colors) {
  20632. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20633. }
  20634. if (parsedGeometry.matricesIndices) {
  20635. if (!parsedGeometry.matricesIndices._isExpanded) {
  20636. var floatIndices = [];
  20637. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20638. var matricesIndex = parsedGeometry.matricesIndices[i];
  20639. floatIndices.push(matricesIndex & 0x000000FF);
  20640. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20641. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20642. floatIndices.push(matricesIndex >> 24);
  20643. }
  20644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20645. }
  20646. else {
  20647. delete parsedGeometry.matricesIndices._isExpanded;
  20648. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20649. }
  20650. }
  20651. if (parsedGeometry.matricesWeights) {
  20652. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20653. }
  20654. mesh.setIndices(parsedGeometry.indices);
  20655. }
  20656. // SubMeshes
  20657. if (parsedGeometry.subMeshes) {
  20658. mesh.subMeshes = [];
  20659. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20660. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20661. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20662. }
  20663. }
  20664. // Flat shading
  20665. if (mesh._shouldGenerateFlatShading) {
  20666. mesh.convertToFlatShadedMesh();
  20667. delete mesh._shouldGenerateFlatShading;
  20668. }
  20669. // Update
  20670. mesh.computeWorldMatrix(true);
  20671. // Octree
  20672. if (scene._selectionOctree) {
  20673. scene._selectionOctree.addMesh(mesh);
  20674. }
  20675. };
  20676. BABYLON.SceneLoader.RegisterPlugin({
  20677. extensions: ".babylon",
  20678. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20679. var parsedData = JSON.parse(data);
  20680. var loadedSkeletonsIds = [];
  20681. var loadedMaterialsIds = [];
  20682. var hierarchyIds = [];
  20683. for (var index = 0; index < parsedData.meshes.length; index++) {
  20684. var parsedMesh = parsedData.meshes[index];
  20685. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20686. if (meshesNames instanceof Array) {
  20687. // Remove found mesh name from list.
  20688. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20689. }
  20690. //Geometry?
  20691. if (parsedMesh.geometryId) {
  20692. //does the file contain geometries?
  20693. if (parsedData.geometries) {
  20694. //find the correct geometry and add it to the scene
  20695. var found = false;
  20696. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20697. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20698. return;
  20699. }
  20700. else {
  20701. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20702. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20703. switch (geometryType) {
  20704. case "boxes":
  20705. parseBox(parsedGeometryData, scene);
  20706. break;
  20707. case "spheres":
  20708. parseSphere(parsedGeometryData, scene);
  20709. break;
  20710. case "cylinders":
  20711. parseCylinder(parsedGeometryData, scene);
  20712. break;
  20713. case "toruses":
  20714. parseTorus(parsedGeometryData, scene);
  20715. break;
  20716. case "grounds":
  20717. parseGround(parsedGeometryData, scene);
  20718. break;
  20719. case "planes":
  20720. parsePlane(parsedGeometryData, scene);
  20721. break;
  20722. case "torusKnots":
  20723. parseTorusKnot(parsedGeometryData, scene);
  20724. break;
  20725. case "vertexData":
  20726. parseVertexData(parsedGeometryData, scene, rootUrl);
  20727. break;
  20728. }
  20729. found = true;
  20730. }
  20731. });
  20732. }
  20733. });
  20734. if (!found) {
  20735. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20736. }
  20737. }
  20738. }
  20739. // Material ?
  20740. if (parsedMesh.materialId) {
  20741. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20742. if (!materialFound && parsedData.multiMaterials) {
  20743. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20744. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20745. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20746. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20747. var subMatId = parsedMultiMaterial.materials[matIndex];
  20748. loadedMaterialsIds.push(subMatId);
  20749. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20750. }
  20751. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20752. parseMultiMaterial(parsedMultiMaterial, scene);
  20753. materialFound = true;
  20754. break;
  20755. }
  20756. }
  20757. }
  20758. if (!materialFound) {
  20759. loadedMaterialsIds.push(parsedMesh.materialId);
  20760. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20761. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20762. }
  20763. }
  20764. }
  20765. // Skeleton ?
  20766. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20767. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20768. if (!skeletonAlreadyLoaded) {
  20769. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20770. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20771. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20772. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20773. loadedSkeletonsIds.push(parsedSkeleton.id);
  20774. }
  20775. }
  20776. }
  20777. }
  20778. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20779. meshes.push(mesh);
  20780. }
  20781. }
  20782. // Connecting parents
  20783. for (index = 0; index < scene.meshes.length; index++) {
  20784. var currentMesh = scene.meshes[index];
  20785. if (currentMesh._waitingParentId) {
  20786. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20787. currentMesh._waitingParentId = undefined;
  20788. }
  20789. }
  20790. // freeze world matrix application
  20791. for (index = 0; index < scene.meshes.length; index++) {
  20792. var currentMesh = scene.meshes[index];
  20793. if (currentMesh._waitingFreezeWorldMatrix) {
  20794. currentMesh.freezeWorldMatrix();
  20795. currentMesh._waitingFreezeWorldMatrix = undefined;
  20796. }
  20797. }
  20798. // Particles
  20799. if (parsedData.particleSystems) {
  20800. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20801. var parsedParticleSystem = parsedData.particleSystems[index];
  20802. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20803. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20804. }
  20805. }
  20806. }
  20807. return true;
  20808. },
  20809. load: function (scene, data, rootUrl) {
  20810. var parsedData = JSON.parse(data);
  20811. // Scene
  20812. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20813. scene.autoClear = parsedData.autoClear;
  20814. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20815. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20816. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20817. // Fog
  20818. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20819. scene.fogMode = parsedData.fogMode;
  20820. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20821. scene.fogStart = parsedData.fogStart;
  20822. scene.fogEnd = parsedData.fogEnd;
  20823. scene.fogDensity = parsedData.fogDensity;
  20824. }
  20825. // Lights
  20826. for (var index = 0; index < parsedData.lights.length; index++) {
  20827. var parsedLight = parsedData.lights[index];
  20828. parseLight(parsedLight, scene);
  20829. }
  20830. // Materials
  20831. if (parsedData.materials) {
  20832. for (index = 0; index < parsedData.materials.length; index++) {
  20833. var parsedMaterial = parsedData.materials[index];
  20834. parseMaterial(parsedMaterial, scene, rootUrl);
  20835. }
  20836. }
  20837. if (parsedData.multiMaterials) {
  20838. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20839. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20840. parseMultiMaterial(parsedMultiMaterial, scene);
  20841. }
  20842. }
  20843. // Skeletons
  20844. if (parsedData.skeletons) {
  20845. for (index = 0; index < parsedData.skeletons.length; index++) {
  20846. var parsedSkeleton = parsedData.skeletons[index];
  20847. parseSkeleton(parsedSkeleton, scene);
  20848. }
  20849. }
  20850. // Geometries
  20851. var geometries = parsedData.geometries;
  20852. if (geometries) {
  20853. // Boxes
  20854. var boxes = geometries.boxes;
  20855. if (boxes) {
  20856. for (index = 0; index < boxes.length; index++) {
  20857. var parsedBox = boxes[index];
  20858. parseBox(parsedBox, scene);
  20859. }
  20860. }
  20861. // Spheres
  20862. var spheres = geometries.spheres;
  20863. if (spheres) {
  20864. for (index = 0; index < spheres.length; index++) {
  20865. var parsedSphere = spheres[index];
  20866. parseSphere(parsedSphere, scene);
  20867. }
  20868. }
  20869. // Cylinders
  20870. var cylinders = geometries.cylinders;
  20871. if (cylinders) {
  20872. for (index = 0; index < cylinders.length; index++) {
  20873. var parsedCylinder = cylinders[index];
  20874. parseCylinder(parsedCylinder, scene);
  20875. }
  20876. }
  20877. // Toruses
  20878. var toruses = geometries.toruses;
  20879. if (toruses) {
  20880. for (index = 0; index < toruses.length; index++) {
  20881. var parsedTorus = toruses[index];
  20882. parseTorus(parsedTorus, scene);
  20883. }
  20884. }
  20885. // Grounds
  20886. var grounds = geometries.grounds;
  20887. if (grounds) {
  20888. for (index = 0; index < grounds.length; index++) {
  20889. var parsedGround = grounds[index];
  20890. parseGround(parsedGround, scene);
  20891. }
  20892. }
  20893. // Planes
  20894. var planes = geometries.planes;
  20895. if (planes) {
  20896. for (index = 0; index < planes.length; index++) {
  20897. var parsedPlane = planes[index];
  20898. parsePlane(parsedPlane, scene);
  20899. }
  20900. }
  20901. // TorusKnots
  20902. var torusKnots = geometries.torusKnots;
  20903. if (torusKnots) {
  20904. for (index = 0; index < torusKnots.length; index++) {
  20905. var parsedTorusKnot = torusKnots[index];
  20906. parseTorusKnot(parsedTorusKnot, scene);
  20907. }
  20908. }
  20909. // VertexData
  20910. var vertexData = geometries.vertexData;
  20911. if (vertexData) {
  20912. for (index = 0; index < vertexData.length; index++) {
  20913. var parsedVertexData = vertexData[index];
  20914. parseVertexData(parsedVertexData, scene, rootUrl);
  20915. }
  20916. }
  20917. }
  20918. // Meshes
  20919. for (index = 0; index < parsedData.meshes.length; index++) {
  20920. var parsedMesh = parsedData.meshes[index];
  20921. parseMesh(parsedMesh, scene, rootUrl);
  20922. }
  20923. // Cameras
  20924. for (index = 0; index < parsedData.cameras.length; index++) {
  20925. var parsedCamera = parsedData.cameras[index];
  20926. parseCamera(parsedCamera, scene);
  20927. }
  20928. if (parsedData.activeCameraID) {
  20929. scene.setActiveCameraByID(parsedData.activeCameraID);
  20930. }
  20931. // Browsing all the graph to connect the dots
  20932. for (index = 0; index < scene.cameras.length; index++) {
  20933. var camera = scene.cameras[index];
  20934. if (camera._waitingParentId) {
  20935. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20936. camera._waitingParentId = undefined;
  20937. }
  20938. }
  20939. for (index = 0; index < scene.lights.length; index++) {
  20940. var light = scene.lights[index];
  20941. if (light._waitingParentId) {
  20942. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20943. light._waitingParentId = undefined;
  20944. }
  20945. }
  20946. // Sounds
  20947. if (parsedData.sounds) {
  20948. for (index = 0; index < parsedData.sounds.length; index++) {
  20949. var parsedSound = parsedData.sounds[index];
  20950. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20951. parseSound(parsedSound, scene, rootUrl);
  20952. }
  20953. else {
  20954. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20955. }
  20956. }
  20957. }
  20958. // Connect parents & children and parse actions
  20959. for (index = 0; index < scene.meshes.length; index++) {
  20960. var mesh = scene.meshes[index];
  20961. if (mesh._waitingParentId) {
  20962. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20963. mesh._waitingParentId = undefined;
  20964. }
  20965. if (mesh._waitingActions) {
  20966. parseActions(mesh._waitingActions, mesh, scene);
  20967. mesh._waitingActions = undefined;
  20968. }
  20969. }
  20970. // freeze world matrix application
  20971. for (index = 0; index < scene.meshes.length; index++) {
  20972. var currentMesh = scene.meshes[index];
  20973. if (currentMesh._waitingFreezeWorldMatrix) {
  20974. currentMesh.freezeWorldMatrix();
  20975. currentMesh._waitingFreezeWorldMatrix = undefined;
  20976. }
  20977. }
  20978. // Particles Systems
  20979. if (parsedData.particleSystems) {
  20980. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20981. var parsedParticleSystem = parsedData.particleSystems[index];
  20982. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20983. }
  20984. }
  20985. // Lens flares
  20986. if (parsedData.lensFlareSystems) {
  20987. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20988. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20989. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20990. }
  20991. }
  20992. // Shadows
  20993. if (parsedData.shadowGenerators) {
  20994. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20995. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20996. parseShadowGenerator(parsedShadowGenerator, scene);
  20997. }
  20998. }
  20999. // Actions (scene)
  21000. if (parsedData.actions) {
  21001. parseActions(parsedData.actions, null, scene);
  21002. }
  21003. // Finish
  21004. return true;
  21005. }
  21006. });
  21007. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21008. })(BABYLON || (BABYLON = {}));
  21009. var BABYLON;
  21010. (function (BABYLON) {
  21011. var SpriteManager = (function () {
  21012. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21014. this.name = name;
  21015. this.cellSize = cellSize;
  21016. this.sprites = new Array();
  21017. this.renderingGroupId = 0;
  21018. this.layerMask = 0x0FFFFFFF;
  21019. this.fogEnabled = true;
  21020. this._vertexDeclaration = [4, 4, 4, 4];
  21021. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21022. this._capacity = capacity;
  21023. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21024. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21025. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21026. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21027. this._scene = scene;
  21028. this._scene.spriteManagers.push(this);
  21029. // VBO
  21030. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21031. var indices = [];
  21032. var index = 0;
  21033. for (var count = 0; count < capacity; count++) {
  21034. indices.push(index);
  21035. indices.push(index + 1);
  21036. indices.push(index + 2);
  21037. indices.push(index);
  21038. indices.push(index + 2);
  21039. indices.push(index + 3);
  21040. index += 4;
  21041. }
  21042. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21043. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21044. // Effects
  21045. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21046. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21047. }
  21048. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21049. var arrayOffset = index * 16;
  21050. if (offsetX === 0)
  21051. offsetX = this._epsilon;
  21052. else if (offsetX === 1)
  21053. offsetX = 1 - this._epsilon;
  21054. if (offsetY === 0)
  21055. offsetY = this._epsilon;
  21056. else if (offsetY === 1)
  21057. offsetY = 1 - this._epsilon;
  21058. this._vertices[arrayOffset] = sprite.position.x;
  21059. this._vertices[arrayOffset + 1] = sprite.position.y;
  21060. this._vertices[arrayOffset + 2] = sprite.position.z;
  21061. this._vertices[arrayOffset + 3] = sprite.angle;
  21062. this._vertices[arrayOffset + 4] = sprite.width;
  21063. this._vertices[arrayOffset + 5] = sprite.height;
  21064. this._vertices[arrayOffset + 6] = offsetX;
  21065. this._vertices[arrayOffset + 7] = offsetY;
  21066. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21067. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21068. var offset = (sprite.cellIndex / rowSize) >> 0;
  21069. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21070. this._vertices[arrayOffset + 11] = offset;
  21071. // Color
  21072. this._vertices[arrayOffset + 12] = sprite.color.r;
  21073. this._vertices[arrayOffset + 13] = sprite.color.g;
  21074. this._vertices[arrayOffset + 14] = sprite.color.b;
  21075. this._vertices[arrayOffset + 15] = sprite.color.a;
  21076. };
  21077. SpriteManager.prototype.render = function () {
  21078. // Check
  21079. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21080. return;
  21081. var engine = this._scene.getEngine();
  21082. var baseSize = this._spriteTexture.getBaseSize();
  21083. // Sprites
  21084. var deltaTime = engine.getDeltaTime();
  21085. var max = Math.min(this._capacity, this.sprites.length);
  21086. var rowSize = baseSize.width / this.cellSize;
  21087. var offset = 0;
  21088. for (var index = 0; index < max; index++) {
  21089. var sprite = this.sprites[index];
  21090. if (!sprite) {
  21091. continue;
  21092. }
  21093. sprite._animate(deltaTime);
  21094. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21095. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21096. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21097. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21098. }
  21099. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21100. // Render
  21101. var effect = this._effectBase;
  21102. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21103. effect = this._effectFog;
  21104. }
  21105. engine.enableEffect(effect);
  21106. var viewMatrix = this._scene.getViewMatrix();
  21107. effect.setTexture("diffuseSampler", this._spriteTexture);
  21108. effect.setMatrix("view", viewMatrix);
  21109. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21110. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21111. // Fog
  21112. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21113. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21114. effect.setColor3("vFogColor", this._scene.fogColor);
  21115. }
  21116. // VBOs
  21117. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21118. // Draw order
  21119. engine.setDepthFunctionToLessOrEqual();
  21120. effect.setBool("alphaTest", true);
  21121. engine.setColorWrite(false);
  21122. engine.draw(true, 0, max * 6);
  21123. engine.setColorWrite(true);
  21124. effect.setBool("alphaTest", false);
  21125. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21126. engine.draw(true, 0, max * 6);
  21127. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21128. };
  21129. SpriteManager.prototype.dispose = function () {
  21130. if (this._vertexBuffer) {
  21131. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21132. this._vertexBuffer = null;
  21133. }
  21134. if (this._indexBuffer) {
  21135. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21136. this._indexBuffer = null;
  21137. }
  21138. if (this._spriteTexture) {
  21139. this._spriteTexture.dispose();
  21140. this._spriteTexture = null;
  21141. }
  21142. // Remove from scene
  21143. var index = this._scene.spriteManagers.indexOf(this);
  21144. this._scene.spriteManagers.splice(index, 1);
  21145. // Callback
  21146. if (this.onDispose) {
  21147. this.onDispose();
  21148. }
  21149. };
  21150. return SpriteManager;
  21151. })();
  21152. BABYLON.SpriteManager = SpriteManager;
  21153. })(BABYLON || (BABYLON = {}));
  21154. var BABYLON;
  21155. (function (BABYLON) {
  21156. var Sprite = (function () {
  21157. function Sprite(name, manager) {
  21158. this.name = name;
  21159. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21160. this.width = 1.0;
  21161. this.height = 1.0;
  21162. this.angle = 0;
  21163. this.cellIndex = 0;
  21164. this.invertU = 0;
  21165. this.invertV = 0;
  21166. this.animations = new Array();
  21167. this._animationStarted = false;
  21168. this._loopAnimation = false;
  21169. this._fromIndex = 0;
  21170. this._toIndex = 0;
  21171. this._delay = 0;
  21172. this._direction = 1;
  21173. this._frameCount = 0;
  21174. this._time = 0;
  21175. this._manager = manager;
  21176. this._manager.sprites.push(this);
  21177. this.position = BABYLON.Vector3.Zero();
  21178. }
  21179. Object.defineProperty(Sprite.prototype, "size", {
  21180. get: function () {
  21181. return this.width;
  21182. },
  21183. set: function (value) {
  21184. this.width = value;
  21185. this.height = value;
  21186. },
  21187. enumerable: true,
  21188. configurable: true
  21189. });
  21190. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21191. this._fromIndex = from;
  21192. this._toIndex = to;
  21193. this._loopAnimation = loop;
  21194. this._delay = delay;
  21195. this._animationStarted = true;
  21196. this._direction = from < to ? 1 : -1;
  21197. this.cellIndex = from;
  21198. this._time = 0;
  21199. };
  21200. Sprite.prototype.stopAnimation = function () {
  21201. this._animationStarted = false;
  21202. };
  21203. Sprite.prototype._animate = function (deltaTime) {
  21204. if (!this._animationStarted)
  21205. return;
  21206. this._time += deltaTime;
  21207. if (this._time > this._delay) {
  21208. this._time = this._time % this._delay;
  21209. this.cellIndex += this._direction;
  21210. if (this.cellIndex == this._toIndex) {
  21211. if (this._loopAnimation) {
  21212. this.cellIndex = this._fromIndex;
  21213. }
  21214. else {
  21215. this._animationStarted = false;
  21216. if (this.disposeWhenFinishedAnimating) {
  21217. this.dispose();
  21218. }
  21219. }
  21220. }
  21221. }
  21222. };
  21223. Sprite.prototype.dispose = function () {
  21224. for (var i = 0; i < this._manager.sprites.length; i++) {
  21225. if (this._manager.sprites[i] == this) {
  21226. this._manager.sprites.splice(i, 1);
  21227. }
  21228. }
  21229. };
  21230. return Sprite;
  21231. })();
  21232. BABYLON.Sprite = Sprite;
  21233. })(BABYLON || (BABYLON = {}));
  21234. var BABYLON;
  21235. (function (BABYLON) {
  21236. var Layer = (function () {
  21237. function Layer(name, imgUrl, scene, isBackground, color) {
  21238. this.name = name;
  21239. this._vertexDeclaration = [2];
  21240. this._vertexStrideSize = 2 * 4;
  21241. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21242. this.isBackground = isBackground === undefined ? true : isBackground;
  21243. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21244. this._scene = scene;
  21245. this._scene.layers.push(this);
  21246. // VBO
  21247. var vertices = [];
  21248. vertices.push(1, 1);
  21249. vertices.push(-1, 1);
  21250. vertices.push(-1, -1);
  21251. vertices.push(1, -1);
  21252. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21253. // Indices
  21254. var indices = [];
  21255. indices.push(0);
  21256. indices.push(1);
  21257. indices.push(2);
  21258. indices.push(0);
  21259. indices.push(2);
  21260. indices.push(3);
  21261. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21262. // Effects
  21263. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21264. }
  21265. Layer.prototype.render = function () {
  21266. // Check
  21267. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21268. return;
  21269. var engine = this._scene.getEngine();
  21270. // Render
  21271. engine.enableEffect(this._effect);
  21272. engine.setState(false);
  21273. // Texture
  21274. this._effect.setTexture("textureSampler", this.texture);
  21275. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21276. // Color
  21277. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21278. // VBOs
  21279. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21280. // Draw order
  21281. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21282. engine.draw(true, 0, 6);
  21283. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21284. };
  21285. Layer.prototype.dispose = function () {
  21286. if (this._vertexBuffer) {
  21287. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21288. this._vertexBuffer = null;
  21289. }
  21290. if (this._indexBuffer) {
  21291. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21292. this._indexBuffer = null;
  21293. }
  21294. if (this.texture) {
  21295. this.texture.dispose();
  21296. this.texture = null;
  21297. }
  21298. // Remove from scene
  21299. var index = this._scene.layers.indexOf(this);
  21300. this._scene.layers.splice(index, 1);
  21301. // Callback
  21302. if (this.onDispose) {
  21303. this.onDispose();
  21304. }
  21305. };
  21306. return Layer;
  21307. })();
  21308. BABYLON.Layer = Layer;
  21309. })(BABYLON || (BABYLON = {}));
  21310. var BABYLON;
  21311. (function (BABYLON) {
  21312. var Particle = (function () {
  21313. function Particle() {
  21314. this.position = BABYLON.Vector3.Zero();
  21315. this.direction = BABYLON.Vector3.Zero();
  21316. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21317. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21318. this.lifeTime = 1.0;
  21319. this.age = 0;
  21320. this.size = 0;
  21321. this.angle = 0;
  21322. this.angularSpeed = 0;
  21323. }
  21324. Particle.prototype.copyTo = function (other) {
  21325. other.position.copyFrom(this.position);
  21326. other.direction.copyFrom(this.direction);
  21327. other.color.copyFrom(this.color);
  21328. other.colorStep.copyFrom(this.colorStep);
  21329. other.lifeTime = this.lifeTime;
  21330. other.age = this.age;
  21331. other.size = this.size;
  21332. other.angle = this.angle;
  21333. other.angularSpeed = this.angularSpeed;
  21334. };
  21335. return Particle;
  21336. })();
  21337. BABYLON.Particle = Particle;
  21338. })(BABYLON || (BABYLON = {}));
  21339. var BABYLON;
  21340. (function (BABYLON) {
  21341. var randomNumber = function (min, max) {
  21342. if (min === max) {
  21343. return (min);
  21344. }
  21345. var random = Math.random();
  21346. return ((random * (max - min)) + min);
  21347. };
  21348. var ParticleSystem = (function () {
  21349. function ParticleSystem(name, capacity, scene, customEffect) {
  21350. var _this = this;
  21351. this.name = name;
  21352. this.renderingGroupId = 0;
  21353. this.emitter = null;
  21354. this.emitRate = 10;
  21355. this.manualEmitCount = -1;
  21356. this.updateSpeed = 0.01;
  21357. this.targetStopDuration = 0;
  21358. this.disposeOnStop = false;
  21359. this.minEmitPower = 1;
  21360. this.maxEmitPower = 1;
  21361. this.minLifeTime = 1;
  21362. this.maxLifeTime = 1;
  21363. this.minSize = 1;
  21364. this.maxSize = 1;
  21365. this.minAngularSpeed = 0;
  21366. this.maxAngularSpeed = 0;
  21367. this.layerMask = 0x0FFFFFFF;
  21368. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21369. this.forceDepthWrite = false;
  21370. this.gravity = BABYLON.Vector3.Zero();
  21371. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21372. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21373. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21374. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21375. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21376. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21377. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21378. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21379. this.particles = new Array();
  21380. this._vertexDeclaration = [3, 4, 4];
  21381. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21382. this._stockParticles = new Array();
  21383. this._newPartsExcess = 0;
  21384. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21385. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21386. this._scaledDirection = BABYLON.Vector3.Zero();
  21387. this._scaledGravity = BABYLON.Vector3.Zero();
  21388. this._currentRenderId = -1;
  21389. this._started = false;
  21390. this._stopped = false;
  21391. this._actualFrame = 0;
  21392. this.id = name;
  21393. this._capacity = capacity;
  21394. this._scene = scene;
  21395. this._customEffect = customEffect;
  21396. scene.particleSystems.push(this);
  21397. // VBO
  21398. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21399. var indices = [];
  21400. var index = 0;
  21401. for (var count = 0; count < capacity; count++) {
  21402. indices.push(index);
  21403. indices.push(index + 1);
  21404. indices.push(index + 2);
  21405. indices.push(index);
  21406. indices.push(index + 2);
  21407. indices.push(index + 3);
  21408. index += 4;
  21409. }
  21410. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21411. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21412. // Default behaviors
  21413. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21414. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21415. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21416. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21417. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21418. };
  21419. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21420. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21421. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21422. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21423. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21424. };
  21425. this.updateFunction = function (particles) {
  21426. for (var index = 0; index < particles.length; index++) {
  21427. var particle = particles[index];
  21428. particle.age += _this._scaledUpdateSpeed;
  21429. if (particle.age >= particle.lifeTime) {
  21430. _this.recycleParticle(particle);
  21431. index--;
  21432. continue;
  21433. }
  21434. else {
  21435. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21436. particle.color.addInPlace(_this._scaledColorStep);
  21437. if (particle.color.a < 0)
  21438. particle.color.a = 0;
  21439. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21440. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21441. particle.position.addInPlace(_this._scaledDirection);
  21442. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21443. particle.direction.addInPlace(_this._scaledGravity);
  21444. }
  21445. }
  21446. };
  21447. }
  21448. ParticleSystem.prototype.recycleParticle = function (particle) {
  21449. var lastParticle = this.particles.pop();
  21450. if (lastParticle !== particle) {
  21451. lastParticle.copyTo(particle);
  21452. this._stockParticles.push(lastParticle);
  21453. }
  21454. };
  21455. ParticleSystem.prototype.getCapacity = function () {
  21456. return this._capacity;
  21457. };
  21458. ParticleSystem.prototype.isAlive = function () {
  21459. return this._alive;
  21460. };
  21461. ParticleSystem.prototype.isStarted = function () {
  21462. return this._started;
  21463. };
  21464. ParticleSystem.prototype.start = function () {
  21465. this._started = true;
  21466. this._stopped = false;
  21467. this._actualFrame = 0;
  21468. };
  21469. ParticleSystem.prototype.stop = function () {
  21470. this._stopped = true;
  21471. };
  21472. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21473. var offset = index * 11;
  21474. this._vertices[offset] = particle.position.x;
  21475. this._vertices[offset + 1] = particle.position.y;
  21476. this._vertices[offset + 2] = particle.position.z;
  21477. this._vertices[offset + 3] = particle.color.r;
  21478. this._vertices[offset + 4] = particle.color.g;
  21479. this._vertices[offset + 5] = particle.color.b;
  21480. this._vertices[offset + 6] = particle.color.a;
  21481. this._vertices[offset + 7] = particle.angle;
  21482. this._vertices[offset + 8] = particle.size;
  21483. this._vertices[offset + 9] = offsetX;
  21484. this._vertices[offset + 10] = offsetY;
  21485. };
  21486. ParticleSystem.prototype._update = function (newParticles) {
  21487. // Update current
  21488. this._alive = this.particles.length > 0;
  21489. this.updateFunction(this.particles);
  21490. // Add new ones
  21491. var worldMatrix;
  21492. if (this.emitter.position) {
  21493. worldMatrix = this.emitter.getWorldMatrix();
  21494. }
  21495. else {
  21496. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21497. }
  21498. for (var index = 0; index < newParticles; index++) {
  21499. if (this.particles.length === this._capacity) {
  21500. break;
  21501. }
  21502. if (this._stockParticles.length !== 0) {
  21503. var particle = this._stockParticles.pop();
  21504. particle.age = 0;
  21505. }
  21506. else {
  21507. particle = new BABYLON.Particle();
  21508. }
  21509. this.particles.push(particle);
  21510. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21511. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21512. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21513. particle.size = randomNumber(this.minSize, this.maxSize);
  21514. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21515. this.startPositionFunction(worldMatrix, particle.position);
  21516. var step = randomNumber(0, 1.0);
  21517. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21518. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21519. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21520. }
  21521. };
  21522. ParticleSystem.prototype._getEffect = function () {
  21523. if (this._customEffect) {
  21524. return this._customEffect;
  21525. }
  21526. ;
  21527. var defines = [];
  21528. if (this._scene.clipPlane) {
  21529. defines.push("#define CLIPPLANE");
  21530. }
  21531. // Effect
  21532. var join = defines.join("\n");
  21533. if (this._cachedDefines !== join) {
  21534. this._cachedDefines = join;
  21535. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21536. }
  21537. return this._effect;
  21538. };
  21539. ParticleSystem.prototype.animate = function () {
  21540. if (!this._started)
  21541. return;
  21542. var effect = this._getEffect();
  21543. // Check
  21544. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21545. return;
  21546. if (this._currentRenderId === this._scene.getRenderId()) {
  21547. return;
  21548. }
  21549. this._currentRenderId = this._scene.getRenderId();
  21550. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21551. // determine the number of particles we need to create
  21552. var emitCout;
  21553. if (this.manualEmitCount > -1) {
  21554. emitCout = this.manualEmitCount;
  21555. this.manualEmitCount = 0;
  21556. }
  21557. else {
  21558. emitCout = this.emitRate;
  21559. }
  21560. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21561. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21562. if (this._newPartsExcess > 1.0) {
  21563. newParticles += this._newPartsExcess >> 0;
  21564. this._newPartsExcess -= this._newPartsExcess >> 0;
  21565. }
  21566. this._alive = false;
  21567. if (!this._stopped) {
  21568. this._actualFrame += this._scaledUpdateSpeed;
  21569. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21570. this.stop();
  21571. }
  21572. else {
  21573. newParticles = 0;
  21574. }
  21575. this._update(newParticles);
  21576. // Stopped?
  21577. if (this._stopped) {
  21578. if (!this._alive) {
  21579. this._started = false;
  21580. if (this.disposeOnStop) {
  21581. this._scene._toBeDisposed.push(this);
  21582. }
  21583. }
  21584. }
  21585. // Update VBO
  21586. var offset = 0;
  21587. for (var index = 0; index < this.particles.length; index++) {
  21588. var particle = this.particles[index];
  21589. this._appendParticleVertex(offset++, particle, 0, 0);
  21590. this._appendParticleVertex(offset++, particle, 1, 0);
  21591. this._appendParticleVertex(offset++, particle, 1, 1);
  21592. this._appendParticleVertex(offset++, particle, 0, 1);
  21593. }
  21594. var engine = this._scene.getEngine();
  21595. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21596. };
  21597. ParticleSystem.prototype.render = function () {
  21598. var effect = this._getEffect();
  21599. // Check
  21600. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21601. return 0;
  21602. var engine = this._scene.getEngine();
  21603. // Render
  21604. engine.enableEffect(effect);
  21605. engine.setState(false);
  21606. var viewMatrix = this._scene.getViewMatrix();
  21607. effect.setTexture("diffuseSampler", this.particleTexture);
  21608. effect.setMatrix("view", viewMatrix);
  21609. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21610. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21611. if (this._scene.clipPlane) {
  21612. var clipPlane = this._scene.clipPlane;
  21613. var invView = viewMatrix.clone();
  21614. invView.invert();
  21615. effect.setMatrix("invView", invView);
  21616. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21617. }
  21618. // VBOs
  21619. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21620. // Draw order
  21621. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21622. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21623. }
  21624. else {
  21625. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21626. }
  21627. if (this.forceDepthWrite) {
  21628. engine.setDepthWrite(true);
  21629. }
  21630. engine.draw(true, 0, this.particles.length * 6);
  21631. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21632. return this.particles.length;
  21633. };
  21634. ParticleSystem.prototype.dispose = function () {
  21635. if (this._vertexBuffer) {
  21636. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21637. this._vertexBuffer = null;
  21638. }
  21639. if (this._indexBuffer) {
  21640. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21641. this._indexBuffer = null;
  21642. }
  21643. if (this.particleTexture) {
  21644. this.particleTexture.dispose();
  21645. this.particleTexture = null;
  21646. }
  21647. // Remove from scene
  21648. var index = this._scene.particleSystems.indexOf(this);
  21649. this._scene.particleSystems.splice(index, 1);
  21650. // Callback
  21651. if (this.onDispose) {
  21652. this.onDispose();
  21653. }
  21654. };
  21655. // Clone
  21656. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21657. var result = new ParticleSystem(name, this._capacity, this._scene);
  21658. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21659. if (newEmitter === undefined) {
  21660. newEmitter = this.emitter;
  21661. }
  21662. result.emitter = newEmitter;
  21663. if (this.particleTexture) {
  21664. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21665. }
  21666. result.start();
  21667. return result;
  21668. };
  21669. // Statics
  21670. ParticleSystem.BLENDMODE_ONEONE = 0;
  21671. ParticleSystem.BLENDMODE_STANDARD = 1;
  21672. return ParticleSystem;
  21673. })();
  21674. BABYLON.ParticleSystem = ParticleSystem;
  21675. })(BABYLON || (BABYLON = {}));
  21676. var BABYLON;
  21677. (function (BABYLON) {
  21678. var Animation = (function () {
  21679. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21680. this.name = name;
  21681. this.targetProperty = targetProperty;
  21682. this.framePerSecond = framePerSecond;
  21683. this.dataType = dataType;
  21684. this.loopMode = loopMode;
  21685. this._offsetsCache = {};
  21686. this._highLimitsCache = {};
  21687. this._stopped = false;
  21688. this.allowMatricesInterpolation = false;
  21689. this.targetPropertyPath = targetProperty.split(".");
  21690. this.dataType = dataType;
  21691. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21692. }
  21693. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21694. var dataType = undefined;
  21695. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21696. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21697. }
  21698. else if (from instanceof BABYLON.Quaternion) {
  21699. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21700. }
  21701. else if (from instanceof BABYLON.Vector3) {
  21702. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21703. }
  21704. else if (from instanceof BABYLON.Vector2) {
  21705. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21706. }
  21707. else if (from instanceof BABYLON.Color3) {
  21708. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21709. }
  21710. if (dataType == undefined) {
  21711. return null;
  21712. }
  21713. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21714. var keys = [];
  21715. keys.push({ frame: 0, value: from });
  21716. keys.push({ frame: totalFrame, value: to });
  21717. animation.setKeys(keys);
  21718. if (easingFunction !== undefined) {
  21719. animation.setEasingFunction(easingFunction);
  21720. }
  21721. mesh.animations.push(animation);
  21722. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21723. };
  21724. // Methods
  21725. Animation.prototype.reset = function () {
  21726. this._offsetsCache = {};
  21727. this._highLimitsCache = {};
  21728. this.currentFrame = 0;
  21729. };
  21730. Animation.prototype.isStopped = function () {
  21731. return this._stopped;
  21732. };
  21733. Animation.prototype.getKeys = function () {
  21734. return this._keys;
  21735. };
  21736. Animation.prototype.getEasingFunction = function () {
  21737. return this._easingFunction;
  21738. };
  21739. Animation.prototype.setEasingFunction = function (easingFunction) {
  21740. this._easingFunction = easingFunction;
  21741. };
  21742. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21743. return startValue + (endValue - startValue) * gradient;
  21744. };
  21745. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21746. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21747. };
  21748. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21749. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21750. };
  21751. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21752. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21753. };
  21754. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21755. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21756. };
  21757. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21758. var startScale = new BABYLON.Vector3(0, 0, 0);
  21759. var startRotation = new BABYLON.Quaternion();
  21760. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21761. startValue.decompose(startScale, startRotation, startTranslation);
  21762. var endScale = new BABYLON.Vector3(0, 0, 0);
  21763. var endRotation = new BABYLON.Quaternion();
  21764. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21765. endValue.decompose(endScale, endRotation, endTranslation);
  21766. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21767. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21768. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21769. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21770. return result;
  21771. };
  21772. Animation.prototype.clone = function () {
  21773. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21774. clone.setKeys(this._keys);
  21775. return clone;
  21776. };
  21777. Animation.prototype.setKeys = function (values) {
  21778. this._keys = values.slice(0);
  21779. this._offsetsCache = {};
  21780. this._highLimitsCache = {};
  21781. };
  21782. Animation.prototype._getKeyValue = function (value) {
  21783. if (typeof value === "function") {
  21784. return value();
  21785. }
  21786. return value;
  21787. };
  21788. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21789. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21790. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21791. }
  21792. this.currentFrame = currentFrame;
  21793. // Try to get a hash to find the right key
  21794. 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));
  21795. if (this._keys[startKey].frame >= currentFrame) {
  21796. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21797. startKey--;
  21798. }
  21799. }
  21800. for (var key = startKey; key < this._keys.length; key++) {
  21801. if (this._keys[key + 1].frame >= currentFrame) {
  21802. var startValue = this._getKeyValue(this._keys[key].value);
  21803. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21804. // gradient : percent of currentFrame between the frame inf and the frame sup
  21805. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21806. // check for easingFunction and correction of gradient
  21807. if (this._easingFunction != null) {
  21808. gradient = this._easingFunction.ease(gradient);
  21809. }
  21810. switch (this.dataType) {
  21811. // Float
  21812. case Animation.ANIMATIONTYPE_FLOAT:
  21813. switch (loopMode) {
  21814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21816. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21818. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21819. }
  21820. break;
  21821. // Quaternion
  21822. case Animation.ANIMATIONTYPE_QUATERNION:
  21823. var quaternion = null;
  21824. switch (loopMode) {
  21825. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21826. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21827. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21828. break;
  21829. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21830. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21831. break;
  21832. }
  21833. return quaternion;
  21834. // Vector3
  21835. case Animation.ANIMATIONTYPE_VECTOR3:
  21836. switch (loopMode) {
  21837. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21838. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21839. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21840. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21841. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21842. }
  21843. // Vector2
  21844. case Animation.ANIMATIONTYPE_VECTOR2:
  21845. switch (loopMode) {
  21846. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21847. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21848. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21849. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21850. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21851. }
  21852. // Color3
  21853. case Animation.ANIMATIONTYPE_COLOR3:
  21854. switch (loopMode) {
  21855. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21856. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21857. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21858. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21859. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21860. }
  21861. // Matrix
  21862. case Animation.ANIMATIONTYPE_MATRIX:
  21863. switch (loopMode) {
  21864. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21865. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21866. if (this.allowMatricesInterpolation) {
  21867. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21868. }
  21869. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21870. return startValue;
  21871. }
  21872. default:
  21873. break;
  21874. }
  21875. break;
  21876. }
  21877. }
  21878. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21879. };
  21880. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21881. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21882. this._stopped = true;
  21883. return false;
  21884. }
  21885. var returnValue = true;
  21886. // Adding a start key at frame 0 if missing
  21887. if (this._keys[0].frame !== 0) {
  21888. var newKey = { frame: 0, value: this._keys[0].value };
  21889. this._keys.splice(0, 0, newKey);
  21890. }
  21891. // Check limits
  21892. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21893. from = this._keys[0].frame;
  21894. }
  21895. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21896. to = this._keys[this._keys.length - 1].frame;
  21897. }
  21898. // Compute ratio
  21899. var range = to - from;
  21900. var offsetValue;
  21901. // ratio represents the frame delta between from and to
  21902. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21903. var highLimitValue = 0;
  21904. if (ratio > range && !loop) {
  21905. returnValue = false;
  21906. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21907. }
  21908. else {
  21909. // Get max value if required
  21910. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21911. var keyOffset = to.toString() + from.toString();
  21912. if (!this._offsetsCache[keyOffset]) {
  21913. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21914. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21915. switch (this.dataType) {
  21916. // Float
  21917. case Animation.ANIMATIONTYPE_FLOAT:
  21918. this._offsetsCache[keyOffset] = toValue - fromValue;
  21919. break;
  21920. // Quaternion
  21921. case Animation.ANIMATIONTYPE_QUATERNION:
  21922. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21923. break;
  21924. // Vector3
  21925. case Animation.ANIMATIONTYPE_VECTOR3:
  21926. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21927. // Vector2
  21928. case Animation.ANIMATIONTYPE_VECTOR2:
  21929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21930. // Color3
  21931. case Animation.ANIMATIONTYPE_COLOR3:
  21932. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21933. default:
  21934. break;
  21935. }
  21936. this._highLimitsCache[keyOffset] = toValue;
  21937. }
  21938. highLimitValue = this._highLimitsCache[keyOffset];
  21939. offsetValue = this._offsetsCache[keyOffset];
  21940. }
  21941. }
  21942. if (offsetValue === undefined) {
  21943. switch (this.dataType) {
  21944. // Float
  21945. case Animation.ANIMATIONTYPE_FLOAT:
  21946. offsetValue = 0;
  21947. break;
  21948. // Quaternion
  21949. case Animation.ANIMATIONTYPE_QUATERNION:
  21950. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21951. break;
  21952. // Vector3
  21953. case Animation.ANIMATIONTYPE_VECTOR3:
  21954. offsetValue = BABYLON.Vector3.Zero();
  21955. break;
  21956. // Vector2
  21957. case Animation.ANIMATIONTYPE_VECTOR2:
  21958. offsetValue = BABYLON.Vector2.Zero();
  21959. break;
  21960. // Color3
  21961. case Animation.ANIMATIONTYPE_COLOR3:
  21962. offsetValue = BABYLON.Color3.Black();
  21963. }
  21964. }
  21965. // Compute value
  21966. var repeatCount = (ratio / range) >> 0;
  21967. var currentFrame = returnValue ? from + ratio % range : to;
  21968. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21969. // Set value
  21970. if (this.targetPropertyPath.length > 1) {
  21971. var property = this._target[this.targetPropertyPath[0]];
  21972. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21973. property = property[this.targetPropertyPath[index]];
  21974. }
  21975. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21976. }
  21977. else {
  21978. this._target[this.targetPropertyPath[0]] = currentValue;
  21979. }
  21980. if (this._target.markAsDirty) {
  21981. this._target.markAsDirty(this.targetProperty);
  21982. }
  21983. if (!returnValue) {
  21984. this._stopped = true;
  21985. }
  21986. return returnValue;
  21987. };
  21988. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21989. get: function () {
  21990. return Animation._ANIMATIONTYPE_FLOAT;
  21991. },
  21992. enumerable: true,
  21993. configurable: true
  21994. });
  21995. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21996. get: function () {
  21997. return Animation._ANIMATIONTYPE_VECTOR3;
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22003. get: function () {
  22004. return Animation._ANIMATIONTYPE_VECTOR2;
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22010. get: function () {
  22011. return Animation._ANIMATIONTYPE_QUATERNION;
  22012. },
  22013. enumerable: true,
  22014. configurable: true
  22015. });
  22016. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22017. get: function () {
  22018. return Animation._ANIMATIONTYPE_MATRIX;
  22019. },
  22020. enumerable: true,
  22021. configurable: true
  22022. });
  22023. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22024. get: function () {
  22025. return Animation._ANIMATIONTYPE_COLOR3;
  22026. },
  22027. enumerable: true,
  22028. configurable: true
  22029. });
  22030. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22031. get: function () {
  22032. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22033. },
  22034. enumerable: true,
  22035. configurable: true
  22036. });
  22037. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22038. get: function () {
  22039. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22045. get: function () {
  22046. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22047. },
  22048. enumerable: true,
  22049. configurable: true
  22050. });
  22051. // Statics
  22052. Animation._ANIMATIONTYPE_FLOAT = 0;
  22053. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22054. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22055. Animation._ANIMATIONTYPE_MATRIX = 3;
  22056. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22057. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22058. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22059. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22060. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22061. return Animation;
  22062. })();
  22063. BABYLON.Animation = Animation;
  22064. })(BABYLON || (BABYLON = {}));
  22065. var BABYLON;
  22066. (function (BABYLON) {
  22067. var Animatable = (function () {
  22068. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22069. if (fromFrame === void 0) { fromFrame = 0; }
  22070. if (toFrame === void 0) { toFrame = 100; }
  22071. if (loopAnimation === void 0) { loopAnimation = false; }
  22072. if (speedRatio === void 0) { speedRatio = 1.0; }
  22073. this.target = target;
  22074. this.fromFrame = fromFrame;
  22075. this.toFrame = toFrame;
  22076. this.loopAnimation = loopAnimation;
  22077. this.speedRatio = speedRatio;
  22078. this.onAnimationEnd = onAnimationEnd;
  22079. this._animations = new Array();
  22080. this._paused = false;
  22081. this.animationStarted = false;
  22082. if (animations) {
  22083. this.appendAnimations(target, animations);
  22084. }
  22085. this._scene = scene;
  22086. scene._activeAnimatables.push(this);
  22087. }
  22088. // Methods
  22089. Animatable.prototype.appendAnimations = function (target, animations) {
  22090. for (var index = 0; index < animations.length; index++) {
  22091. var animation = animations[index];
  22092. animation._target = target;
  22093. this._animations.push(animation);
  22094. }
  22095. };
  22096. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22097. var animations = this._animations;
  22098. for (var index = 0; index < animations.length; index++) {
  22099. if (animations[index].targetProperty === property) {
  22100. return animations[index];
  22101. }
  22102. }
  22103. return null;
  22104. };
  22105. Animatable.prototype.reset = function () {
  22106. var animations = this._animations;
  22107. for (var index = 0; index < animations.length; index++) {
  22108. animations[index].reset();
  22109. }
  22110. this._localDelayOffset = null;
  22111. this._pausedDelay = null;
  22112. };
  22113. Animatable.prototype.pause = function () {
  22114. if (this._paused) {
  22115. return;
  22116. }
  22117. this._paused = true;
  22118. };
  22119. Animatable.prototype.restart = function () {
  22120. this._paused = false;
  22121. };
  22122. Animatable.prototype.stop = function () {
  22123. var index = this._scene._activeAnimatables.indexOf(this);
  22124. if (index > -1) {
  22125. this._scene._activeAnimatables.splice(index, 1);
  22126. }
  22127. if (this.onAnimationEnd) {
  22128. this.onAnimationEnd();
  22129. }
  22130. };
  22131. Animatable.prototype._animate = function (delay) {
  22132. if (this._paused) {
  22133. if (!this._pausedDelay) {
  22134. this._pausedDelay = delay;
  22135. }
  22136. return true;
  22137. }
  22138. if (!this._localDelayOffset) {
  22139. this._localDelayOffset = delay;
  22140. }
  22141. else if (this._pausedDelay) {
  22142. this._localDelayOffset += delay - this._pausedDelay;
  22143. this._pausedDelay = null;
  22144. }
  22145. // Animating
  22146. var running = false;
  22147. var animations = this._animations;
  22148. for (var index = 0; index < animations.length; index++) {
  22149. var animation = animations[index];
  22150. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22151. running = running || isRunning;
  22152. }
  22153. if (!running) {
  22154. // Remove from active animatables
  22155. index = this._scene._activeAnimatables.indexOf(this);
  22156. this._scene._activeAnimatables.splice(index, 1);
  22157. }
  22158. if (!running && this.onAnimationEnd) {
  22159. this.onAnimationEnd();
  22160. }
  22161. return running;
  22162. };
  22163. return Animatable;
  22164. })();
  22165. BABYLON.Animatable = Animatable;
  22166. })(BABYLON || (BABYLON = {}));
  22167. var BABYLON;
  22168. (function (BABYLON) {
  22169. var EasingFunction = (function () {
  22170. function EasingFunction() {
  22171. // Properties
  22172. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22173. }
  22174. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22175. get: function () {
  22176. return EasingFunction._EASINGMODE_EASEIN;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22182. get: function () {
  22183. return EasingFunction._EASINGMODE_EASEOUT;
  22184. },
  22185. enumerable: true,
  22186. configurable: true
  22187. });
  22188. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22189. get: function () {
  22190. return EasingFunction._EASINGMODE_EASEINOUT;
  22191. },
  22192. enumerable: true,
  22193. configurable: true
  22194. });
  22195. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22196. var n = Math.min(Math.max(easingMode, 0), 2);
  22197. this._easingMode = n;
  22198. };
  22199. EasingFunction.prototype.getEasingMode = function () {
  22200. return this._easingMode;
  22201. };
  22202. EasingFunction.prototype.easeInCore = function (gradient) {
  22203. throw new Error('You must implement this method');
  22204. };
  22205. EasingFunction.prototype.ease = function (gradient) {
  22206. switch (this._easingMode) {
  22207. case EasingFunction.EASINGMODE_EASEIN:
  22208. return this.easeInCore(gradient);
  22209. case EasingFunction.EASINGMODE_EASEOUT:
  22210. return (1 - this.easeInCore(1 - gradient));
  22211. }
  22212. if (gradient >= 0.5) {
  22213. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22214. }
  22215. return (this.easeInCore(gradient * 2) * 0.5);
  22216. };
  22217. //Statics
  22218. EasingFunction._EASINGMODE_EASEIN = 0;
  22219. EasingFunction._EASINGMODE_EASEOUT = 1;
  22220. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22221. return EasingFunction;
  22222. })();
  22223. BABYLON.EasingFunction = EasingFunction;
  22224. var CircleEase = (function (_super) {
  22225. __extends(CircleEase, _super);
  22226. function CircleEase() {
  22227. _super.apply(this, arguments);
  22228. }
  22229. CircleEase.prototype.easeInCore = function (gradient) {
  22230. gradient = Math.max(0, Math.min(1, gradient));
  22231. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22232. };
  22233. return CircleEase;
  22234. })(EasingFunction);
  22235. BABYLON.CircleEase = CircleEase;
  22236. var BackEase = (function (_super) {
  22237. __extends(BackEase, _super);
  22238. function BackEase(amplitude) {
  22239. if (amplitude === void 0) { amplitude = 1; }
  22240. _super.call(this);
  22241. this.amplitude = amplitude;
  22242. }
  22243. BackEase.prototype.easeInCore = function (gradient) {
  22244. var num = Math.max(0, this.amplitude);
  22245. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22246. };
  22247. return BackEase;
  22248. })(EasingFunction);
  22249. BABYLON.BackEase = BackEase;
  22250. var BounceEase = (function (_super) {
  22251. __extends(BounceEase, _super);
  22252. function BounceEase(bounces, bounciness) {
  22253. if (bounces === void 0) { bounces = 3; }
  22254. if (bounciness === void 0) { bounciness = 2; }
  22255. _super.call(this);
  22256. this.bounces = bounces;
  22257. this.bounciness = bounciness;
  22258. }
  22259. BounceEase.prototype.easeInCore = function (gradient) {
  22260. var y = Math.max(0.0, this.bounces);
  22261. var bounciness = this.bounciness;
  22262. if (bounciness <= 1.0) {
  22263. bounciness = 1.001;
  22264. }
  22265. var num9 = Math.pow(bounciness, y);
  22266. var num5 = 1.0 - bounciness;
  22267. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22268. var num15 = gradient * num4;
  22269. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22270. var num3 = Math.floor(num65);
  22271. var num13 = num3 + 1.0;
  22272. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22273. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22274. var num7 = (num8 + num12) * 0.5;
  22275. var num6 = gradient - num7;
  22276. var num2 = num7 - num8;
  22277. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22278. };
  22279. return BounceEase;
  22280. })(EasingFunction);
  22281. BABYLON.BounceEase = BounceEase;
  22282. var CubicEase = (function (_super) {
  22283. __extends(CubicEase, _super);
  22284. function CubicEase() {
  22285. _super.apply(this, arguments);
  22286. }
  22287. CubicEase.prototype.easeInCore = function (gradient) {
  22288. return (gradient * gradient * gradient);
  22289. };
  22290. return CubicEase;
  22291. })(EasingFunction);
  22292. BABYLON.CubicEase = CubicEase;
  22293. var ElasticEase = (function (_super) {
  22294. __extends(ElasticEase, _super);
  22295. function ElasticEase(oscillations, springiness) {
  22296. if (oscillations === void 0) { oscillations = 3; }
  22297. if (springiness === void 0) { springiness = 3; }
  22298. _super.call(this);
  22299. this.oscillations = oscillations;
  22300. this.springiness = springiness;
  22301. }
  22302. ElasticEase.prototype.easeInCore = function (gradient) {
  22303. var num2;
  22304. var num3 = Math.max(0.0, this.oscillations);
  22305. var num = Math.max(0.0, this.springiness);
  22306. if (num == 0) {
  22307. num2 = gradient;
  22308. }
  22309. else {
  22310. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22311. }
  22312. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22313. };
  22314. return ElasticEase;
  22315. })(EasingFunction);
  22316. BABYLON.ElasticEase = ElasticEase;
  22317. var ExponentialEase = (function (_super) {
  22318. __extends(ExponentialEase, _super);
  22319. function ExponentialEase(exponent) {
  22320. if (exponent === void 0) { exponent = 2; }
  22321. _super.call(this);
  22322. this.exponent = exponent;
  22323. }
  22324. ExponentialEase.prototype.easeInCore = function (gradient) {
  22325. if (this.exponent <= 0) {
  22326. return gradient;
  22327. }
  22328. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22329. };
  22330. return ExponentialEase;
  22331. })(EasingFunction);
  22332. BABYLON.ExponentialEase = ExponentialEase;
  22333. var PowerEase = (function (_super) {
  22334. __extends(PowerEase, _super);
  22335. function PowerEase(power) {
  22336. if (power === void 0) { power = 2; }
  22337. _super.call(this);
  22338. this.power = power;
  22339. }
  22340. PowerEase.prototype.easeInCore = function (gradient) {
  22341. var y = Math.max(0.0, this.power);
  22342. return Math.pow(gradient, y);
  22343. };
  22344. return PowerEase;
  22345. })(EasingFunction);
  22346. BABYLON.PowerEase = PowerEase;
  22347. var QuadraticEase = (function (_super) {
  22348. __extends(QuadraticEase, _super);
  22349. function QuadraticEase() {
  22350. _super.apply(this, arguments);
  22351. }
  22352. QuadraticEase.prototype.easeInCore = function (gradient) {
  22353. return (gradient * gradient);
  22354. };
  22355. return QuadraticEase;
  22356. })(EasingFunction);
  22357. BABYLON.QuadraticEase = QuadraticEase;
  22358. var QuarticEase = (function (_super) {
  22359. __extends(QuarticEase, _super);
  22360. function QuarticEase() {
  22361. _super.apply(this, arguments);
  22362. }
  22363. QuarticEase.prototype.easeInCore = function (gradient) {
  22364. return (gradient * gradient * gradient * gradient);
  22365. };
  22366. return QuarticEase;
  22367. })(EasingFunction);
  22368. BABYLON.QuarticEase = QuarticEase;
  22369. var QuinticEase = (function (_super) {
  22370. __extends(QuinticEase, _super);
  22371. function QuinticEase() {
  22372. _super.apply(this, arguments);
  22373. }
  22374. QuinticEase.prototype.easeInCore = function (gradient) {
  22375. return (gradient * gradient * gradient * gradient * gradient);
  22376. };
  22377. return QuinticEase;
  22378. })(EasingFunction);
  22379. BABYLON.QuinticEase = QuinticEase;
  22380. var SineEase = (function (_super) {
  22381. __extends(SineEase, _super);
  22382. function SineEase() {
  22383. _super.apply(this, arguments);
  22384. }
  22385. SineEase.prototype.easeInCore = function (gradient) {
  22386. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22387. };
  22388. return SineEase;
  22389. })(EasingFunction);
  22390. BABYLON.SineEase = SineEase;
  22391. var BezierCurveEase = (function (_super) {
  22392. __extends(BezierCurveEase, _super);
  22393. function BezierCurveEase(x1, y1, x2, y2) {
  22394. if (x1 === void 0) { x1 = 0; }
  22395. if (y1 === void 0) { y1 = 0; }
  22396. if (x2 === void 0) { x2 = 1; }
  22397. if (y2 === void 0) { y2 = 1; }
  22398. _super.call(this);
  22399. this.x1 = x1;
  22400. this.y1 = y1;
  22401. this.x2 = x2;
  22402. this.y2 = y2;
  22403. }
  22404. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22405. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22406. };
  22407. return BezierCurveEase;
  22408. })(EasingFunction);
  22409. BABYLON.BezierCurveEase = BezierCurveEase;
  22410. })(BABYLON || (BABYLON = {}));
  22411. var BABYLON;
  22412. (function (BABYLON) {
  22413. var Octree = (function () {
  22414. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22415. if (maxDepth === void 0) { maxDepth = 2; }
  22416. this.maxDepth = maxDepth;
  22417. this.dynamicContent = new Array();
  22418. this._maxBlockCapacity = maxBlockCapacity || 64;
  22419. this._selectionContent = new BABYLON.SmartArray(1024);
  22420. this._creationFunc = creationFunc;
  22421. }
  22422. // Methods
  22423. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22424. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22425. };
  22426. Octree.prototype.addMesh = function (entry) {
  22427. for (var index = 0; index < this.blocks.length; index++) {
  22428. var block = this.blocks[index];
  22429. block.addEntry(entry);
  22430. }
  22431. };
  22432. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22433. this._selectionContent.reset();
  22434. for (var index = 0; index < this.blocks.length; index++) {
  22435. var block = this.blocks[index];
  22436. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22437. }
  22438. if (allowDuplicate) {
  22439. this._selectionContent.concat(this.dynamicContent);
  22440. }
  22441. else {
  22442. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22443. }
  22444. return this._selectionContent;
  22445. };
  22446. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22447. this._selectionContent.reset();
  22448. for (var index = 0; index < this.blocks.length; index++) {
  22449. var block = this.blocks[index];
  22450. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22451. }
  22452. if (allowDuplicate) {
  22453. this._selectionContent.concat(this.dynamicContent);
  22454. }
  22455. else {
  22456. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22457. }
  22458. return this._selectionContent;
  22459. };
  22460. Octree.prototype.intersectsRay = function (ray) {
  22461. this._selectionContent.reset();
  22462. for (var index = 0; index < this.blocks.length; index++) {
  22463. var block = this.blocks[index];
  22464. block.intersectsRay(ray, this._selectionContent);
  22465. }
  22466. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22467. return this._selectionContent;
  22468. };
  22469. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22470. target.blocks = new Array();
  22471. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22472. // Segmenting space
  22473. for (var x = 0; x < 2; x++) {
  22474. for (var y = 0; y < 2; y++) {
  22475. for (var z = 0; z < 2; z++) {
  22476. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22477. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22478. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22479. block.addEntries(entries);
  22480. target.blocks.push(block);
  22481. }
  22482. }
  22483. }
  22484. };
  22485. Octree.CreationFuncForMeshes = function (entry, block) {
  22486. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22487. block.entries.push(entry);
  22488. }
  22489. };
  22490. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22491. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22492. block.entries.push(entry);
  22493. }
  22494. };
  22495. return Octree;
  22496. })();
  22497. BABYLON.Octree = Octree;
  22498. })(BABYLON || (BABYLON = {}));
  22499. var BABYLON;
  22500. (function (BABYLON) {
  22501. var OctreeBlock = (function () {
  22502. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22503. this.entries = new Array();
  22504. this._boundingVectors = new Array();
  22505. this._capacity = capacity;
  22506. this._depth = depth;
  22507. this._maxDepth = maxDepth;
  22508. this._creationFunc = creationFunc;
  22509. this._minPoint = minPoint;
  22510. this._maxPoint = maxPoint;
  22511. this._boundingVectors.push(minPoint.clone());
  22512. this._boundingVectors.push(maxPoint.clone());
  22513. this._boundingVectors.push(minPoint.clone());
  22514. this._boundingVectors[2].x = maxPoint.x;
  22515. this._boundingVectors.push(minPoint.clone());
  22516. this._boundingVectors[3].y = maxPoint.y;
  22517. this._boundingVectors.push(minPoint.clone());
  22518. this._boundingVectors[4].z = maxPoint.z;
  22519. this._boundingVectors.push(maxPoint.clone());
  22520. this._boundingVectors[5].z = minPoint.z;
  22521. this._boundingVectors.push(maxPoint.clone());
  22522. this._boundingVectors[6].x = minPoint.x;
  22523. this._boundingVectors.push(maxPoint.clone());
  22524. this._boundingVectors[7].y = minPoint.y;
  22525. }
  22526. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22527. // Property
  22528. get: function () {
  22529. return this._capacity;
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22535. get: function () {
  22536. return this._minPoint;
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22542. get: function () {
  22543. return this._maxPoint;
  22544. },
  22545. enumerable: true,
  22546. configurable: true
  22547. });
  22548. // Methods
  22549. OctreeBlock.prototype.addEntry = function (entry) {
  22550. if (this.blocks) {
  22551. for (var index = 0; index < this.blocks.length; index++) {
  22552. var block = this.blocks[index];
  22553. block.addEntry(entry);
  22554. }
  22555. return;
  22556. }
  22557. this._creationFunc(entry, this);
  22558. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22559. this.createInnerBlocks();
  22560. }
  22561. };
  22562. OctreeBlock.prototype.addEntries = function (entries) {
  22563. for (var index = 0; index < entries.length; index++) {
  22564. var mesh = entries[index];
  22565. this.addEntry(mesh);
  22566. }
  22567. };
  22568. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22569. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22570. if (this.blocks) {
  22571. for (var index = 0; index < this.blocks.length; index++) {
  22572. var block = this.blocks[index];
  22573. block.select(frustumPlanes, selection, allowDuplicate);
  22574. }
  22575. return;
  22576. }
  22577. if (allowDuplicate) {
  22578. selection.concat(this.entries);
  22579. }
  22580. else {
  22581. selection.concatWithNoDuplicate(this.entries);
  22582. }
  22583. }
  22584. };
  22585. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22586. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22587. if (this.blocks) {
  22588. for (var index = 0; index < this.blocks.length; index++) {
  22589. var block = this.blocks[index];
  22590. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22591. }
  22592. return;
  22593. }
  22594. if (allowDuplicate) {
  22595. selection.concat(this.entries);
  22596. }
  22597. else {
  22598. selection.concatWithNoDuplicate(this.entries);
  22599. }
  22600. }
  22601. };
  22602. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22603. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22604. if (this.blocks) {
  22605. for (var index = 0; index < this.blocks.length; index++) {
  22606. var block = this.blocks[index];
  22607. block.intersectsRay(ray, selection);
  22608. }
  22609. return;
  22610. }
  22611. selection.concatWithNoDuplicate(this.entries);
  22612. }
  22613. };
  22614. OctreeBlock.prototype.createInnerBlocks = function () {
  22615. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22616. };
  22617. return OctreeBlock;
  22618. })();
  22619. BABYLON.OctreeBlock = OctreeBlock;
  22620. })(BABYLON || (BABYLON = {}));
  22621. var BABYLON;
  22622. (function (BABYLON) {
  22623. var Bone = (function (_super) {
  22624. __extends(Bone, _super);
  22625. function Bone(name, skeleton, parentBone, matrix) {
  22626. _super.call(this, name, skeleton.getScene());
  22627. this.name = name;
  22628. this.children = new Array();
  22629. this.animations = new Array();
  22630. this._worldTransform = new BABYLON.Matrix();
  22631. this._absoluteTransform = new BABYLON.Matrix();
  22632. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22633. this._skeleton = skeleton;
  22634. this._matrix = matrix;
  22635. this._baseMatrix = matrix;
  22636. skeleton.bones.push(this);
  22637. if (parentBone) {
  22638. this._parent = parentBone;
  22639. parentBone.children.push(this);
  22640. }
  22641. else {
  22642. this._parent = null;
  22643. }
  22644. this._updateDifferenceMatrix();
  22645. }
  22646. // Members
  22647. Bone.prototype.getParent = function () {
  22648. return this._parent;
  22649. };
  22650. Bone.prototype.getLocalMatrix = function () {
  22651. return this._matrix;
  22652. };
  22653. Bone.prototype.getBaseMatrix = function () {
  22654. return this._baseMatrix;
  22655. };
  22656. Bone.prototype.getWorldMatrix = function () {
  22657. return this._worldTransform;
  22658. };
  22659. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22660. return this._invertedAbsoluteTransform;
  22661. };
  22662. Bone.prototype.getAbsoluteMatrix = function () {
  22663. var matrix = this._matrix.clone();
  22664. var parent = this._parent;
  22665. while (parent) {
  22666. matrix = matrix.multiply(parent.getLocalMatrix());
  22667. parent = parent.getParent();
  22668. }
  22669. return matrix;
  22670. };
  22671. // Methods
  22672. Bone.prototype.updateMatrix = function (matrix) {
  22673. this._matrix = matrix;
  22674. this._skeleton._markAsDirty();
  22675. this._updateDifferenceMatrix();
  22676. };
  22677. Bone.prototype._updateDifferenceMatrix = function () {
  22678. if (this._parent) {
  22679. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22680. }
  22681. else {
  22682. this._absoluteTransform.copyFrom(this._matrix);
  22683. }
  22684. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22685. for (var index = 0; index < this.children.length; index++) {
  22686. this.children[index]._updateDifferenceMatrix();
  22687. }
  22688. };
  22689. Bone.prototype.markAsDirty = function () {
  22690. this._currentRenderId++;
  22691. this._skeleton._markAsDirty();
  22692. };
  22693. return Bone;
  22694. })(BABYLON.Node);
  22695. BABYLON.Bone = Bone;
  22696. })(BABYLON || (BABYLON = {}));
  22697. var BABYLON;
  22698. (function (BABYLON) {
  22699. var Skeleton = (function () {
  22700. function Skeleton(name, id, scene) {
  22701. this.name = name;
  22702. this.id = id;
  22703. this.bones = new Array();
  22704. this._isDirty = true;
  22705. this._identity = BABYLON.Matrix.Identity();
  22706. this.bones = [];
  22707. this._scene = scene;
  22708. scene.skeletons.push(this);
  22709. this.prepare();
  22710. //make sure it will recalculate the matrix next time prepare is called.
  22711. this._isDirty = true;
  22712. }
  22713. // Members
  22714. Skeleton.prototype.getTransformMatrices = function () {
  22715. return this._transformMatrices;
  22716. };
  22717. Skeleton.prototype.getScene = function () {
  22718. return this._scene;
  22719. };
  22720. // Methods
  22721. Skeleton.prototype._markAsDirty = function () {
  22722. this._isDirty = true;
  22723. };
  22724. Skeleton.prototype.prepare = function () {
  22725. if (!this._isDirty) {
  22726. return;
  22727. }
  22728. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22729. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22730. }
  22731. for (var index = 0; index < this.bones.length; index++) {
  22732. var bone = this.bones[index];
  22733. var parentBone = bone.getParent();
  22734. if (parentBone) {
  22735. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22736. }
  22737. else {
  22738. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22739. }
  22740. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22741. }
  22742. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22743. this._isDirty = false;
  22744. this._scene._activeBones += this.bones.length;
  22745. };
  22746. Skeleton.prototype.getAnimatables = function () {
  22747. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22748. this._animatables = [];
  22749. for (var index = 0; index < this.bones.length; index++) {
  22750. this._animatables.push(this.bones[index]);
  22751. }
  22752. }
  22753. return this._animatables;
  22754. };
  22755. Skeleton.prototype.clone = function (name, id) {
  22756. var result = new Skeleton(name, id || name, this._scene);
  22757. for (var index = 0; index < this.bones.length; index++) {
  22758. var source = this.bones[index];
  22759. var parentBone = null;
  22760. if (source.getParent()) {
  22761. var parentIndex = this.bones.indexOf(source.getParent());
  22762. parentBone = result.bones[parentIndex];
  22763. }
  22764. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22765. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22766. }
  22767. return result;
  22768. };
  22769. return Skeleton;
  22770. })();
  22771. BABYLON.Skeleton = Skeleton;
  22772. })(BABYLON || (BABYLON = {}));
  22773. var BABYLON;
  22774. (function (BABYLON) {
  22775. var PostProcess = (function () {
  22776. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22778. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22779. this.name = name;
  22780. this.width = -1;
  22781. this.height = -1;
  22782. this._reusable = false;
  22783. this._textures = new BABYLON.SmartArray(2);
  22784. this._currentRenderTextureInd = 0;
  22785. if (camera != null) {
  22786. this._camera = camera;
  22787. this._scene = camera.getScene();
  22788. camera.attachPostProcess(this);
  22789. this._engine = this._scene.getEngine();
  22790. }
  22791. else {
  22792. this._engine = engine;
  22793. }
  22794. this._renderRatio = ratio;
  22795. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22796. this._reusable = reusable || false;
  22797. this._textureType = textureType;
  22798. samplers = samplers || [];
  22799. samplers.push("textureSampler");
  22800. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22801. }
  22802. PostProcess.prototype.isReusable = function () {
  22803. return this._reusable;
  22804. };
  22805. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22806. camera = camera || this._camera;
  22807. var scene = camera.getScene();
  22808. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22809. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22810. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22811. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22812. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22813. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22814. if (this._textures.length > 0) {
  22815. for (var i = 0; i < this._textures.length; i++) {
  22816. this._engine._releaseTexture(this._textures.data[i]);
  22817. }
  22818. this._textures.reset();
  22819. }
  22820. this.width = desiredWidth;
  22821. this.height = desiredHeight;
  22822. 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 }));
  22823. if (this._reusable) {
  22824. 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 }));
  22825. }
  22826. if (this.onSizeChanged) {
  22827. this.onSizeChanged();
  22828. }
  22829. }
  22830. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22831. if (this.onActivate) {
  22832. this.onActivate(camera);
  22833. }
  22834. // Clear
  22835. if (this.clearColor) {
  22836. this._engine.clear(this.clearColor, true, true);
  22837. }
  22838. else {
  22839. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22840. }
  22841. if (this._reusable) {
  22842. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22843. }
  22844. };
  22845. PostProcess.prototype.apply = function () {
  22846. // Check
  22847. if (!this._effect.isReady())
  22848. return null;
  22849. // States
  22850. this._engine.enableEffect(this._effect);
  22851. this._engine.setState(false);
  22852. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22853. this._engine.setDepthBuffer(false);
  22854. this._engine.setDepthWrite(false);
  22855. // Texture
  22856. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22857. // Parameters
  22858. if (this.onApply) {
  22859. this.onApply(this._effect);
  22860. }
  22861. return this._effect;
  22862. };
  22863. PostProcess.prototype.dispose = function (camera) {
  22864. camera = camera || this._camera;
  22865. if (this._textures.length > 0) {
  22866. for (var i = 0; i < this._textures.length; i++) {
  22867. this._engine._releaseTexture(this._textures.data[i]);
  22868. }
  22869. this._textures.reset();
  22870. }
  22871. if (!camera) {
  22872. return;
  22873. }
  22874. camera.detachPostProcess(this);
  22875. var index = camera._postProcesses.indexOf(this);
  22876. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22877. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22878. }
  22879. };
  22880. return PostProcess;
  22881. })();
  22882. BABYLON.PostProcess = PostProcess;
  22883. })(BABYLON || (BABYLON = {}));
  22884. var BABYLON;
  22885. (function (BABYLON) {
  22886. var PostProcessManager = (function () {
  22887. function PostProcessManager(scene) {
  22888. this._vertexDeclaration = [2];
  22889. this._vertexStrideSize = 2 * 4;
  22890. this._scene = scene;
  22891. }
  22892. PostProcessManager.prototype._prepareBuffers = function () {
  22893. if (this._vertexBuffer) {
  22894. return;
  22895. }
  22896. // VBO
  22897. var vertices = [];
  22898. vertices.push(1, 1);
  22899. vertices.push(-1, 1);
  22900. vertices.push(-1, -1);
  22901. vertices.push(1, -1);
  22902. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22903. // Indices
  22904. var indices = [];
  22905. indices.push(0);
  22906. indices.push(1);
  22907. indices.push(2);
  22908. indices.push(0);
  22909. indices.push(2);
  22910. indices.push(3);
  22911. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22912. };
  22913. // Methods
  22914. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22915. var postProcesses = this._scene.activeCamera._postProcesses;
  22916. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22917. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22918. return false;
  22919. }
  22920. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22921. return true;
  22922. };
  22923. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22924. var engine = this._scene.getEngine();
  22925. for (var index = 0; index < postProcesses.length; index++) {
  22926. if (index < postProcesses.length - 1) {
  22927. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22928. }
  22929. else {
  22930. if (targetTexture) {
  22931. engine.bindFramebuffer(targetTexture);
  22932. }
  22933. else {
  22934. engine.restoreDefaultFramebuffer();
  22935. }
  22936. }
  22937. var pp = postProcesses[index];
  22938. var effect = pp.apply();
  22939. if (effect) {
  22940. if (pp.onBeforeRender) {
  22941. pp.onBeforeRender(effect);
  22942. }
  22943. // VBOs
  22944. this._prepareBuffers();
  22945. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22946. // Draw order
  22947. engine.draw(true, 0, 6);
  22948. if (pp.onAfterRender) {
  22949. pp.onAfterRender(effect);
  22950. }
  22951. }
  22952. }
  22953. // Restore depth buffer
  22954. engine.setDepthBuffer(true);
  22955. engine.setDepthWrite(true);
  22956. };
  22957. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22958. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22959. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22960. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22961. return;
  22962. }
  22963. var engine = this._scene.getEngine();
  22964. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22965. if (index < postProcessesTakenIndices.length - 1) {
  22966. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22967. }
  22968. else {
  22969. if (targetTexture) {
  22970. engine.bindFramebuffer(targetTexture);
  22971. }
  22972. else {
  22973. engine.restoreDefaultFramebuffer();
  22974. }
  22975. }
  22976. if (doNotPresent) {
  22977. break;
  22978. }
  22979. var pp = postProcesses[postProcessesTakenIndices[index]];
  22980. var effect = pp.apply();
  22981. if (effect) {
  22982. if (pp.onBeforeRender) {
  22983. pp.onBeforeRender(effect);
  22984. }
  22985. // VBOs
  22986. this._prepareBuffers();
  22987. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22988. // Draw order
  22989. engine.draw(true, 0, 6);
  22990. if (pp.onAfterRender) {
  22991. pp.onAfterRender(effect);
  22992. }
  22993. }
  22994. }
  22995. // Restore depth buffer
  22996. engine.setDepthBuffer(true);
  22997. engine.setDepthWrite(true);
  22998. };
  22999. PostProcessManager.prototype.dispose = function () {
  23000. if (this._vertexBuffer) {
  23001. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23002. this._vertexBuffer = null;
  23003. }
  23004. if (this._indexBuffer) {
  23005. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23006. this._indexBuffer = null;
  23007. }
  23008. };
  23009. return PostProcessManager;
  23010. })();
  23011. BABYLON.PostProcessManager = PostProcessManager;
  23012. })(BABYLON || (BABYLON = {}));
  23013. var BABYLON;
  23014. (function (BABYLON) {
  23015. var PassPostProcess = (function (_super) {
  23016. __extends(PassPostProcess, _super);
  23017. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23018. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23019. }
  23020. return PassPostProcess;
  23021. })(BABYLON.PostProcess);
  23022. BABYLON.PassPostProcess = PassPostProcess;
  23023. })(BABYLON || (BABYLON = {}));
  23024. var BABYLON;
  23025. (function (BABYLON) {
  23026. var BlurPostProcess = (function (_super) {
  23027. __extends(BlurPostProcess, _super);
  23028. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23029. var _this = this;
  23030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23031. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23032. this.direction = direction;
  23033. this.blurWidth = blurWidth;
  23034. this.onApply = function (effect) {
  23035. effect.setFloat2("screenSize", _this.width, _this.height);
  23036. effect.setVector2("direction", _this.direction);
  23037. effect.setFloat("blurWidth", _this.blurWidth);
  23038. };
  23039. }
  23040. return BlurPostProcess;
  23041. })(BABYLON.PostProcess);
  23042. BABYLON.BlurPostProcess = BlurPostProcess;
  23043. })(BABYLON || (BABYLON = {}));
  23044. var BABYLON;
  23045. (function (BABYLON) {
  23046. var RefractionPostProcess = (function (_super) {
  23047. __extends(RefractionPostProcess, _super);
  23048. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23049. var _this = this;
  23050. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23051. this.color = color;
  23052. this.depth = depth;
  23053. this.colorLevel = colorLevel;
  23054. this.onActivate = function (cam) {
  23055. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23056. };
  23057. this.onApply = function (effect) {
  23058. effect.setColor3("baseColor", _this.color);
  23059. effect.setFloat("depth", _this.depth);
  23060. effect.setFloat("colorLevel", _this.colorLevel);
  23061. effect.setTexture("refractionSampler", _this._refRexture);
  23062. };
  23063. }
  23064. // Methods
  23065. RefractionPostProcess.prototype.dispose = function (camera) {
  23066. if (this._refRexture) {
  23067. this._refRexture.dispose();
  23068. }
  23069. _super.prototype.dispose.call(this, camera);
  23070. };
  23071. return RefractionPostProcess;
  23072. })(BABYLON.PostProcess);
  23073. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23074. })(BABYLON || (BABYLON = {}));
  23075. var BABYLON;
  23076. (function (BABYLON) {
  23077. var BlackAndWhitePostProcess = (function (_super) {
  23078. __extends(BlackAndWhitePostProcess, _super);
  23079. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23080. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23081. }
  23082. return BlackAndWhitePostProcess;
  23083. })(BABYLON.PostProcess);
  23084. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23085. })(BABYLON || (BABYLON = {}));
  23086. var BABYLON;
  23087. (function (BABYLON) {
  23088. var ConvolutionPostProcess = (function (_super) {
  23089. __extends(ConvolutionPostProcess, _super);
  23090. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23091. var _this = this;
  23092. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23093. this.kernel = kernel;
  23094. this.onApply = function (effect) {
  23095. effect.setFloat2("screenSize", _this.width, _this.height);
  23096. effect.setArray("kernel", _this.kernel);
  23097. };
  23098. }
  23099. // Statics
  23100. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23101. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23102. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23103. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23104. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23105. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23106. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23107. return ConvolutionPostProcess;
  23108. })(BABYLON.PostProcess);
  23109. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23110. })(BABYLON || (BABYLON = {}));
  23111. var BABYLON;
  23112. (function (BABYLON) {
  23113. var FilterPostProcess = (function (_super) {
  23114. __extends(FilterPostProcess, _super);
  23115. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23116. var _this = this;
  23117. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23118. this.kernelMatrix = kernelMatrix;
  23119. this.onApply = function (effect) {
  23120. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23121. };
  23122. }
  23123. return FilterPostProcess;
  23124. })(BABYLON.PostProcess);
  23125. BABYLON.FilterPostProcess = FilterPostProcess;
  23126. })(BABYLON || (BABYLON = {}));
  23127. var BABYLON;
  23128. (function (BABYLON) {
  23129. var FxaaPostProcess = (function (_super) {
  23130. __extends(FxaaPostProcess, _super);
  23131. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23132. var _this = this;
  23133. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23134. this.onSizeChanged = function () {
  23135. _this.texelWidth = 1.0 / _this.width;
  23136. _this.texelHeight = 1.0 / _this.height;
  23137. };
  23138. this.onApply = function (effect) {
  23139. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23140. };
  23141. }
  23142. return FxaaPostProcess;
  23143. })(BABYLON.PostProcess);
  23144. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23145. })(BABYLON || (BABYLON = {}));
  23146. var BABYLON;
  23147. (function (BABYLON) {
  23148. var StereoscopicInterlacePostProcess = (function (_super) {
  23149. __extends(StereoscopicInterlacePostProcess, _super);
  23150. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23151. var _this = this;
  23152. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23153. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23154. this.onSizeChanged = function () {
  23155. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23156. };
  23157. this.onApply = function (effect) {
  23158. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23159. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23160. };
  23161. }
  23162. return StereoscopicInterlacePostProcess;
  23163. })(BABYLON.PostProcess);
  23164. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23165. })(BABYLON || (BABYLON = {}));
  23166. var BABYLON;
  23167. (function (BABYLON) {
  23168. var LensFlare = (function () {
  23169. function LensFlare(size, position, color, imgUrl, system) {
  23170. this.size = size;
  23171. this.position = position;
  23172. this.dispose = function () {
  23173. if (this.texture) {
  23174. this.texture.dispose();
  23175. }
  23176. // Remove from scene
  23177. var index = this._system.lensFlares.indexOf(this);
  23178. this._system.lensFlares.splice(index, 1);
  23179. };
  23180. this.color = color || new BABYLON.Color3(1, 1, 1);
  23181. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23182. this._system = system;
  23183. system.lensFlares.push(this);
  23184. }
  23185. return LensFlare;
  23186. })();
  23187. BABYLON.LensFlare = LensFlare;
  23188. })(BABYLON || (BABYLON = {}));
  23189. var BABYLON;
  23190. (function (BABYLON) {
  23191. var LensFlareSystem = (function () {
  23192. function LensFlareSystem(name, emitter, scene) {
  23193. this.name = name;
  23194. this.lensFlares = new Array();
  23195. this.borderLimit = 300;
  23196. this.layerMask = 0x0FFFFFFF;
  23197. this._vertexDeclaration = [2];
  23198. this._vertexStrideSize = 2 * 4;
  23199. this._isEnabled = true;
  23200. this._scene = scene;
  23201. this._emitter = emitter;
  23202. scene.lensFlareSystems.push(this);
  23203. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23204. // VBO
  23205. var vertices = [];
  23206. vertices.push(1, 1);
  23207. vertices.push(-1, 1);
  23208. vertices.push(-1, -1);
  23209. vertices.push(1, -1);
  23210. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23211. // Indices
  23212. var indices = [];
  23213. indices.push(0);
  23214. indices.push(1);
  23215. indices.push(2);
  23216. indices.push(0);
  23217. indices.push(2);
  23218. indices.push(3);
  23219. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23220. // Effects
  23221. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23222. }
  23223. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23224. get: function () {
  23225. return this._isEnabled;
  23226. },
  23227. set: function (value) {
  23228. this._isEnabled = value;
  23229. },
  23230. enumerable: true,
  23231. configurable: true
  23232. });
  23233. LensFlareSystem.prototype.getScene = function () {
  23234. return this._scene;
  23235. };
  23236. LensFlareSystem.prototype.getEmitter = function () {
  23237. return this._emitter;
  23238. };
  23239. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23240. this._emitter = newEmitter;
  23241. };
  23242. LensFlareSystem.prototype.getEmitterPosition = function () {
  23243. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23244. };
  23245. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23246. var position = this.getEmitterPosition();
  23247. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23248. this._positionX = position.x;
  23249. this._positionY = position.y;
  23250. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23251. if (position.z > 0) {
  23252. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23253. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23254. return true;
  23255. }
  23256. }
  23257. return false;
  23258. };
  23259. LensFlareSystem.prototype._isVisible = function () {
  23260. if (!this._isEnabled) {
  23261. return false;
  23262. }
  23263. var emitterPosition = this.getEmitterPosition();
  23264. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23265. var distance = direction.length();
  23266. direction.normalize();
  23267. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23268. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23269. return !pickInfo.hit || pickInfo.distance > distance;
  23270. };
  23271. LensFlareSystem.prototype.render = function () {
  23272. if (!this._effect.isReady())
  23273. return false;
  23274. var engine = this._scene.getEngine();
  23275. var viewport = this._scene.activeCamera.viewport;
  23276. var globalViewport = viewport.toGlobal(engine);
  23277. // Position
  23278. if (!this.computeEffectivePosition(globalViewport)) {
  23279. return false;
  23280. }
  23281. // Visibility
  23282. if (!this._isVisible()) {
  23283. return false;
  23284. }
  23285. // Intensity
  23286. var awayX;
  23287. var awayY;
  23288. if (this._positionX < this.borderLimit + globalViewport.x) {
  23289. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23290. }
  23291. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23292. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23293. }
  23294. else {
  23295. awayX = 0;
  23296. }
  23297. if (this._positionY < this.borderLimit + globalViewport.y) {
  23298. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23299. }
  23300. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23301. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23302. }
  23303. else {
  23304. awayY = 0;
  23305. }
  23306. var away = (awayX > awayY) ? awayX : awayY;
  23307. if (away > this.borderLimit) {
  23308. away = this.borderLimit;
  23309. }
  23310. var intensity = 1.0 - (away / this.borderLimit);
  23311. if (intensity < 0) {
  23312. return false;
  23313. }
  23314. if (intensity > 1.0) {
  23315. intensity = 1.0;
  23316. }
  23317. // Position
  23318. var centerX = globalViewport.x + globalViewport.width / 2;
  23319. var centerY = globalViewport.y + globalViewport.height / 2;
  23320. var distX = centerX - this._positionX;
  23321. var distY = centerY - this._positionY;
  23322. // Effects
  23323. engine.enableEffect(this._effect);
  23324. engine.setState(false);
  23325. engine.setDepthBuffer(false);
  23326. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23327. // VBOs
  23328. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23329. // Flares
  23330. for (var index = 0; index < this.lensFlares.length; index++) {
  23331. var flare = this.lensFlares[index];
  23332. var x = centerX - (distX * flare.position);
  23333. var y = centerY - (distY * flare.position);
  23334. var cw = flare.size;
  23335. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23336. var cx = 2 * (x / globalViewport.width) - 1.0;
  23337. var cy = 1.0 - 2 * (y / globalViewport.height);
  23338. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23339. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23340. // Texture
  23341. this._effect.setTexture("textureSampler", flare.texture);
  23342. // Color
  23343. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23344. // Draw order
  23345. engine.draw(true, 0, 6);
  23346. }
  23347. engine.setDepthBuffer(true);
  23348. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23349. return true;
  23350. };
  23351. LensFlareSystem.prototype.dispose = function () {
  23352. if (this._vertexBuffer) {
  23353. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23354. this._vertexBuffer = null;
  23355. }
  23356. if (this._indexBuffer) {
  23357. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23358. this._indexBuffer = null;
  23359. }
  23360. while (this.lensFlares.length) {
  23361. this.lensFlares[0].dispose();
  23362. }
  23363. // Remove from scene
  23364. var index = this._scene.lensFlareSystems.indexOf(this);
  23365. this._scene.lensFlareSystems.splice(index, 1);
  23366. };
  23367. return LensFlareSystem;
  23368. })();
  23369. BABYLON.LensFlareSystem = LensFlareSystem;
  23370. })(BABYLON || (BABYLON = {}));
  23371. var BABYLON;
  23372. (function (BABYLON) {
  23373. var CannonJSPlugin = (function () {
  23374. function CannonJSPlugin() {
  23375. this._registeredMeshes = [];
  23376. this._physicsMaterials = [];
  23377. this.updateBodyPosition = function (mesh) {
  23378. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23379. var registeredMesh = this._registeredMeshes[index];
  23380. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23381. var body = registeredMesh.body;
  23382. var center = mesh.getBoundingInfo().boundingBox.center;
  23383. body.position.set(center.x, center.z, center.y);
  23384. body.quaternion.x = mesh.rotationQuaternion.x;
  23385. body.quaternion.z = mesh.rotationQuaternion.y;
  23386. body.quaternion.y = mesh.rotationQuaternion.z;
  23387. body.quaternion.w = -mesh.rotationQuaternion.w;
  23388. return;
  23389. }
  23390. }
  23391. };
  23392. }
  23393. CannonJSPlugin.prototype.initialize = function (iterations) {
  23394. if (iterations === void 0) { iterations = 10; }
  23395. this._world = new CANNON.World();
  23396. this._world.broadphase = new CANNON.NaiveBroadphase();
  23397. this._world.solver.iterations = iterations;
  23398. };
  23399. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23400. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23401. };
  23402. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23403. this._world.step(delta);
  23404. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23405. var registeredMesh = this._registeredMeshes[index];
  23406. if (registeredMesh.isChild) {
  23407. continue;
  23408. }
  23409. // Body position
  23410. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23411. var deltaPos = registeredMesh.delta;
  23412. if (deltaPos) {
  23413. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23414. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23415. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23416. }
  23417. else {
  23418. registeredMesh.mesh.position.x = bodyX;
  23419. registeredMesh.mesh.position.y = bodyZ;
  23420. registeredMesh.mesh.position.z = bodyY;
  23421. }
  23422. if (!registeredMesh.mesh.rotationQuaternion) {
  23423. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23424. }
  23425. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23426. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23427. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23428. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23429. }
  23430. };
  23431. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23432. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23433. };
  23434. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23435. this.unregisterMesh(mesh);
  23436. mesh.computeWorldMatrix(true);
  23437. switch (impostor) {
  23438. case BABYLON.PhysicsEngine.SphereImpostor:
  23439. var bbox = mesh.getBoundingInfo().boundingBox;
  23440. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23441. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23442. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23443. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23444. case BABYLON.PhysicsEngine.BoxImpostor:
  23445. bbox = mesh.getBoundingInfo().boundingBox;
  23446. var min = bbox.minimumWorld;
  23447. var max = bbox.maximumWorld;
  23448. var box = max.subtract(min).scale(0.5);
  23449. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23450. case BABYLON.PhysicsEngine.PlaneImpostor:
  23451. return this._createPlane(mesh, options);
  23452. case BABYLON.PhysicsEngine.MeshImpostor:
  23453. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23454. var rawFaces = mesh.getIndices();
  23455. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23456. }
  23457. return null;
  23458. };
  23459. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23460. var shape = new CANNON.Sphere(radius);
  23461. if (!options) {
  23462. return shape;
  23463. }
  23464. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23465. };
  23466. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23467. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23468. if (!options) {
  23469. return shape;
  23470. }
  23471. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23472. };
  23473. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23474. var shape = new CANNON.Plane();
  23475. if (!options) {
  23476. return shape;
  23477. }
  23478. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23479. };
  23480. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23481. var verts = [], faces = [];
  23482. mesh.computeWorldMatrix(true);
  23483. // Get vertices
  23484. for (var i = 0; i < rawVerts.length; i += 3) {
  23485. var transformed = BABYLON.Vector3.Zero();
  23486. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23487. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23488. }
  23489. // Get faces
  23490. for (var j = 0; j < rawFaces.length; j += 3) {
  23491. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23492. }
  23493. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23494. if (!options) {
  23495. return shape;
  23496. }
  23497. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23498. };
  23499. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23500. var index;
  23501. var mat;
  23502. for (index = 0; index < this._physicsMaterials.length; index++) {
  23503. mat = this._physicsMaterials[index];
  23504. if (mat.friction === friction && mat.restitution === restitution) {
  23505. return mat;
  23506. }
  23507. }
  23508. var currentMat = new CANNON.Material();
  23509. currentMat.friction = friction;
  23510. currentMat.restitution = restitution;
  23511. this._physicsMaterials.push(currentMat);
  23512. for (index = 0; index < this._physicsMaterials.length; index++) {
  23513. mat = this._physicsMaterials[index];
  23514. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23515. contactMaterial.contactEquationStiffness = 1e10;
  23516. contactMaterial.contactEquationRegularizationTime = 10;
  23517. this._world.addContactMaterial(contactMaterial);
  23518. }
  23519. return currentMat;
  23520. };
  23521. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23522. var initialRotation = null;
  23523. if (mesh.rotationQuaternion) {
  23524. initialRotation = mesh.rotationQuaternion.clone();
  23525. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23526. }
  23527. // The delta between the mesh position and the mesh bounding box center
  23528. var bbox = mesh.getBoundingInfo().boundingBox;
  23529. var deltaPosition = mesh.position.subtract(bbox.center);
  23530. var material = this._addMaterial(friction, restitution);
  23531. var body = new CANNON.RigidBody(mass, shape, material);
  23532. if (initialRotation) {
  23533. body.quaternion.x = initialRotation.x;
  23534. body.quaternion.z = initialRotation.y;
  23535. body.quaternion.y = initialRotation.z;
  23536. body.quaternion.w = -initialRotation.w;
  23537. }
  23538. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23539. this._world.add(body);
  23540. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23541. return body;
  23542. };
  23543. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23544. var compoundShape = new CANNON.Compound();
  23545. for (var index = 0; index < parts.length; index++) {
  23546. var mesh = parts[index].mesh;
  23547. var shape = this.registerMesh(mesh, parts[index].impostor);
  23548. if (index == 0) {
  23549. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23550. }
  23551. else {
  23552. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23553. }
  23554. }
  23555. var initialMesh = parts[0].mesh;
  23556. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23557. body.parts = parts;
  23558. return body;
  23559. };
  23560. CannonJSPlugin.prototype._unbindBody = function (body) {
  23561. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23562. var registeredMesh = this._registeredMeshes[index];
  23563. if (registeredMesh.body === body) {
  23564. registeredMesh.body = null;
  23565. registeredMesh.delta = 0;
  23566. }
  23567. }
  23568. };
  23569. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23570. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23571. var registeredMesh = this._registeredMeshes[index];
  23572. if (registeredMesh.mesh === mesh) {
  23573. // Remove body
  23574. if (registeredMesh.body) {
  23575. this._world.remove(registeredMesh.body);
  23576. this._unbindBody(registeredMesh.body);
  23577. }
  23578. this._registeredMeshes.splice(index, 1);
  23579. return;
  23580. }
  23581. }
  23582. };
  23583. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23584. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23585. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23586. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23587. var registeredMesh = this._registeredMeshes[index];
  23588. if (registeredMesh.mesh === mesh) {
  23589. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23590. return;
  23591. }
  23592. }
  23593. };
  23594. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23595. var body1 = null, body2 = null;
  23596. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23597. var registeredMesh = this._registeredMeshes[index];
  23598. if (registeredMesh.mesh === mesh1) {
  23599. body1 = registeredMesh.body;
  23600. }
  23601. else if (registeredMesh.mesh === mesh2) {
  23602. body2 = registeredMesh.body;
  23603. }
  23604. }
  23605. if (!body1 || !body2) {
  23606. return false;
  23607. }
  23608. 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));
  23609. this._world.addConstraint(constraint);
  23610. return true;
  23611. };
  23612. CannonJSPlugin.prototype.dispose = function () {
  23613. while (this._registeredMeshes.length) {
  23614. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23615. }
  23616. };
  23617. CannonJSPlugin.prototype.isSupported = function () {
  23618. return window.CANNON !== undefined;
  23619. };
  23620. return CannonJSPlugin;
  23621. })();
  23622. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23623. })(BABYLON || (BABYLON = {}));
  23624. var BABYLON;
  23625. (function (BABYLON) {
  23626. var OimoJSPlugin = (function () {
  23627. function OimoJSPlugin() {
  23628. this._registeredMeshes = [];
  23629. /**
  23630. * Update the body position according to the mesh position
  23631. * @param mesh
  23632. */
  23633. this.updateBodyPosition = function (mesh) {
  23634. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23635. var registeredMesh = this._registeredMeshes[index];
  23636. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23637. var body = registeredMesh.body.body;
  23638. mesh.computeWorldMatrix(true);
  23639. var center = mesh.getBoundingInfo().boundingBox.center;
  23640. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23641. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23642. body.sleeping = false;
  23643. return;
  23644. }
  23645. // Case where the parent has been updated
  23646. if (registeredMesh.mesh.parent === mesh) {
  23647. mesh.computeWorldMatrix(true);
  23648. registeredMesh.mesh.computeWorldMatrix(true);
  23649. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23650. var absoluteRotation = mesh.rotation;
  23651. body = registeredMesh.body.body;
  23652. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23653. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23654. body.sleeping = false;
  23655. return;
  23656. }
  23657. }
  23658. };
  23659. }
  23660. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23661. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23662. };
  23663. OimoJSPlugin.prototype.initialize = function (iterations) {
  23664. this._world = new OIMO.World();
  23665. this._world.clear();
  23666. };
  23667. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23668. this._world.gravity = gravity;
  23669. };
  23670. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23671. var body = null;
  23672. this.unregisterMesh(mesh);
  23673. mesh.computeWorldMatrix(true);
  23674. var initialRotation = null;
  23675. if (mesh.rotationQuaternion) {
  23676. initialRotation = mesh.rotationQuaternion.clone();
  23677. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23678. mesh.computeWorldMatrix(true);
  23679. }
  23680. var bbox = mesh.getBoundingInfo().boundingBox;
  23681. // The delta between the mesh position and the mesh bounding box center
  23682. var deltaPosition = mesh.position.subtract(bbox.center);
  23683. // Transform delta position with the rotation
  23684. if (initialRotation) {
  23685. var m = new BABYLON.Matrix();
  23686. initialRotation.toRotationMatrix(m);
  23687. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23688. }
  23689. // register mesh
  23690. switch (impostor) {
  23691. case BABYLON.PhysicsEngine.SphereImpostor:
  23692. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23693. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23694. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23695. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23696. body = new OIMO.Body({
  23697. type: 'sphere',
  23698. size: [size],
  23699. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23700. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23701. move: options.mass != 0,
  23702. config: [options.mass, options.friction, options.restitution],
  23703. world: this._world
  23704. });
  23705. break;
  23706. case BABYLON.PhysicsEngine.PlaneImpostor:
  23707. //Oimo "fakes" a cylinder as a box, so why don't we!
  23708. case BABYLON.PhysicsEngine.CylinderImpostor:
  23709. case BABYLON.PhysicsEngine.BoxImpostor:
  23710. var min = bbox.minimumWorld;
  23711. var max = bbox.maximumWorld;
  23712. var box = max.subtract(min);
  23713. var sizeX = this._checkWithEpsilon(box.x);
  23714. var sizeY = this._checkWithEpsilon(box.y);
  23715. var sizeZ = this._checkWithEpsilon(box.z);
  23716. body = new OIMO.Body({
  23717. type: 'box',
  23718. size: [sizeX, sizeY, sizeZ],
  23719. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23720. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23721. move: options.mass != 0,
  23722. config: [options.mass, options.friction, options.restitution],
  23723. world: this._world
  23724. });
  23725. break;
  23726. }
  23727. //If quaternion was set as the rotation of the object
  23728. if (initialRotation) {
  23729. //We have to access the rigid body's properties to set the quaternion.
  23730. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23731. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23732. //update the internal rotation matrix
  23733. body.body.syncShapes();
  23734. }
  23735. this._registeredMeshes.push({
  23736. mesh: mesh,
  23737. body: body,
  23738. delta: deltaPosition
  23739. });
  23740. return body;
  23741. };
  23742. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23743. var types = [], sizes = [], positions = [], rotations = [];
  23744. var initialMesh = parts[0].mesh;
  23745. for (var index = 0; index < parts.length; index++) {
  23746. var part = parts[index];
  23747. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23748. types.push(bodyParameters.type);
  23749. sizes.push.apply(sizes, bodyParameters.size);
  23750. positions.push.apply(positions, bodyParameters.pos);
  23751. rotations.push.apply(rotations, bodyParameters.rot);
  23752. }
  23753. var body = new OIMO.Body({
  23754. type: types,
  23755. size: sizes,
  23756. pos: positions,
  23757. rot: rotations,
  23758. move: options.mass != 0,
  23759. config: [options.mass, options.friction, options.restitution],
  23760. world: this._world
  23761. });
  23762. this._registeredMeshes.push({
  23763. mesh: initialMesh,
  23764. body: body
  23765. });
  23766. return body;
  23767. };
  23768. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23769. var bodyParameters = null;
  23770. var mesh = part.mesh;
  23771. // We need the bounding box/sphere info to compute the physics body
  23772. mesh.computeWorldMatrix();
  23773. switch (part.impostor) {
  23774. case BABYLON.PhysicsEngine.SphereImpostor:
  23775. var bbox = mesh.getBoundingInfo().boundingBox;
  23776. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23777. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23778. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23779. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23780. bodyParameters = {
  23781. type: 'sphere',
  23782. /* bug with oimo : sphere needs 3 sizes in this case */
  23783. size: [size, -1, -1],
  23784. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23785. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23786. };
  23787. break;
  23788. case BABYLON.PhysicsEngine.PlaneImpostor:
  23789. case BABYLON.PhysicsEngine.BoxImpostor:
  23790. bbox = mesh.getBoundingInfo().boundingBox;
  23791. var min = bbox.minimumWorld;
  23792. var max = bbox.maximumWorld;
  23793. var box = max.subtract(min);
  23794. var sizeX = this._checkWithEpsilon(box.x);
  23795. var sizeY = this._checkWithEpsilon(box.y);
  23796. var sizeZ = this._checkWithEpsilon(box.z);
  23797. var relativePosition = mesh.position;
  23798. bodyParameters = {
  23799. type: 'box',
  23800. size: [sizeX, sizeY, sizeZ],
  23801. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23802. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23803. };
  23804. break;
  23805. }
  23806. return bodyParameters;
  23807. };
  23808. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23809. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23810. var registeredMesh = this._registeredMeshes[index];
  23811. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23812. if (registeredMesh.body) {
  23813. this._world.removeRigidBody(registeredMesh.body.body);
  23814. this._unbindBody(registeredMesh.body);
  23815. }
  23816. this._registeredMeshes.splice(index, 1);
  23817. return;
  23818. }
  23819. }
  23820. };
  23821. OimoJSPlugin.prototype._unbindBody = function (body) {
  23822. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23823. var registeredMesh = this._registeredMeshes[index];
  23824. if (registeredMesh.body === body) {
  23825. registeredMesh.body = null;
  23826. }
  23827. }
  23828. };
  23829. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23830. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23831. var registeredMesh = this._registeredMeshes[index];
  23832. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23833. // Get object mass to have a behaviour similar to cannon.js
  23834. var mass = registeredMesh.body.body.massInfo.mass;
  23835. // The force is scaled with the mass of object
  23836. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23837. return;
  23838. }
  23839. }
  23840. };
  23841. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23842. var body1 = null, body2 = null;
  23843. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23844. var registeredMesh = this._registeredMeshes[index];
  23845. if (registeredMesh.mesh === mesh1) {
  23846. body1 = registeredMesh.body.body;
  23847. }
  23848. else if (registeredMesh.mesh === mesh2) {
  23849. body2 = registeredMesh.body.body;
  23850. }
  23851. }
  23852. if (!body1 || !body2) {
  23853. return false;
  23854. }
  23855. if (!options) {
  23856. options = {};
  23857. }
  23858. new OIMO.Link({
  23859. type: options.type,
  23860. body1: body1,
  23861. body2: body2,
  23862. min: options.min,
  23863. max: options.max,
  23864. axe1: options.axe1,
  23865. axe2: options.axe2,
  23866. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23867. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23868. collision: options.collision,
  23869. spring: options.spring,
  23870. world: this._world
  23871. });
  23872. return true;
  23873. };
  23874. OimoJSPlugin.prototype.dispose = function () {
  23875. this._world.clear();
  23876. while (this._registeredMeshes.length) {
  23877. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23878. }
  23879. };
  23880. OimoJSPlugin.prototype.isSupported = function () {
  23881. return OIMO !== undefined;
  23882. };
  23883. OimoJSPlugin.prototype._getLastShape = function (body) {
  23884. var lastShape = body.shapes;
  23885. while (lastShape.next) {
  23886. lastShape = lastShape.next;
  23887. }
  23888. return lastShape;
  23889. };
  23890. OimoJSPlugin.prototype.runOneStep = function (time) {
  23891. this._world.step();
  23892. // Update the position of all registered meshes
  23893. var i = this._registeredMeshes.length;
  23894. var m;
  23895. while (i--) {
  23896. var body = this._registeredMeshes[i].body.body;
  23897. var mesh = this._registeredMeshes[i].mesh;
  23898. var delta = this._registeredMeshes[i].delta;
  23899. if (!body.sleeping) {
  23900. if (body.shapes.next) {
  23901. var parentShape = this._getLastShape(body);
  23902. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23903. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23904. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23905. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23906. if (!mesh.rotationQuaternion) {
  23907. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23908. }
  23909. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23910. mesh.computeWorldMatrix();
  23911. }
  23912. else {
  23913. m = body.getMatrix();
  23914. mtx = BABYLON.Matrix.FromArray(m);
  23915. // Body position
  23916. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23917. if (!delta) {
  23918. mesh.position.x = bodyX;
  23919. mesh.position.y = bodyY;
  23920. mesh.position.z = bodyZ;
  23921. }
  23922. else {
  23923. mesh.position.x = bodyX + delta.x;
  23924. mesh.position.y = bodyY + delta.y;
  23925. mesh.position.z = bodyZ + delta.z;
  23926. }
  23927. if (!mesh.rotationQuaternion) {
  23928. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23929. }
  23930. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23931. mesh.computeWorldMatrix();
  23932. }
  23933. }
  23934. }
  23935. };
  23936. return OimoJSPlugin;
  23937. })();
  23938. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23939. })(BABYLON || (BABYLON = {}));
  23940. var BABYLON;
  23941. (function (BABYLON) {
  23942. var PhysicsEngine = (function () {
  23943. function PhysicsEngine(plugin) {
  23944. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23945. }
  23946. PhysicsEngine.prototype._initialize = function (gravity) {
  23947. this._currentPlugin.initialize();
  23948. this._setGravity(gravity);
  23949. };
  23950. PhysicsEngine.prototype._runOneStep = function (delta) {
  23951. if (delta > 0.1) {
  23952. delta = 0.1;
  23953. }
  23954. else if (delta <= 0) {
  23955. delta = 1.0 / 60.0;
  23956. }
  23957. this._currentPlugin.runOneStep(delta);
  23958. };
  23959. PhysicsEngine.prototype._setGravity = function (gravity) {
  23960. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23961. this._currentPlugin.setGravity(this.gravity);
  23962. };
  23963. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23964. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23965. };
  23966. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23967. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23968. };
  23969. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23970. this._currentPlugin.unregisterMesh(mesh);
  23971. };
  23972. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23973. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23974. };
  23975. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23976. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23977. };
  23978. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23979. this._currentPlugin.updateBodyPosition(mesh);
  23980. };
  23981. PhysicsEngine.prototype.dispose = function () {
  23982. this._currentPlugin.dispose();
  23983. };
  23984. PhysicsEngine.prototype.isSupported = function () {
  23985. return this._currentPlugin.isSupported();
  23986. };
  23987. // Statics
  23988. PhysicsEngine.NoImpostor = 0;
  23989. PhysicsEngine.SphereImpostor = 1;
  23990. PhysicsEngine.BoxImpostor = 2;
  23991. PhysicsEngine.PlaneImpostor = 3;
  23992. PhysicsEngine.MeshImpostor = 4;
  23993. PhysicsEngine.CapsuleImpostor = 5;
  23994. PhysicsEngine.ConeImpostor = 6;
  23995. PhysicsEngine.CylinderImpostor = 7;
  23996. PhysicsEngine.ConvexHullImpostor = 8;
  23997. PhysicsEngine.Epsilon = 0.001;
  23998. return PhysicsEngine;
  23999. })();
  24000. BABYLON.PhysicsEngine = PhysicsEngine;
  24001. })(BABYLON || (BABYLON = {}));
  24002. var BABYLON;
  24003. (function (BABYLON) {
  24004. var serializeLight = function (light) {
  24005. var serializationObject = {};
  24006. serializationObject.name = light.name;
  24007. serializationObject.id = light.id;
  24008. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24009. if (light instanceof BABYLON.PointLight) {
  24010. serializationObject.type = 0;
  24011. serializationObject.position = (light).position.asArray();
  24012. }
  24013. else if (light instanceof BABYLON.DirectionalLight) {
  24014. serializationObject.type = 1;
  24015. var directionalLight = light;
  24016. serializationObject.position = directionalLight.position.asArray();
  24017. serializationObject.direction = directionalLight.direction.asArray();
  24018. }
  24019. else if (light instanceof BABYLON.SpotLight) {
  24020. serializationObject.type = 2;
  24021. var spotLight = light;
  24022. serializationObject.position = spotLight.position.asArray();
  24023. serializationObject.direction = spotLight.position.asArray();
  24024. serializationObject.angle = spotLight.angle;
  24025. serializationObject.exponent = spotLight.exponent;
  24026. }
  24027. else if (light instanceof BABYLON.HemisphericLight) {
  24028. serializationObject.type = 3;
  24029. var hemisphericLight = light;
  24030. serializationObject.direction = hemisphericLight.direction.asArray();
  24031. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24032. }
  24033. if (light.intensity) {
  24034. serializationObject.intensity = light.intensity;
  24035. }
  24036. serializationObject.range = light.range;
  24037. serializationObject.diffuse = light.diffuse.asArray();
  24038. serializationObject.specular = light.specular.asArray();
  24039. return serializationObject;
  24040. };
  24041. var serializeFresnelParameter = function (fresnelParameter) {
  24042. var serializationObject = {};
  24043. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24044. serializationObject.leftColor = fresnelParameter.leftColor;
  24045. serializationObject.rightColor = fresnelParameter.rightColor;
  24046. serializationObject.bias = fresnelParameter.bias;
  24047. serializationObject.power = fresnelParameter.power;
  24048. return serializationObject;
  24049. };
  24050. var serializeAnimation;
  24051. var appendAnimations = function (source, destination) {
  24052. if (source.animations) {
  24053. destination.animations = [];
  24054. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24055. var animation = source.animations[animationIndex];
  24056. destination.animations.push(serializeAnimation(animation));
  24057. }
  24058. }
  24059. };
  24060. var serializeCamera = function (camera) {
  24061. var serializationObject = {};
  24062. serializationObject.name = camera.name;
  24063. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24064. serializationObject.id = camera.id;
  24065. serializationObject.position = camera.position.asArray();
  24066. // Parent
  24067. if (camera.parent) {
  24068. serializationObject.parentId = camera.parent.id;
  24069. }
  24070. serializationObject.fov = camera.fov;
  24071. serializationObject.minZ = camera.minZ;
  24072. serializationObject.maxZ = camera.maxZ;
  24073. serializationObject.inertia = camera.inertia;
  24074. //setting the type
  24075. if (camera instanceof BABYLON.FreeCamera) {
  24076. serializationObject.type = "FreeCamera";
  24077. }
  24078. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24079. serializationObject.type = "ArcRotateCamera";
  24080. }
  24081. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24082. serializationObject.type = "AnaglyphArcRotateCamera";
  24083. }
  24084. else if (camera instanceof BABYLON.GamepadCamera) {
  24085. serializationObject.type = "GamepadCamera";
  24086. }
  24087. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24088. serializationObject.type = "AnaglyphFreeCamera";
  24089. }
  24090. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24091. serializationObject.type = "DeviceOrientationCamera";
  24092. }
  24093. else if (camera instanceof BABYLON.FollowCamera) {
  24094. serializationObject.type = "FollowCamera";
  24095. }
  24096. else if (camera instanceof BABYLON.TouchCamera) {
  24097. serializationObject.type = "TouchCamera";
  24098. }
  24099. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24100. serializationObject.type = "VirtualJoysticksCamera";
  24101. }
  24102. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24103. serializationObject.type = "WebVRFreeCamera";
  24104. }
  24105. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24106. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24107. }
  24108. //special properties of specific cameras
  24109. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24110. var arcCamera = camera;
  24111. serializationObject.alpha = arcCamera.alpha;
  24112. serializationObject.beta = arcCamera.beta;
  24113. serializationObject.radius = arcCamera.radius;
  24114. if (arcCamera.target && arcCamera.target.id) {
  24115. serializationObject.lockedTargetId = arcCamera.target.id;
  24116. }
  24117. }
  24118. else if (camera instanceof BABYLON.FollowCamera) {
  24119. var followCam = camera;
  24120. serializationObject.radius = followCam.radius;
  24121. serializationObject.heightOffset = followCam.heightOffset;
  24122. serializationObject.rotationOffset = followCam.rotationOffset;
  24123. }
  24124. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24125. //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.
  24126. if (camera['_interaxialDistance'] !== undefined) {
  24127. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24128. }
  24129. }
  24130. //general properties that not all cameras have. The [] is due to typescript's type safety
  24131. if (camera['speed'] !== undefined) {
  24132. serializationObject.speed = camera['speed'];
  24133. }
  24134. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24135. serializationObject.target = camera['target'].asArray();
  24136. }
  24137. // Target
  24138. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24139. serializationObject.rotation = camera['rotation'].asArray();
  24140. }
  24141. // Locked target
  24142. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24143. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24144. }
  24145. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24146. serializationObject.applyGravity = camera['applyGravity'] || false;
  24147. if (camera['ellipsoid']) {
  24148. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24149. }
  24150. // Animations
  24151. appendAnimations(camera, serializationObject);
  24152. // Layer mask
  24153. serializationObject.layerMask = camera.layerMask;
  24154. return serializationObject;
  24155. };
  24156. serializeAnimation = function (animation) {
  24157. var serializationObject = {};
  24158. serializationObject.name = animation.name;
  24159. serializationObject.property = animation.targetProperty;
  24160. serializationObject.framePerSecond = animation.framePerSecond;
  24161. serializationObject.dataType = animation.dataType;
  24162. serializationObject.loopBehavior = animation.loopMode;
  24163. var dataType = animation.dataType;
  24164. serializationObject.keys = [];
  24165. var keys = animation.getKeys();
  24166. for (var index = 0; index < keys.length; index++) {
  24167. var animationKey = keys[index];
  24168. var key = {};
  24169. key.frame = animationKey.frame;
  24170. switch (dataType) {
  24171. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24172. key.values = [animationKey.value];
  24173. break;
  24174. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24175. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24176. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24177. key.values = animationKey.value.asArray();
  24178. break;
  24179. }
  24180. serializationObject.keys.push(key);
  24181. }
  24182. return serializationObject;
  24183. };
  24184. var serializeMultiMaterial = function (material) {
  24185. var serializationObject = {};
  24186. serializationObject.name = material.name;
  24187. serializationObject.id = material.id;
  24188. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24189. serializationObject.materials = [];
  24190. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24191. var subMat = material.subMaterials[matIndex];
  24192. if (subMat) {
  24193. serializationObject.materials.push(subMat.id);
  24194. }
  24195. else {
  24196. serializationObject.materials.push(null);
  24197. }
  24198. }
  24199. return serializationObject;
  24200. };
  24201. var serializeTexture;
  24202. var serializeMaterial = function (material) {
  24203. var serializationObject = {};
  24204. serializationObject.name = material.name;
  24205. serializationObject.ambient = material.ambientColor.asArray();
  24206. serializationObject.diffuse = material.diffuseColor.asArray();
  24207. serializationObject.specular = material.specularColor.asArray();
  24208. serializationObject.specularPower = material.specularPower;
  24209. serializationObject.emissive = material.emissiveColor.asArray();
  24210. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24211. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24212. serializationObject.alpha = material.alpha;
  24213. serializationObject.id = material.id;
  24214. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24215. serializationObject.backFaceCulling = material.backFaceCulling;
  24216. if (material.diffuseTexture) {
  24217. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24218. }
  24219. if (material.diffuseFresnelParameters) {
  24220. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24221. }
  24222. if (material.ambientTexture) {
  24223. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24224. }
  24225. if (material.opacityTexture) {
  24226. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24227. }
  24228. if (material.opacityFresnelParameters) {
  24229. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24230. }
  24231. if (material.reflectionTexture) {
  24232. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24233. }
  24234. if (material.reflectionFresnelParameters) {
  24235. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24236. }
  24237. if (material.emissiveTexture) {
  24238. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24239. }
  24240. if (material.lightmapTexture) {
  24241. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24242. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24243. }
  24244. if (material.emissiveFresnelParameters) {
  24245. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24246. }
  24247. if (material.specularTexture) {
  24248. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24249. }
  24250. if (material.bumpTexture) {
  24251. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24252. }
  24253. return serializationObject;
  24254. };
  24255. serializeTexture = function (texture) {
  24256. var serializationObject = {};
  24257. if (!texture.name) {
  24258. return null;
  24259. }
  24260. if (texture instanceof BABYLON.CubeTexture) {
  24261. serializationObject.name = texture.name;
  24262. serializationObject.hasAlpha = texture.hasAlpha;
  24263. serializationObject.isCube = true;
  24264. serializationObject.level = texture.level;
  24265. serializationObject.coordinatesMode = texture.coordinatesMode;
  24266. return serializationObject;
  24267. }
  24268. var index;
  24269. if (texture instanceof BABYLON.MirrorTexture) {
  24270. var mirrorTexture = texture;
  24271. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24272. serializationObject.renderList = [];
  24273. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24274. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24275. }
  24276. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24277. }
  24278. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24279. var renderTargetTexture = texture;
  24280. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24281. serializationObject.renderList = [];
  24282. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24283. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24284. }
  24285. }
  24286. var regularTexture = texture;
  24287. serializationObject.name = texture.name;
  24288. serializationObject.hasAlpha = texture.hasAlpha;
  24289. serializationObject.level = texture.level;
  24290. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24291. serializationObject.coordinatesMode = texture.coordinatesMode;
  24292. serializationObject.uOffset = regularTexture.uOffset;
  24293. serializationObject.vOffset = regularTexture.vOffset;
  24294. serializationObject.uScale = regularTexture.uScale;
  24295. serializationObject.vScale = regularTexture.vScale;
  24296. serializationObject.uAng = regularTexture.uAng;
  24297. serializationObject.vAng = regularTexture.vAng;
  24298. serializationObject.wAng = regularTexture.wAng;
  24299. serializationObject.wrapU = texture.wrapU;
  24300. serializationObject.wrapV = texture.wrapV;
  24301. // Animations
  24302. appendAnimations(texture, serializationObject);
  24303. return serializationObject;
  24304. };
  24305. var serializeSkeleton = function (skeleton) {
  24306. var serializationObject = {};
  24307. serializationObject.name = skeleton.name;
  24308. serializationObject.id = skeleton.id;
  24309. serializationObject.bones = [];
  24310. for (var index = 0; index < skeleton.bones.length; index++) {
  24311. var bone = skeleton.bones[index];
  24312. var serializedBone = {
  24313. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24314. name: bone.name,
  24315. matrix: bone.getLocalMatrix().toArray()
  24316. };
  24317. serializationObject.bones.push(serializedBone);
  24318. if (bone.animations && bone.animations.length > 0) {
  24319. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24320. }
  24321. }
  24322. return serializationObject;
  24323. };
  24324. var serializeParticleSystem = function (particleSystem) {
  24325. var serializationObject = {};
  24326. serializationObject.emitterId = particleSystem.emitter.id;
  24327. serializationObject.capacity = particleSystem.getCapacity();
  24328. if (particleSystem.particleTexture) {
  24329. serializationObject.textureName = particleSystem.particleTexture.name;
  24330. }
  24331. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24332. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24333. serializationObject.minSize = particleSystem.minSize;
  24334. serializationObject.maxSize = particleSystem.maxSize;
  24335. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24336. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24337. serializationObject.emitRate = particleSystem.emitRate;
  24338. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24339. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24340. serializationObject.gravity = particleSystem.gravity.asArray();
  24341. serializationObject.direction1 = particleSystem.direction1.asArray();
  24342. serializationObject.direction2 = particleSystem.direction2.asArray();
  24343. serializationObject.color1 = particleSystem.color1.asArray();
  24344. serializationObject.color2 = particleSystem.color2.asArray();
  24345. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24346. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24347. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24348. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24349. serializationObject.blendMode = particleSystem.blendMode;
  24350. return serializationObject;
  24351. };
  24352. var serializeLensFlareSystem = function (lensFlareSystem) {
  24353. var serializationObject = {};
  24354. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24355. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24356. serializationObject.flares = [];
  24357. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24358. var flare = lensFlareSystem.lensFlares[index];
  24359. serializationObject.flares.push({
  24360. size: flare.size,
  24361. position: flare.position,
  24362. color: flare.color.asArray(),
  24363. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24364. });
  24365. }
  24366. return serializationObject;
  24367. };
  24368. var serializeShadowGenerator = function (light) {
  24369. var serializationObject = {};
  24370. var shadowGenerator = light.getShadowGenerator();
  24371. serializationObject.lightId = light.id;
  24372. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24373. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24374. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24375. serializationObject.renderList = [];
  24376. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24377. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24378. serializationObject.renderList.push(mesh.id);
  24379. }
  24380. return serializationObject;
  24381. };
  24382. var serializedGeometries = [];
  24383. var serializeVertexData;
  24384. var serializeTorusKnot;
  24385. var serializePlane;
  24386. var serializeGround;
  24387. var serializeTorus;
  24388. var serializeCylinder;
  24389. var serializeSphere;
  24390. var serializeBox;
  24391. var serializeGeometry = function (geometry, serializationGeometries) {
  24392. if (serializedGeometries[geometry.id]) {
  24393. return;
  24394. }
  24395. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24396. serializationGeometries.boxes.push(serializeBox(geometry));
  24397. }
  24398. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24399. serializationGeometries.spheres.push(serializeSphere(geometry));
  24400. }
  24401. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24402. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24403. }
  24404. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24405. serializationGeometries.toruses.push(serializeTorus(geometry));
  24406. }
  24407. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24408. serializationGeometries.grounds.push(serializeGround(geometry));
  24409. }
  24410. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24411. serializationGeometries.planes.push(serializePlane(geometry));
  24412. }
  24413. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24414. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24415. }
  24416. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24417. throw new Error("Unknown primitive type");
  24418. }
  24419. else {
  24420. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24421. }
  24422. serializedGeometries[geometry.id] = true;
  24423. };
  24424. var serializeGeometryBase = function (geometry) {
  24425. var serializationObject = {};
  24426. serializationObject.id = geometry.id;
  24427. if (BABYLON.Tags.HasTags(geometry)) {
  24428. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24429. }
  24430. return serializationObject;
  24431. };
  24432. serializeVertexData = function (vertexData) {
  24433. var serializationObject = serializeGeometryBase(vertexData);
  24434. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24435. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24436. }
  24437. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24438. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24439. }
  24440. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24441. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24442. }
  24443. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24444. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24445. }
  24446. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24447. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24448. }
  24449. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24450. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24451. }
  24452. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24453. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24454. }
  24455. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24456. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24457. }
  24458. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24459. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24460. }
  24461. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24462. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24463. serializationObject.matricesIndices._isExpanded = true;
  24464. }
  24465. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24466. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24467. }
  24468. serializationObject.indices = vertexData.getIndices();
  24469. return serializationObject;
  24470. };
  24471. var serializePrimitive = function (primitive) {
  24472. var serializationObject = serializeGeometryBase(primitive);
  24473. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24474. return serializationObject;
  24475. };
  24476. serializeBox = function (box) {
  24477. var serializationObject = serializePrimitive(box);
  24478. serializationObject.size = box.size;
  24479. return serializationObject;
  24480. };
  24481. serializeSphere = function (sphere) {
  24482. var serializationObject = serializePrimitive(sphere);
  24483. serializationObject.segments = sphere.segments;
  24484. serializationObject.diameter = sphere.diameter;
  24485. return serializationObject;
  24486. };
  24487. serializeCylinder = function (cylinder) {
  24488. var serializationObject = serializePrimitive(cylinder);
  24489. serializationObject.height = cylinder.height;
  24490. serializationObject.diameterTop = cylinder.diameterTop;
  24491. serializationObject.diameterBottom = cylinder.diameterBottom;
  24492. serializationObject.tessellation = cylinder.tessellation;
  24493. return serializationObject;
  24494. };
  24495. serializeTorus = function (torus) {
  24496. var serializationObject = serializePrimitive(torus);
  24497. serializationObject.diameter = torus.diameter;
  24498. serializationObject.thickness = torus.thickness;
  24499. serializationObject.tessellation = torus.tessellation;
  24500. return serializationObject;
  24501. };
  24502. serializeGround = function (ground) {
  24503. var serializationObject = serializePrimitive(ground);
  24504. serializationObject.width = ground.width;
  24505. serializationObject.height = ground.height;
  24506. serializationObject.subdivisions = ground.subdivisions;
  24507. return serializationObject;
  24508. };
  24509. serializePlane = function (plane) {
  24510. var serializationObject = serializePrimitive(plane);
  24511. serializationObject.size = plane.size;
  24512. return serializationObject;
  24513. };
  24514. serializeTorusKnot = function (torusKnot) {
  24515. var serializationObject = serializePrimitive(torusKnot);
  24516. serializationObject.radius = torusKnot.radius;
  24517. serializationObject.tube = torusKnot.tube;
  24518. serializationObject.radialSegments = torusKnot.radialSegments;
  24519. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24520. serializationObject.p = torusKnot.p;
  24521. serializationObject.q = torusKnot.q;
  24522. return serializationObject;
  24523. };
  24524. var serializeMesh = function (mesh, serializationScene) {
  24525. var serializationObject = {};
  24526. serializationObject.name = mesh.name;
  24527. serializationObject.id = mesh.id;
  24528. if (BABYLON.Tags.HasTags(mesh)) {
  24529. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24530. }
  24531. serializationObject.position = mesh.position.asArray();
  24532. if (mesh.rotationQuaternion) {
  24533. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24534. }
  24535. else if (mesh.rotation) {
  24536. serializationObject.rotation = mesh.rotation.asArray();
  24537. }
  24538. serializationObject.scaling = mesh.scaling.asArray();
  24539. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24540. serializationObject.isEnabled = mesh.isEnabled();
  24541. serializationObject.isVisible = mesh.isVisible;
  24542. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24543. serializationObject.pickable = mesh.isPickable;
  24544. serializationObject.receiveShadows = mesh.receiveShadows;
  24545. serializationObject.billboardMode = mesh.billboardMode;
  24546. serializationObject.visibility = mesh.visibility;
  24547. serializationObject.checkCollisions = mesh.checkCollisions;
  24548. // Parent
  24549. if (mesh.parent) {
  24550. serializationObject.parentId = mesh.parent.id;
  24551. }
  24552. // Geometry
  24553. var geometry = mesh._geometry;
  24554. if (geometry) {
  24555. var geometryId = geometry.id;
  24556. serializationObject.geometryId = geometryId;
  24557. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24558. // 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
  24559. serializeGeometry(geometry, serializationScene.geometries);
  24560. }
  24561. // SubMeshes
  24562. serializationObject.subMeshes = [];
  24563. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24564. var subMesh = mesh.subMeshes[subIndex];
  24565. serializationObject.subMeshes.push({
  24566. materialIndex: subMesh.materialIndex,
  24567. verticesStart: subMesh.verticesStart,
  24568. verticesCount: subMesh.verticesCount,
  24569. indexStart: subMesh.indexStart,
  24570. indexCount: subMesh.indexCount
  24571. });
  24572. }
  24573. }
  24574. // Material
  24575. if (mesh.material) {
  24576. serializationObject.materialId = mesh.material.id;
  24577. }
  24578. else {
  24579. mesh.material = null;
  24580. }
  24581. // Skeleton
  24582. if (mesh.skeleton) {
  24583. serializationObject.skeletonId = mesh.skeleton.id;
  24584. }
  24585. // Physics
  24586. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24587. serializationObject.physicsMass = mesh.getPhysicsMass();
  24588. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24589. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24590. switch (mesh.getPhysicsImpostor()) {
  24591. case BABYLON.PhysicsEngine.BoxImpostor:
  24592. serializationObject.physicsImpostor = 1;
  24593. break;
  24594. case BABYLON.PhysicsEngine.SphereImpostor:
  24595. serializationObject.physicsImpostor = 2;
  24596. break;
  24597. }
  24598. }
  24599. // Instances
  24600. serializationObject.instances = [];
  24601. for (var index = 0; index < mesh.instances.length; index++) {
  24602. var instance = mesh.instances[index];
  24603. var serializationInstance = {
  24604. name: instance.name,
  24605. position: instance.position,
  24606. rotation: instance.rotation,
  24607. rotationQuaternion: instance.rotationQuaternion,
  24608. scaling: instance.scaling
  24609. };
  24610. serializationObject.instances.push(serializationInstance);
  24611. // Animations
  24612. appendAnimations(instance, serializationInstance);
  24613. }
  24614. // Animations
  24615. appendAnimations(mesh, serializationObject);
  24616. // Layer mask
  24617. serializationObject.layerMask = mesh.layerMask;
  24618. return serializationObject;
  24619. };
  24620. var finalizeSingleMesh = function (mesh, serializationObject) {
  24621. //only works if the mesh is already loaded
  24622. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24623. //serialize material
  24624. if (mesh.material) {
  24625. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24626. serializationObject.materials = serializationObject.materials || [];
  24627. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24628. serializationObject.materials.push(serializeMaterial(mesh.material));
  24629. }
  24630. }
  24631. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24632. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24633. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24634. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24635. }
  24636. }
  24637. }
  24638. //serialize geometry
  24639. var geometry = mesh._geometry;
  24640. if (geometry) {
  24641. if (!serializationObject.geometries) {
  24642. serializationObject.geometries = {};
  24643. serializationObject.geometries.boxes = [];
  24644. serializationObject.geometries.spheres = [];
  24645. serializationObject.geometries.cylinders = [];
  24646. serializationObject.geometries.toruses = [];
  24647. serializationObject.geometries.grounds = [];
  24648. serializationObject.geometries.planes = [];
  24649. serializationObject.geometries.torusKnots = [];
  24650. serializationObject.geometries.vertexData = [];
  24651. }
  24652. serializeGeometry(geometry, serializationObject.geometries);
  24653. }
  24654. // Skeletons
  24655. if (mesh.skeleton) {
  24656. serializationObject.skeletons = serializationObject.skeletons || [];
  24657. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24658. }
  24659. //serialize the actual mesh
  24660. serializationObject.meshes = serializationObject.meshes || [];
  24661. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24662. }
  24663. };
  24664. var SceneSerializer = (function () {
  24665. function SceneSerializer() {
  24666. }
  24667. SceneSerializer.Serialize = function (scene) {
  24668. var serializationObject = {};
  24669. // Scene
  24670. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24671. serializationObject.autoClear = scene.autoClear;
  24672. serializationObject.clearColor = scene.clearColor.asArray();
  24673. serializationObject.ambientColor = scene.ambientColor.asArray();
  24674. serializationObject.gravity = scene.gravity.asArray();
  24675. // Fog
  24676. if (scene.fogMode && scene.fogMode !== 0) {
  24677. serializationObject.fogMode = scene.fogMode;
  24678. serializationObject.fogColor = scene.fogColor.asArray();
  24679. serializationObject.fogStart = scene.fogStart;
  24680. serializationObject.fogEnd = scene.fogEnd;
  24681. serializationObject.fogDensity = scene.fogDensity;
  24682. }
  24683. // Lights
  24684. serializationObject.lights = [];
  24685. var index;
  24686. var light;
  24687. for (index = 0; index < scene.lights.length; index++) {
  24688. light = scene.lights[index];
  24689. serializationObject.lights.push(serializeLight(light));
  24690. }
  24691. // Cameras
  24692. serializationObject.cameras = [];
  24693. for (index = 0; index < scene.cameras.length; index++) {
  24694. var camera = scene.cameras[index];
  24695. serializationObject.cameras.push(serializeCamera(camera));
  24696. }
  24697. if (scene.activeCamera) {
  24698. serializationObject.activeCameraID = scene.activeCamera.id;
  24699. }
  24700. // Materials
  24701. serializationObject.materials = [];
  24702. serializationObject.multiMaterials = [];
  24703. var material;
  24704. for (index = 0; index < scene.materials.length; index++) {
  24705. material = scene.materials[index];
  24706. serializationObject.materials.push(serializeMaterial(material));
  24707. }
  24708. // MultiMaterials
  24709. serializationObject.multiMaterials = [];
  24710. for (index = 0; index < scene.multiMaterials.length; index++) {
  24711. var multiMaterial = scene.multiMaterials[index];
  24712. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  24713. }
  24714. for (index = 0; index < scene.materials.length; index++) {
  24715. material = scene.materials[index];
  24716. if (material instanceof BABYLON.StandardMaterial) {
  24717. serializationObject.materials.push(serializeMaterial(material));
  24718. }
  24719. else if (material instanceof BABYLON.MultiMaterial) {
  24720. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24721. }
  24722. }
  24723. // Skeletons
  24724. serializationObject.skeletons = [];
  24725. for (index = 0; index < scene.skeletons.length; index++) {
  24726. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24727. }
  24728. // Geometries
  24729. serializationObject.geometries = {};
  24730. serializationObject.geometries.boxes = [];
  24731. serializationObject.geometries.spheres = [];
  24732. serializationObject.geometries.cylinders = [];
  24733. serializationObject.geometries.toruses = [];
  24734. serializationObject.geometries.grounds = [];
  24735. serializationObject.geometries.planes = [];
  24736. serializationObject.geometries.torusKnots = [];
  24737. serializationObject.geometries.vertexData = [];
  24738. serializedGeometries = [];
  24739. var geometries = scene.getGeometries();
  24740. for (index = 0; index < geometries.length; index++) {
  24741. var geometry = geometries[index];
  24742. if (geometry.isReady()) {
  24743. serializeGeometry(geometry, serializationObject.geometries);
  24744. }
  24745. }
  24746. // Meshes
  24747. serializationObject.meshes = [];
  24748. for (index = 0; index < scene.meshes.length; index++) {
  24749. var abstractMesh = scene.meshes[index];
  24750. if (abstractMesh instanceof BABYLON.Mesh) {
  24751. var mesh = abstractMesh;
  24752. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24753. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24754. }
  24755. }
  24756. }
  24757. // Particles Systems
  24758. serializationObject.particleSystems = [];
  24759. for (index = 0; index < scene.particleSystems.length; index++) {
  24760. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24761. }
  24762. // Lens flares
  24763. serializationObject.lensFlareSystems = [];
  24764. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24765. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24766. }
  24767. // Shadows
  24768. serializationObject.shadowGenerators = [];
  24769. for (index = 0; index < scene.lights.length; index++) {
  24770. light = scene.lights[index];
  24771. if (light.getShadowGenerator()) {
  24772. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24773. }
  24774. }
  24775. return serializationObject;
  24776. };
  24777. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24778. if (withParents === void 0) { withParents = false; }
  24779. if (withChildren === void 0) { withChildren = false; }
  24780. var serializationObject = {};
  24781. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24782. if (withParents || withChildren) {
  24783. //deliberate for loop! not for each, appended should be processed as well.
  24784. for (var i = 0; i < toSerialize.length; ++i) {
  24785. if (withChildren) {
  24786. toSerialize[i].getDescendants().forEach(function (node) {
  24787. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24788. toSerialize.push(node);
  24789. }
  24790. });
  24791. }
  24792. //make sure the array doesn't contain the object already
  24793. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24794. toSerialize.push(toSerialize[i].parent);
  24795. }
  24796. }
  24797. }
  24798. toSerialize.forEach(function (mesh) {
  24799. finalizeSingleMesh(mesh, serializationObject);
  24800. });
  24801. return serializationObject;
  24802. };
  24803. return SceneSerializer;
  24804. })();
  24805. BABYLON.SceneSerializer = SceneSerializer;
  24806. })(BABYLON || (BABYLON = {}));
  24807. var BABYLON;
  24808. (function (BABYLON) {
  24809. // Unique ID when we import meshes from Babylon to CSG
  24810. var currentCSGMeshId = 0;
  24811. // # class Vertex
  24812. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24813. // one to provide additional features like texture coordinates and vertex
  24814. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24815. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24816. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24817. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24818. // is not used anywhere else.
  24819. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24820. var Vertex = (function () {
  24821. function Vertex(pos, normal, uv) {
  24822. this.pos = pos;
  24823. this.normal = normal;
  24824. this.uv = uv;
  24825. }
  24826. Vertex.prototype.clone = function () {
  24827. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24828. };
  24829. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24830. // orientation of a polygon is flipped.
  24831. Vertex.prototype.flip = function () {
  24832. this.normal = this.normal.scale(-1);
  24833. };
  24834. // Create a new vertex between this vertex and `other` by linearly
  24835. // interpolating all properties using a parameter of `t`. Subclasses should
  24836. // override this to interpolate additional properties.
  24837. Vertex.prototype.interpolate = function (other, t) {
  24838. 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));
  24839. };
  24840. return Vertex;
  24841. })();
  24842. // # class Plane
  24843. // Represents a plane in 3D space.
  24844. var Plane = (function () {
  24845. function Plane(normal, w) {
  24846. this.normal = normal;
  24847. this.w = w;
  24848. }
  24849. Plane.FromPoints = function (a, b, c) {
  24850. var v0 = c.subtract(a);
  24851. var v1 = b.subtract(a);
  24852. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24853. return null;
  24854. }
  24855. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24856. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24857. };
  24858. Plane.prototype.clone = function () {
  24859. return new Plane(this.normal.clone(), this.w);
  24860. };
  24861. Plane.prototype.flip = function () {
  24862. this.normal.scaleInPlace(-1);
  24863. this.w = -this.w;
  24864. };
  24865. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24866. // fragments in the appropriate lists. Coplanar polygons go into either
  24867. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24868. // respect to this plane. Polygons in front or in back of this plane go into
  24869. // either `front` or `back`.
  24870. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24871. var COPLANAR = 0;
  24872. var FRONT = 1;
  24873. var BACK = 2;
  24874. var SPANNING = 3;
  24875. // Classify each point as well as the entire polygon into one of the above
  24876. // four classes.
  24877. var polygonType = 0;
  24878. var types = [];
  24879. for (var i = 0; i < polygon.vertices.length; i++) {
  24880. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24881. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24882. polygonType |= type;
  24883. types.push(type);
  24884. }
  24885. // Put the polygon in the correct list, splitting it when necessary.
  24886. switch (polygonType) {
  24887. case COPLANAR:
  24888. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24889. break;
  24890. case FRONT:
  24891. front.push(polygon);
  24892. break;
  24893. case BACK:
  24894. back.push(polygon);
  24895. break;
  24896. case SPANNING:
  24897. var f = [], b = [];
  24898. for (i = 0; i < polygon.vertices.length; i++) {
  24899. var j = (i + 1) % polygon.vertices.length;
  24900. var ti = types[i], tj = types[j];
  24901. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24902. if (ti != BACK)
  24903. f.push(vi);
  24904. if (ti != FRONT)
  24905. b.push(ti != BACK ? vi.clone() : vi);
  24906. if ((ti | tj) == SPANNING) {
  24907. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24908. var v = vi.interpolate(vj, t);
  24909. f.push(v);
  24910. b.push(v.clone());
  24911. }
  24912. }
  24913. if (f.length >= 3) {
  24914. var poly = new Polygon(f, polygon.shared);
  24915. if (poly.plane)
  24916. front.push(poly);
  24917. }
  24918. if (b.length >= 3) {
  24919. poly = new Polygon(b, polygon.shared);
  24920. if (poly.plane)
  24921. back.push(poly);
  24922. }
  24923. break;
  24924. }
  24925. };
  24926. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24927. // point is on the plane.
  24928. Plane.EPSILON = 1e-5;
  24929. return Plane;
  24930. })();
  24931. // # class Polygon
  24932. // Represents a convex polygon. The vertices used to initialize a polygon must
  24933. // be coplanar and form a convex loop.
  24934. //
  24935. // Each convex polygon has a `shared` property, which is shared between all
  24936. // polygons that are clones of each other or were split from the same polygon.
  24937. // This can be used to define per-polygon properties (such as surface color).
  24938. var Polygon = (function () {
  24939. function Polygon(vertices, shared) {
  24940. this.vertices = vertices;
  24941. this.shared = shared;
  24942. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24943. }
  24944. Polygon.prototype.clone = function () {
  24945. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24946. return new Polygon(vertices, this.shared);
  24947. };
  24948. Polygon.prototype.flip = function () {
  24949. this.vertices.reverse().map(function (v) { v.flip(); });
  24950. this.plane.flip();
  24951. };
  24952. return Polygon;
  24953. })();
  24954. // # class Node
  24955. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24956. // by picking a polygon to split along. That polygon (and all other coplanar
  24957. // polygons) are added directly to that node and the other polygons are added to
  24958. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24959. // no distinction between internal and leaf nodes.
  24960. var Node = (function () {
  24961. function Node(polygons) {
  24962. this.plane = null;
  24963. this.front = null;
  24964. this.back = null;
  24965. this.polygons = [];
  24966. if (polygons) {
  24967. this.build(polygons);
  24968. }
  24969. }
  24970. Node.prototype.clone = function () {
  24971. var node = new Node();
  24972. node.plane = this.plane && this.plane.clone();
  24973. node.front = this.front && this.front.clone();
  24974. node.back = this.back && this.back.clone();
  24975. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24976. return node;
  24977. };
  24978. // Convert solid space to empty space and empty space to solid space.
  24979. Node.prototype.invert = function () {
  24980. for (var i = 0; i < this.polygons.length; i++) {
  24981. this.polygons[i].flip();
  24982. }
  24983. if (this.plane) {
  24984. this.plane.flip();
  24985. }
  24986. if (this.front) {
  24987. this.front.invert();
  24988. }
  24989. if (this.back) {
  24990. this.back.invert();
  24991. }
  24992. var temp = this.front;
  24993. this.front = this.back;
  24994. this.back = temp;
  24995. };
  24996. // Recursively remove all polygons in `polygons` that are inside this BSP
  24997. // tree.
  24998. Node.prototype.clipPolygons = function (polygons) {
  24999. if (!this.plane)
  25000. return polygons.slice();
  25001. var front = [], back = [];
  25002. for (var i = 0; i < polygons.length; i++) {
  25003. this.plane.splitPolygon(polygons[i], front, back, front, back);
  25004. }
  25005. if (this.front) {
  25006. front = this.front.clipPolygons(front);
  25007. }
  25008. if (this.back) {
  25009. back = this.back.clipPolygons(back);
  25010. }
  25011. else {
  25012. back = [];
  25013. }
  25014. return front.concat(back);
  25015. };
  25016. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25017. // `bsp`.
  25018. Node.prototype.clipTo = function (bsp) {
  25019. this.polygons = bsp.clipPolygons(this.polygons);
  25020. if (this.front)
  25021. this.front.clipTo(bsp);
  25022. if (this.back)
  25023. this.back.clipTo(bsp);
  25024. };
  25025. // Return a list of all polygons in this BSP tree.
  25026. Node.prototype.allPolygons = function () {
  25027. var polygons = this.polygons.slice();
  25028. if (this.front)
  25029. polygons = polygons.concat(this.front.allPolygons());
  25030. if (this.back)
  25031. polygons = polygons.concat(this.back.allPolygons());
  25032. return polygons;
  25033. };
  25034. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25035. // new polygons are filtered down to the bottom of the tree and become new
  25036. // nodes there. Each set of polygons is partitioned using the first polygon
  25037. // (no heuristic is used to pick a good split).
  25038. Node.prototype.build = function (polygons) {
  25039. if (!polygons.length)
  25040. return;
  25041. if (!this.plane)
  25042. this.plane = polygons[0].plane.clone();
  25043. var front = [], back = [];
  25044. for (var i = 0; i < polygons.length; i++) {
  25045. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25046. }
  25047. if (front.length) {
  25048. if (!this.front)
  25049. this.front = new Node();
  25050. this.front.build(front);
  25051. }
  25052. if (back.length) {
  25053. if (!this.back)
  25054. this.back = new Node();
  25055. this.back.build(back);
  25056. }
  25057. };
  25058. return Node;
  25059. })();
  25060. var CSG = (function () {
  25061. function CSG() {
  25062. this.polygons = new Array();
  25063. }
  25064. // Convert BABYLON.Mesh to BABYLON.CSG
  25065. CSG.FromMesh = function (mesh) {
  25066. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25067. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25068. if (mesh instanceof BABYLON.Mesh) {
  25069. mesh.computeWorldMatrix(true);
  25070. matrix = mesh.getWorldMatrix();
  25071. meshPosition = mesh.position.clone();
  25072. meshRotation = mesh.rotation.clone();
  25073. if (mesh.rotationQuaternion) {
  25074. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25075. }
  25076. meshScaling = mesh.scaling.clone();
  25077. }
  25078. else {
  25079. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25080. }
  25081. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25082. var subMeshes = mesh.subMeshes;
  25083. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25084. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25085. vertices = [];
  25086. for (var j = 0; j < 3; j++) {
  25087. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25088. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25089. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25090. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25091. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25092. vertex = new Vertex(position, normal, uv);
  25093. vertices.push(vertex);
  25094. }
  25095. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25096. // To handle the case of degenerated triangle
  25097. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25098. if (polygon.plane)
  25099. polygons.push(polygon);
  25100. }
  25101. }
  25102. var csg = CSG.FromPolygons(polygons);
  25103. csg.matrix = matrix;
  25104. csg.position = meshPosition;
  25105. csg.rotation = meshRotation;
  25106. csg.scaling = meshScaling;
  25107. csg.rotationQuaternion = meshRotationQuaternion;
  25108. currentCSGMeshId++;
  25109. return csg;
  25110. };
  25111. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25112. CSG.FromPolygons = function (polygons) {
  25113. var csg = new CSG();
  25114. csg.polygons = polygons;
  25115. return csg;
  25116. };
  25117. CSG.prototype.clone = function () {
  25118. var csg = new CSG();
  25119. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25120. csg.copyTransformAttributes(this);
  25121. return csg;
  25122. };
  25123. CSG.prototype.toPolygons = function () {
  25124. return this.polygons;
  25125. };
  25126. CSG.prototype.union = function (csg) {
  25127. var a = new Node(this.clone().polygons);
  25128. var b = new Node(csg.clone().polygons);
  25129. a.clipTo(b);
  25130. b.clipTo(a);
  25131. b.invert();
  25132. b.clipTo(a);
  25133. b.invert();
  25134. a.build(b.allPolygons());
  25135. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25136. };
  25137. CSG.prototype.unionInPlace = function (csg) {
  25138. var a = new Node(this.polygons);
  25139. var b = new Node(csg.polygons);
  25140. a.clipTo(b);
  25141. b.clipTo(a);
  25142. b.invert();
  25143. b.clipTo(a);
  25144. b.invert();
  25145. a.build(b.allPolygons());
  25146. this.polygons = a.allPolygons();
  25147. };
  25148. CSG.prototype.subtract = function (csg) {
  25149. var a = new Node(this.clone().polygons);
  25150. var b = new Node(csg.clone().polygons);
  25151. a.invert();
  25152. a.clipTo(b);
  25153. b.clipTo(a);
  25154. b.invert();
  25155. b.clipTo(a);
  25156. b.invert();
  25157. a.build(b.allPolygons());
  25158. a.invert();
  25159. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25160. };
  25161. CSG.prototype.subtractInPlace = function (csg) {
  25162. var a = new Node(this.polygons);
  25163. var b = new Node(csg.polygons);
  25164. a.invert();
  25165. a.clipTo(b);
  25166. b.clipTo(a);
  25167. b.invert();
  25168. b.clipTo(a);
  25169. b.invert();
  25170. a.build(b.allPolygons());
  25171. a.invert();
  25172. this.polygons = a.allPolygons();
  25173. };
  25174. CSG.prototype.intersect = function (csg) {
  25175. var a = new Node(this.clone().polygons);
  25176. var b = new Node(csg.clone().polygons);
  25177. a.invert();
  25178. b.clipTo(a);
  25179. b.invert();
  25180. a.clipTo(b);
  25181. b.clipTo(a);
  25182. a.build(b.allPolygons());
  25183. a.invert();
  25184. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25185. };
  25186. CSG.prototype.intersectInPlace = function (csg) {
  25187. var a = new Node(this.polygons);
  25188. var b = new Node(csg.polygons);
  25189. a.invert();
  25190. b.clipTo(a);
  25191. b.invert();
  25192. a.clipTo(b);
  25193. b.clipTo(a);
  25194. a.build(b.allPolygons());
  25195. a.invert();
  25196. this.polygons = a.allPolygons();
  25197. };
  25198. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25199. // not modified.
  25200. CSG.prototype.inverse = function () {
  25201. var csg = this.clone();
  25202. csg.inverseInPlace();
  25203. return csg;
  25204. };
  25205. CSG.prototype.inverseInPlace = function () {
  25206. this.polygons.map(function (p) { p.flip(); });
  25207. };
  25208. // This is used to keep meshes transformations so they can be restored
  25209. // when we build back a Babylon Mesh
  25210. // NB : All CSG operations are performed in world coordinates
  25211. CSG.prototype.copyTransformAttributes = function (csg) {
  25212. this.matrix = csg.matrix;
  25213. this.position = csg.position;
  25214. this.rotation = csg.rotation;
  25215. this.scaling = csg.scaling;
  25216. this.rotationQuaternion = csg.rotationQuaternion;
  25217. return this;
  25218. };
  25219. // Build Raw mesh from CSG
  25220. // Coordinates here are in world space
  25221. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25222. var matrix = this.matrix.clone();
  25223. matrix.invert();
  25224. 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;
  25225. if (keepSubMeshes) {
  25226. // Sort Polygons, since subMeshes are indices range
  25227. polygons.sort(function (a, b) {
  25228. if (a.shared.meshId === b.shared.meshId) {
  25229. return a.shared.subMeshId - b.shared.subMeshId;
  25230. }
  25231. else {
  25232. return a.shared.meshId - b.shared.meshId;
  25233. }
  25234. });
  25235. }
  25236. for (var i = 0, il = polygons.length; i < il; i++) {
  25237. polygon = polygons[i];
  25238. // Building SubMeshes
  25239. if (!subMesh_dict[polygon.shared.meshId]) {
  25240. subMesh_dict[polygon.shared.meshId] = {};
  25241. }
  25242. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25243. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25244. indexStart: +Infinity,
  25245. indexEnd: -Infinity,
  25246. materialIndex: polygon.shared.materialIndex
  25247. };
  25248. }
  25249. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25250. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25251. polygonIndices[0] = 0;
  25252. polygonIndices[1] = j - 1;
  25253. polygonIndices[2] = j;
  25254. for (var k = 0; k < 3; k++) {
  25255. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25256. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25257. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25258. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25259. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25260. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25261. // Check if 2 points can be merged
  25262. if (!(typeof vertex_idx !== 'undefined' &&
  25263. normals[vertex_idx * 3] === localNormal.x &&
  25264. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25265. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25266. uvs[vertex_idx * 2] === uv.x &&
  25267. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25268. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25269. uvs.push(uv.x, uv.y);
  25270. normals.push(normal.x, normal.y, normal.z);
  25271. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25272. }
  25273. indices.push(vertex_idx);
  25274. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25275. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25276. currentIndex++;
  25277. }
  25278. }
  25279. }
  25280. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25281. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25282. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25283. mesh.setIndices(indices);
  25284. if (keepSubMeshes) {
  25285. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25286. var materialIndexOffset = 0, materialMaxIndex;
  25287. mesh.subMeshes.length = 0;
  25288. for (var m in subMesh_dict) {
  25289. materialMaxIndex = -1;
  25290. for (var sm in subMesh_dict[m]) {
  25291. subMesh_obj = subMesh_dict[m][sm];
  25292. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25293. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25294. }
  25295. materialIndexOffset += ++materialMaxIndex;
  25296. }
  25297. }
  25298. return mesh;
  25299. };
  25300. // Build Mesh from CSG taking material and transforms into account
  25301. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25302. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25303. mesh.material = material;
  25304. mesh.position.copyFrom(this.position);
  25305. mesh.rotation.copyFrom(this.rotation);
  25306. if (this.rotationQuaternion) {
  25307. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25308. }
  25309. mesh.scaling.copyFrom(this.scaling);
  25310. mesh.computeWorldMatrix(true);
  25311. return mesh;
  25312. };
  25313. return CSG;
  25314. })();
  25315. BABYLON.CSG = CSG;
  25316. })(BABYLON || (BABYLON = {}));
  25317. var BABYLON;
  25318. (function (BABYLON) {
  25319. var VRDistortionCorrectionPostProcess = (function (_super) {
  25320. __extends(VRDistortionCorrectionPostProcess, _super);
  25321. //ANY
  25322. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25323. var _this = this;
  25324. _super.call(this, name, "vrDistortionCorrection", [
  25325. 'LensCenter',
  25326. 'Scale',
  25327. 'ScaleIn',
  25328. 'HmdWarpParam'
  25329. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25330. this._isRightEye = isRightEye;
  25331. this._distortionFactors = vrMetrics.distortionK;
  25332. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25333. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25334. this.onSizeChanged = function () {
  25335. _this.aspectRatio = _this.width * .5 / _this.height;
  25336. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25337. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25338. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25339. };
  25340. this.onApply = function (effect) {
  25341. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25342. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25343. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25344. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25345. };
  25346. }
  25347. return VRDistortionCorrectionPostProcess;
  25348. })(BABYLON.PostProcess);
  25349. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25350. })(BABYLON || (BABYLON = {}));
  25351. // Mainly based on these 2 articles :
  25352. // 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
  25353. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25354. var BABYLON;
  25355. (function (BABYLON) {
  25356. (function (JoystickAxis) {
  25357. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25358. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25359. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25360. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25361. var JoystickAxis = BABYLON.JoystickAxis;
  25362. var VirtualJoystick = (function () {
  25363. function VirtualJoystick(leftJoystick) {
  25364. var _this = this;
  25365. if (leftJoystick) {
  25366. this._leftJoystick = true;
  25367. }
  25368. else {
  25369. this._leftJoystick = false;
  25370. }
  25371. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25372. VirtualJoystick._globalJoystickIndex++;
  25373. // By default left & right arrow keys are moving the X
  25374. // and up & down keys are moving the Y
  25375. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25376. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25377. this.reverseLeftRight = false;
  25378. this.reverseUpDown = false;
  25379. // collections of pointers
  25380. this._touches = new BABYLON.SmartCollection();
  25381. this.deltaPosition = BABYLON.Vector3.Zero();
  25382. this._joystickSensibility = 25;
  25383. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25384. this._rotationSpeed = 25;
  25385. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25386. this._rotateOnAxisRelativeToMesh = false;
  25387. this._onResize = function (evt) {
  25388. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25389. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25390. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25391. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25392. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25393. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25394. };
  25395. // injecting a canvas element on top of the canvas 3D game
  25396. if (!VirtualJoystick.vjCanvas) {
  25397. window.addEventListener("resize", this._onResize, false);
  25398. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25399. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25400. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25401. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25402. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25403. VirtualJoystick.vjCanvas.style.width = "100%";
  25404. VirtualJoystick.vjCanvas.style.height = "100%";
  25405. VirtualJoystick.vjCanvas.style.position = "absolute";
  25406. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25407. VirtualJoystick.vjCanvas.style.top = "0px";
  25408. VirtualJoystick.vjCanvas.style.left = "0px";
  25409. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25410. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25411. // Support for jQuery PEP polyfill
  25412. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  25413. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25414. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25415. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25416. document.body.appendChild(VirtualJoystick.vjCanvas);
  25417. }
  25418. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25419. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25420. this.pressed = false;
  25421. // default joystick color
  25422. this._joystickColor = "cyan";
  25423. this._joystickPointerID = -1;
  25424. // current joystick position
  25425. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25426. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25427. // origin joystick position
  25428. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25429. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25430. this._onPointerDownHandlerRef = function (evt) {
  25431. _this._onPointerDown(evt);
  25432. };
  25433. this._onPointerMoveHandlerRef = function (evt) {
  25434. _this._onPointerMove(evt);
  25435. };
  25436. this._onPointerOutHandlerRef = function (evt) {
  25437. _this._onPointerUp(evt);
  25438. };
  25439. this._onPointerUpHandlerRef = function (evt) {
  25440. _this._onPointerUp(evt);
  25441. };
  25442. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25443. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25444. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25445. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25446. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25447. evt.preventDefault(); // Disables system menu
  25448. }, false);
  25449. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25450. }
  25451. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25452. this._joystickSensibility = newJoystickSensibility;
  25453. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25454. };
  25455. VirtualJoystick.prototype._onPointerDown = function (e) {
  25456. var positionOnScreenCondition;
  25457. e.preventDefault();
  25458. if (this._leftJoystick === true) {
  25459. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25460. }
  25461. else {
  25462. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25463. }
  25464. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25465. // First contact will be dedicated to the virtual joystick
  25466. this._joystickPointerID = e.pointerId;
  25467. this._joystickPointerStartPos.x = e.clientX;
  25468. this._joystickPointerStartPos.y = e.clientY;
  25469. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25470. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25471. this._deltaJoystickVector.x = 0;
  25472. this._deltaJoystickVector.y = 0;
  25473. this.pressed = true;
  25474. this._touches.add(e.pointerId.toString(), e);
  25475. }
  25476. else {
  25477. // You can only trigger the action buttons with a joystick declared
  25478. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25479. this._action();
  25480. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25481. }
  25482. }
  25483. };
  25484. VirtualJoystick.prototype._onPointerMove = function (e) {
  25485. // If the current pointer is the one associated to the joystick (first touch contact)
  25486. if (this._joystickPointerID == e.pointerId) {
  25487. this._joystickPointerPos.x = e.clientX;
  25488. this._joystickPointerPos.y = e.clientY;
  25489. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25490. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25491. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25492. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25493. switch (this._axisTargetedByLeftAndRight) {
  25494. case JoystickAxis.X:
  25495. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25496. break;
  25497. case JoystickAxis.Y:
  25498. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25499. break;
  25500. case JoystickAxis.Z:
  25501. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25502. break;
  25503. }
  25504. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25505. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25506. switch (this._axisTargetedByUpAndDown) {
  25507. case JoystickAxis.X:
  25508. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25509. break;
  25510. case JoystickAxis.Y:
  25511. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25512. break;
  25513. case JoystickAxis.Z:
  25514. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25515. break;
  25516. }
  25517. }
  25518. else {
  25519. if (this._touches.item(e.pointerId.toString())) {
  25520. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25521. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25522. }
  25523. }
  25524. };
  25525. VirtualJoystick.prototype._onPointerUp = function (e) {
  25526. if (this._joystickPointerID == e.pointerId) {
  25527. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25528. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25529. this._joystickPointerID = -1;
  25530. this.pressed = false;
  25531. }
  25532. else {
  25533. var touch = this._touches.item(e.pointerId.toString());
  25534. if (touch) {
  25535. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25536. }
  25537. }
  25538. this._deltaJoystickVector.x = 0;
  25539. this._deltaJoystickVector.y = 0;
  25540. this._touches.remove(e.pointerId.toString());
  25541. };
  25542. /**
  25543. * Change the color of the virtual joystick
  25544. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25545. */
  25546. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25547. this._joystickColor = newColor;
  25548. };
  25549. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25550. this._action = action;
  25551. };
  25552. // Define which axis you'd like to control for left & right
  25553. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25554. switch (axis) {
  25555. case JoystickAxis.X:
  25556. case JoystickAxis.Y:
  25557. case JoystickAxis.Z:
  25558. this._axisTargetedByLeftAndRight = axis;
  25559. break;
  25560. default:
  25561. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25562. break;
  25563. }
  25564. };
  25565. // Define which axis you'd like to control for up & down
  25566. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25567. switch (axis) {
  25568. case JoystickAxis.X:
  25569. case JoystickAxis.Y:
  25570. case JoystickAxis.Z:
  25571. this._axisTargetedByUpAndDown = axis;
  25572. break;
  25573. default:
  25574. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25575. break;
  25576. }
  25577. };
  25578. VirtualJoystick.prototype._clearCanvas = function () {
  25579. if (this._leftJoystick) {
  25580. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25581. }
  25582. else {
  25583. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25584. }
  25585. };
  25586. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25587. var _this = this;
  25588. if (this.pressed) {
  25589. this._touches.forEach(function (touch) {
  25590. if (touch.pointerId === _this._joystickPointerID) {
  25591. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25592. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25593. VirtualJoystick.vjCanvasContext.beginPath();
  25594. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25595. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25596. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25597. VirtualJoystick.vjCanvasContext.stroke();
  25598. VirtualJoystick.vjCanvasContext.closePath();
  25599. VirtualJoystick.vjCanvasContext.beginPath();
  25600. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25601. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25602. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25603. VirtualJoystick.vjCanvasContext.stroke();
  25604. VirtualJoystick.vjCanvasContext.closePath();
  25605. VirtualJoystick.vjCanvasContext.beginPath();
  25606. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25607. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25608. VirtualJoystick.vjCanvasContext.stroke();
  25609. VirtualJoystick.vjCanvasContext.closePath();
  25610. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25611. }
  25612. else {
  25613. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25614. VirtualJoystick.vjCanvasContext.beginPath();
  25615. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25616. VirtualJoystick.vjCanvasContext.beginPath();
  25617. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25618. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25619. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25620. VirtualJoystick.vjCanvasContext.stroke();
  25621. VirtualJoystick.vjCanvasContext.closePath();
  25622. touch.prevX = touch.x;
  25623. touch.prevY = touch.y;
  25624. }
  25625. ;
  25626. });
  25627. }
  25628. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25629. };
  25630. VirtualJoystick.prototype.releaseCanvas = function () {
  25631. if (VirtualJoystick.vjCanvas) {
  25632. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25633. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25634. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25635. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25636. window.removeEventListener("resize", this._onResize);
  25637. document.body.removeChild(VirtualJoystick.vjCanvas);
  25638. VirtualJoystick.vjCanvas = null;
  25639. }
  25640. };
  25641. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25642. VirtualJoystick._globalJoystickIndex = 0;
  25643. return VirtualJoystick;
  25644. })();
  25645. BABYLON.VirtualJoystick = VirtualJoystick;
  25646. })(BABYLON || (BABYLON = {}));
  25647. var BABYLON;
  25648. (function (BABYLON) {
  25649. // We're mainly based on the logic defined into the FreeCamera code
  25650. var VirtualJoysticksCamera = (function (_super) {
  25651. __extends(VirtualJoysticksCamera, _super);
  25652. function VirtualJoysticksCamera(name, position, scene) {
  25653. _super.call(this, name, position, scene);
  25654. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25655. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25656. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25657. this._leftjoystick.setJoystickSensibility(0.15);
  25658. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25659. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25660. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25661. this._rightjoystick.reverseUpDown = true;
  25662. this._rightjoystick.setJoystickSensibility(0.05);
  25663. this._rightjoystick.setJoystickColor("yellow");
  25664. }
  25665. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25666. return this._leftjoystick;
  25667. };
  25668. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25669. return this._rightjoystick;
  25670. };
  25671. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25672. var speed = this._computeLocalCameraSpeed() * 50;
  25673. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25674. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25675. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25676. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25677. if (!this._leftjoystick.pressed) {
  25678. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25679. }
  25680. if (!this._rightjoystick.pressed) {
  25681. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25682. }
  25683. _super.prototype._checkInputs.call(this);
  25684. };
  25685. VirtualJoysticksCamera.prototype.dispose = function () {
  25686. this._leftjoystick.releaseCanvas();
  25687. _super.prototype.dispose.call(this);
  25688. };
  25689. return VirtualJoysticksCamera;
  25690. })(BABYLON.FreeCamera);
  25691. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25692. })(BABYLON || (BABYLON = {}));
  25693. var BABYLON;
  25694. (function (BABYLON) {
  25695. var ShaderMaterial = (function (_super) {
  25696. __extends(ShaderMaterial, _super);
  25697. function ShaderMaterial(name, scene, shaderPath, options) {
  25698. _super.call(this, name, scene);
  25699. this._textures = new Array();
  25700. this._floats = new Array();
  25701. this._floatsArrays = {};
  25702. this._colors3 = new Array();
  25703. this._colors4 = new Array();
  25704. this._vectors2 = new Array();
  25705. this._vectors3 = new Array();
  25706. this._vectors4 = new Array();
  25707. this._matrices = new Array();
  25708. this._matrices3x3 = new Array();
  25709. this._matrices2x2 = new Array();
  25710. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25711. this._shaderPath = shaderPath;
  25712. options.needAlphaBlending = options.needAlphaBlending || false;
  25713. options.needAlphaTesting = options.needAlphaTesting || false;
  25714. options.attributes = options.attributes || ["position", "normal", "uv"];
  25715. options.uniforms = options.uniforms || ["worldViewProjection"];
  25716. options.samplers = options.samplers || [];
  25717. options.defines = options.defines || [];
  25718. this._options = options;
  25719. }
  25720. ShaderMaterial.prototype.needAlphaBlending = function () {
  25721. return this._options.needAlphaBlending;
  25722. };
  25723. ShaderMaterial.prototype.needAlphaTesting = function () {
  25724. return this._options.needAlphaTesting;
  25725. };
  25726. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25727. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25728. this._options.uniforms.push(uniformName);
  25729. }
  25730. };
  25731. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25732. if (this._options.samplers.indexOf(name) === -1) {
  25733. this._options.samplers.push(name);
  25734. }
  25735. this._textures[name] = texture;
  25736. return this;
  25737. };
  25738. ShaderMaterial.prototype.setFloat = function (name, value) {
  25739. this._checkUniform(name);
  25740. this._floats[name] = value;
  25741. return this;
  25742. };
  25743. ShaderMaterial.prototype.setFloats = function (name, value) {
  25744. this._checkUniform(name);
  25745. this._floatsArrays[name] = value;
  25746. return this;
  25747. };
  25748. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25749. this._checkUniform(name);
  25750. this._colors3[name] = value;
  25751. return this;
  25752. };
  25753. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25754. this._checkUniform(name);
  25755. this._colors4[name] = value;
  25756. return this;
  25757. };
  25758. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25759. this._checkUniform(name);
  25760. this._vectors2[name] = value;
  25761. return this;
  25762. };
  25763. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25764. this._checkUniform(name);
  25765. this._vectors3[name] = value;
  25766. return this;
  25767. };
  25768. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25769. this._checkUniform(name);
  25770. this._vectors4[name] = value;
  25771. return this;
  25772. };
  25773. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25774. this._checkUniform(name);
  25775. this._matrices[name] = value;
  25776. return this;
  25777. };
  25778. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25779. this._checkUniform(name);
  25780. this._matrices3x3[name] = value;
  25781. return this;
  25782. };
  25783. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25784. this._checkUniform(name);
  25785. this._matrices2x2[name] = value;
  25786. return this;
  25787. };
  25788. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25789. var scene = this.getScene();
  25790. var engine = scene.getEngine();
  25791. if (!this.checkReadyOnEveryCall) {
  25792. if (this._renderId === scene.getRenderId()) {
  25793. return true;
  25794. }
  25795. }
  25796. // Instances
  25797. var defines = [];
  25798. var fallbacks = new BABYLON.EffectFallbacks();
  25799. if (useInstances) {
  25800. defines.push("#define INSTANCES");
  25801. }
  25802. for (var index = 0; index < this._options.defines.length; index++) {
  25803. defines.push(this._options.defines[index]);
  25804. }
  25805. // Bones
  25806. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25807. defines.push("#define BONES");
  25808. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25809. defines.push("#define BONES4");
  25810. fallbacks.addFallback(0, "BONES4");
  25811. }
  25812. // Alpha test
  25813. if (engine.getAlphaTesting()) {
  25814. defines.push("#define ALPHATEST");
  25815. }
  25816. var previousEffect = this._effect;
  25817. var join = defines.join("\n");
  25818. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25819. if (!this._effect.isReady()) {
  25820. return false;
  25821. }
  25822. if (previousEffect !== this._effect) {
  25823. scene.resetCachedMaterial();
  25824. }
  25825. this._renderId = scene.getRenderId();
  25826. return true;
  25827. };
  25828. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25829. var scene = this.getScene();
  25830. if (this._options.uniforms.indexOf("world") !== -1) {
  25831. this._effect.setMatrix("world", world);
  25832. }
  25833. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25834. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25835. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25836. }
  25837. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25838. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25839. }
  25840. };
  25841. ShaderMaterial.prototype.bind = function (world, mesh) {
  25842. // Std values
  25843. this.bindOnlyWorldMatrix(world);
  25844. if (this.getScene().getCachedMaterial() !== this) {
  25845. if (this._options.uniforms.indexOf("view") !== -1) {
  25846. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25847. }
  25848. if (this._options.uniforms.indexOf("projection") !== -1) {
  25849. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25850. }
  25851. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25852. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25853. }
  25854. // Bones
  25855. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25856. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25857. }
  25858. // Texture
  25859. for (var name in this._textures) {
  25860. this._effect.setTexture(name, this._textures[name]);
  25861. }
  25862. // Float
  25863. for (name in this._floats) {
  25864. this._effect.setFloat(name, this._floats[name]);
  25865. }
  25866. // Float s
  25867. for (name in this._floatsArrays) {
  25868. this._effect.setArray(name, this._floatsArrays[name]);
  25869. }
  25870. // Color3
  25871. for (name in this._colors3) {
  25872. this._effect.setColor3(name, this._colors3[name]);
  25873. }
  25874. // Color4
  25875. for (name in this._colors4) {
  25876. var color = this._colors4[name];
  25877. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25878. }
  25879. // Vector2
  25880. for (name in this._vectors2) {
  25881. this._effect.setVector2(name, this._vectors2[name]);
  25882. }
  25883. // Vector3
  25884. for (name in this._vectors3) {
  25885. this._effect.setVector3(name, this._vectors3[name]);
  25886. }
  25887. // Vector4
  25888. for (name in this._vectors4) {
  25889. this._effect.setVector4(name, this._vectors4[name]);
  25890. }
  25891. // Matrix
  25892. for (name in this._matrices) {
  25893. this._effect.setMatrix(name, this._matrices[name]);
  25894. }
  25895. // Matrix 3x3
  25896. for (name in this._matrices3x3) {
  25897. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25898. }
  25899. // Matrix 2x2
  25900. for (name in this._matrices2x2) {
  25901. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25902. }
  25903. }
  25904. _super.prototype.bind.call(this, world, mesh);
  25905. };
  25906. ShaderMaterial.prototype.clone = function (name) {
  25907. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25908. return newShaderMaterial;
  25909. };
  25910. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25911. for (var name in this._textures) {
  25912. this._textures[name].dispose();
  25913. }
  25914. this._textures = [];
  25915. _super.prototype.dispose.call(this, forceDisposeEffect);
  25916. };
  25917. return ShaderMaterial;
  25918. })(BABYLON.Material);
  25919. BABYLON.ShaderMaterial = ShaderMaterial;
  25920. })(BABYLON || (BABYLON = {}));
  25921. var BABYLON;
  25922. (function (BABYLON) {
  25923. var VertexData = (function () {
  25924. function VertexData() {
  25925. }
  25926. VertexData.prototype.set = function (data, kind) {
  25927. switch (kind) {
  25928. case BABYLON.VertexBuffer.PositionKind:
  25929. this.positions = data;
  25930. break;
  25931. case BABYLON.VertexBuffer.NormalKind:
  25932. this.normals = data;
  25933. break;
  25934. case BABYLON.VertexBuffer.UVKind:
  25935. this.uvs = data;
  25936. break;
  25937. case BABYLON.VertexBuffer.UV2Kind:
  25938. this.uvs2 = data;
  25939. break;
  25940. case BABYLON.VertexBuffer.UV3Kind:
  25941. this.uvs3 = data;
  25942. break;
  25943. case BABYLON.VertexBuffer.UV4Kind:
  25944. this.uvs4 = data;
  25945. break;
  25946. case BABYLON.VertexBuffer.UV5Kind:
  25947. this.uvs5 = data;
  25948. break;
  25949. case BABYLON.VertexBuffer.UV6Kind:
  25950. this.uvs6 = data;
  25951. break;
  25952. case BABYLON.VertexBuffer.ColorKind:
  25953. this.colors = data;
  25954. break;
  25955. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25956. this.matricesIndices = data;
  25957. break;
  25958. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25959. this.matricesWeights = data;
  25960. break;
  25961. }
  25962. };
  25963. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25964. this._applyTo(mesh, updatable);
  25965. };
  25966. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25967. this._applyTo(geometry, updatable);
  25968. };
  25969. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25970. this._update(mesh);
  25971. };
  25972. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25973. this._update(geometry);
  25974. };
  25975. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25976. if (this.positions) {
  25977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25978. }
  25979. if (this.normals) {
  25980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25981. }
  25982. if (this.uvs) {
  25983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25984. }
  25985. if (this.uvs2) {
  25986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25987. }
  25988. if (this.uvs3) {
  25989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25990. }
  25991. if (this.uvs4) {
  25992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25993. }
  25994. if (this.uvs5) {
  25995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25996. }
  25997. if (this.uvs6) {
  25998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25999. }
  26000. if (this.colors) {
  26001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26002. }
  26003. if (this.matricesIndices) {
  26004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26005. }
  26006. if (this.matricesWeights) {
  26007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26008. }
  26009. if (this.indices) {
  26010. meshOrGeometry.setIndices(this.indices);
  26011. }
  26012. };
  26013. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26014. if (this.positions) {
  26015. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26016. }
  26017. if (this.normals) {
  26018. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26019. }
  26020. if (this.uvs) {
  26021. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26022. }
  26023. if (this.uvs2) {
  26024. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26025. }
  26026. if (this.uvs3) {
  26027. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26028. }
  26029. if (this.uvs4) {
  26030. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26031. }
  26032. if (this.uvs5) {
  26033. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26034. }
  26035. if (this.uvs6) {
  26036. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26037. }
  26038. if (this.colors) {
  26039. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26040. }
  26041. if (this.matricesIndices) {
  26042. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26043. }
  26044. if (this.matricesWeights) {
  26045. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26046. }
  26047. if (this.indices) {
  26048. meshOrGeometry.setIndices(this.indices);
  26049. }
  26050. };
  26051. VertexData.prototype.transform = function (matrix) {
  26052. var transformed = BABYLON.Vector3.Zero();
  26053. var index;
  26054. if (this.positions) {
  26055. var position = BABYLON.Vector3.Zero();
  26056. for (index = 0; index < this.positions.length; index += 3) {
  26057. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26058. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26059. this.positions[index] = transformed.x;
  26060. this.positions[index + 1] = transformed.y;
  26061. this.positions[index + 2] = transformed.z;
  26062. }
  26063. }
  26064. if (this.normals) {
  26065. var normal = BABYLON.Vector3.Zero();
  26066. for (index = 0; index < this.normals.length; index += 3) {
  26067. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26068. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26069. this.normals[index] = transformed.x;
  26070. this.normals[index + 1] = transformed.y;
  26071. this.normals[index + 2] = transformed.z;
  26072. }
  26073. }
  26074. };
  26075. VertexData.prototype.merge = function (other) {
  26076. var index;
  26077. if (other.indices) {
  26078. if (!this.indices) {
  26079. this.indices = [];
  26080. }
  26081. var offset = this.positions ? this.positions.length / 3 : 0;
  26082. for (index = 0; index < other.indices.length; index++) {
  26083. this.indices.push(other.indices[index] + offset);
  26084. }
  26085. }
  26086. if (other.positions) {
  26087. if (!this.positions) {
  26088. this.positions = [];
  26089. }
  26090. for (index = 0; index < other.positions.length; index++) {
  26091. this.positions.push(other.positions[index]);
  26092. }
  26093. }
  26094. if (other.normals) {
  26095. if (!this.normals) {
  26096. this.normals = [];
  26097. }
  26098. for (index = 0; index < other.normals.length; index++) {
  26099. this.normals.push(other.normals[index]);
  26100. }
  26101. }
  26102. if (other.uvs) {
  26103. if (!this.uvs) {
  26104. this.uvs = [];
  26105. }
  26106. for (index = 0; index < other.uvs.length; index++) {
  26107. this.uvs.push(other.uvs[index]);
  26108. }
  26109. }
  26110. if (other.uvs2) {
  26111. if (!this.uvs2) {
  26112. this.uvs2 = [];
  26113. }
  26114. for (index = 0; index < other.uvs2.length; index++) {
  26115. this.uvs2.push(other.uvs2[index]);
  26116. }
  26117. }
  26118. if (other.uvs3) {
  26119. if (!this.uvs3) {
  26120. this.uvs3 = [];
  26121. }
  26122. for (index = 0; index < other.uvs3.length; index++) {
  26123. this.uvs3.push(other.uvs3[index]);
  26124. }
  26125. }
  26126. if (other.uvs4) {
  26127. if (!this.uvs4) {
  26128. this.uvs4 = [];
  26129. }
  26130. for (index = 0; index < other.uvs4.length; index++) {
  26131. this.uvs4.push(other.uvs4[index]);
  26132. }
  26133. }
  26134. if (other.uvs5) {
  26135. if (!this.uvs5) {
  26136. this.uvs5 = [];
  26137. }
  26138. for (index = 0; index < other.uvs5.length; index++) {
  26139. this.uvs5.push(other.uvs5[index]);
  26140. }
  26141. }
  26142. if (other.uvs6) {
  26143. if (!this.uvs6) {
  26144. this.uvs6 = [];
  26145. }
  26146. for (index = 0; index < other.uvs6.length; index++) {
  26147. this.uvs6.push(other.uvs6[index]);
  26148. }
  26149. }
  26150. if (other.matricesIndices) {
  26151. if (!this.matricesIndices) {
  26152. this.matricesIndices = [];
  26153. }
  26154. for (index = 0; index < other.matricesIndices.length; index++) {
  26155. this.matricesIndices.push(other.matricesIndices[index]);
  26156. }
  26157. }
  26158. if (other.matricesWeights) {
  26159. if (!this.matricesWeights) {
  26160. this.matricesWeights = [];
  26161. }
  26162. for (index = 0; index < other.matricesWeights.length; index++) {
  26163. this.matricesWeights.push(other.matricesWeights[index]);
  26164. }
  26165. }
  26166. if (other.colors) {
  26167. if (!this.colors) {
  26168. this.colors = [];
  26169. }
  26170. for (index = 0; index < other.colors.length; index++) {
  26171. this.colors.push(other.colors[index]);
  26172. }
  26173. }
  26174. };
  26175. // Statics
  26176. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26177. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26178. };
  26179. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26180. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26181. };
  26182. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26183. var result = new VertexData();
  26184. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26185. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26186. }
  26187. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26188. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26189. }
  26190. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26191. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26192. }
  26193. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26194. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26195. }
  26196. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26197. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26198. }
  26199. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26200. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26201. }
  26202. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26203. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26204. }
  26205. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26206. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26207. }
  26208. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26209. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26210. }
  26211. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26212. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26213. }
  26214. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26215. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26216. }
  26217. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26218. return result;
  26219. };
  26220. VertexData.CreateRibbon = function (options, closeArray, closePath, offset, sideOrientation) {
  26221. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26222. var pathArray = pathArray || options.pathArray;
  26223. closeArray = closeArray || options.closeArray || false;
  26224. closePath = closePath || options.closePath || false;
  26225. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26226. offset = offset || options.offset || defaultOffset;
  26227. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26228. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26229. var positions = [];
  26230. var indices = [];
  26231. var normals = [];
  26232. var uvs = [];
  26233. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26234. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26235. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26236. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26237. var minlg; // minimal length among all paths from pathArray
  26238. var lg = []; // array of path lengths : nb of vertex per path
  26239. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26240. var p; // path iterator
  26241. var i; // point iterator
  26242. var j; // point iterator
  26243. // if single path in pathArray
  26244. if (pathArray.length < 2) {
  26245. var ar1 = [];
  26246. var ar2 = [];
  26247. for (i = 0; i < pathArray[0].length - offset; i++) {
  26248. ar1.push(pathArray[0][i]);
  26249. ar2.push(pathArray[0][i + offset]);
  26250. }
  26251. pathArray = [ar1, ar2];
  26252. }
  26253. // positions and horizontal distances (u)
  26254. var idc = 0;
  26255. var closePathCorr = (closePath) ? 1 : 0;
  26256. var path;
  26257. var l;
  26258. minlg = pathArray[0].length;
  26259. var vectlg;
  26260. var dist;
  26261. for (p = 0; p < pathArray.length; p++) {
  26262. uTotalDistance[p] = 0;
  26263. us[p] = [0];
  26264. path = pathArray[p];
  26265. l = path.length;
  26266. minlg = (minlg < l) ? minlg : l;
  26267. j = 0;
  26268. while (j < l) {
  26269. positions.push(path[j].x, path[j].y, path[j].z);
  26270. if (j > 0) {
  26271. vectlg = path[j].subtract(path[j - 1]).length();
  26272. dist = vectlg + uTotalDistance[p];
  26273. us[p].push(dist);
  26274. uTotalDistance[p] = dist;
  26275. }
  26276. j++;
  26277. }
  26278. if (closePath) {
  26279. j--;
  26280. positions.push(path[0].x, path[0].y, path[0].z);
  26281. vectlg = path[j].subtract(path[0]).length();
  26282. dist = vectlg + uTotalDistance[p];
  26283. us[p].push(dist);
  26284. uTotalDistance[p] = dist;
  26285. }
  26286. lg[p] = l + closePathCorr;
  26287. idx[p] = idc;
  26288. idc += (l + closePathCorr);
  26289. }
  26290. // vertical distances (v)
  26291. var path1;
  26292. var path2;
  26293. var vertex1;
  26294. var vertex2;
  26295. for (i = 0; i < minlg + closePathCorr; i++) {
  26296. vTotalDistance[i] = 0;
  26297. vs[i] = [0];
  26298. for (p = 0; p < pathArray.length - 1; p++) {
  26299. path1 = pathArray[p];
  26300. path2 = pathArray[p + 1];
  26301. if (i === minlg) {
  26302. vertex1 = path1[0];
  26303. vertex2 = path2[0];
  26304. }
  26305. else {
  26306. vertex1 = path1[i];
  26307. vertex2 = path2[i];
  26308. }
  26309. vectlg = vertex2.subtract(vertex1).length();
  26310. dist = vectlg + vTotalDistance[i];
  26311. vs[i].push(dist);
  26312. vTotalDistance[i] = dist;
  26313. }
  26314. if (closeArray) {
  26315. path1 = pathArray[p];
  26316. path2 = pathArray[0];
  26317. vectlg = path2[i].subtract(path1[i]).length();
  26318. dist = vectlg + vTotalDistance[i];
  26319. vTotalDistance[i] = dist;
  26320. }
  26321. }
  26322. // uvs
  26323. var u;
  26324. var v;
  26325. for (p = 0; p < pathArray.length; p++) {
  26326. for (i = 0; i < minlg + closePathCorr; i++) {
  26327. u = us[p][i] / uTotalDistance[p];
  26328. v = vs[i][p] / vTotalDistance[i];
  26329. uvs.push(u, v);
  26330. }
  26331. }
  26332. // indices
  26333. p = 0; // path index
  26334. var pi = 0; // positions array index
  26335. var l1 = lg[p] - 1; // path1 length
  26336. var l2 = lg[p + 1] - 1; // path2 length
  26337. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26338. var shft = idx[1] - idx[0]; // shift
  26339. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26340. while (pi <= min && p < path1nb) {
  26341. // 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
  26342. indices.push(pi, pi + shft, pi + 1);
  26343. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26344. pi += 1;
  26345. if (pi === min) {
  26346. p++;
  26347. if (p === lg.length - 1) {
  26348. shft = idx[0] - idx[p];
  26349. l1 = lg[p] - 1;
  26350. l2 = lg[0] - 1;
  26351. }
  26352. else {
  26353. shft = idx[p + 1] - idx[p];
  26354. l1 = lg[p] - 1;
  26355. l2 = lg[p + 1] - 1;
  26356. }
  26357. pi = idx[p];
  26358. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26359. }
  26360. }
  26361. // normals
  26362. VertexData.ComputeNormals(positions, indices, normals);
  26363. if (closePath) {
  26364. var indexFirst = 0;
  26365. var indexLast = 0;
  26366. for (p = 0; p < pathArray.length; p++) {
  26367. indexFirst = idx[p] * 3;
  26368. if (p + 1 < pathArray.length) {
  26369. indexLast = (idx[p + 1] - 1) * 3;
  26370. }
  26371. else {
  26372. indexLast = normals.length - 3;
  26373. }
  26374. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26375. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26376. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26377. normals[indexLast] = normals[indexFirst];
  26378. normals[indexLast + 1] = normals[indexFirst + 1];
  26379. normals[indexLast + 2] = normals[indexFirst + 2];
  26380. }
  26381. }
  26382. // sides
  26383. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26384. // Result
  26385. var vertexData = new VertexData();
  26386. vertexData.indices = indices;
  26387. vertexData.positions = positions;
  26388. vertexData.normals = normals;
  26389. vertexData.uvs = uvs;
  26390. if (closePath) {
  26391. vertexData._idx = idx;
  26392. }
  26393. return vertexData;
  26394. };
  26395. VertexData.CreateBox = function (options, sideOrientation) {
  26396. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26397. var normalsSource = [
  26398. new BABYLON.Vector3(0, 0, 1),
  26399. new BABYLON.Vector3(0, 0, -1),
  26400. new BABYLON.Vector3(1, 0, 0),
  26401. new BABYLON.Vector3(-1, 0, 0),
  26402. new BABYLON.Vector3(0, 1, 0),
  26403. new BABYLON.Vector3(0, -1, 0)
  26404. ];
  26405. var indices = [];
  26406. var positions = [];
  26407. var normals = [];
  26408. var uvs = [];
  26409. var width = 1;
  26410. var height = 1;
  26411. var depth = 1;
  26412. var faceUV = options.faceUV || new Array(6);
  26413. var faceColors;
  26414. var colors = [];
  26415. if (options.faceColors) {
  26416. faceColors = options.faceColors;
  26417. }
  26418. if (options.width !== undefined) {
  26419. width = options.width || 1;
  26420. height = options.height || 1;
  26421. depth = options.depth || 1;
  26422. }
  26423. else {
  26424. width = options || 1;
  26425. height = options || 1;
  26426. depth = options || 1;
  26427. }
  26428. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26429. for (var f = 0; f < 6; f++) {
  26430. if (faceUV[f] === undefined) {
  26431. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26432. }
  26433. if (faceColors && faceColors[f] === undefined) {
  26434. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26435. }
  26436. }
  26437. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26438. // Create each face in turn.
  26439. for (var index = 0; index < normalsSource.length; index++) {
  26440. var normal = normalsSource[index];
  26441. // Get two vectors perpendicular to the face normal and to each other.
  26442. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26443. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26444. // Six indices (two triangles) per face.
  26445. var verticesLength = positions.length / 3;
  26446. indices.push(verticesLength);
  26447. indices.push(verticesLength + 1);
  26448. indices.push(verticesLength + 2);
  26449. indices.push(verticesLength);
  26450. indices.push(verticesLength + 2);
  26451. indices.push(verticesLength + 3);
  26452. // Four vertices per face.
  26453. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26454. positions.push(vertex.x, vertex.y, vertex.z);
  26455. normals.push(normal.x, normal.y, normal.z);
  26456. uvs.push(faceUV[index].z, faceUV[index].w);
  26457. if (faceColors) {
  26458. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26459. }
  26460. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26461. positions.push(vertex.x, vertex.y, vertex.z);
  26462. normals.push(normal.x, normal.y, normal.z);
  26463. uvs.push(faceUV[index].x, faceUV[index].w);
  26464. if (faceColors) {
  26465. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26466. }
  26467. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26468. positions.push(vertex.x, vertex.y, vertex.z);
  26469. normals.push(normal.x, normal.y, normal.z);
  26470. uvs.push(faceUV[index].x, faceUV[index].y);
  26471. if (faceColors) {
  26472. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26473. }
  26474. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26475. positions.push(vertex.x, vertex.y, vertex.z);
  26476. normals.push(normal.x, normal.y, normal.z);
  26477. uvs.push(faceUV[index].z, faceUV[index].y);
  26478. if (faceColors) {
  26479. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26480. }
  26481. }
  26482. // sides
  26483. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26484. // Result
  26485. var vertexData = new VertexData();
  26486. vertexData.indices = indices;
  26487. vertexData.positions = positions;
  26488. vertexData.normals = normals;
  26489. vertexData.uvs = uvs;
  26490. if (faceColors) {
  26491. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26492. vertexData.colors = totalColors;
  26493. }
  26494. return vertexData;
  26495. };
  26496. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26497. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26498. var segments;
  26499. var diameterX;
  26500. var diameterY;
  26501. var diameterZ;
  26502. if (options.segments) {
  26503. segments = options.segments || 32;
  26504. diameterX = options.diameterX || 1;
  26505. diameterY = options.diameterY || 1;
  26506. diameterZ = options.diameterZ || 1;
  26507. }
  26508. else {
  26509. segments = options || 32;
  26510. diameterX = diameter || 1;
  26511. diameterY = diameterX;
  26512. diameterZ = diameterX;
  26513. }
  26514. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26515. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26516. var totalZRotationSteps = 2 + segments;
  26517. var totalYRotationSteps = 2 * totalZRotationSteps;
  26518. var indices = [];
  26519. var positions = [];
  26520. var normals = [];
  26521. var uvs = [];
  26522. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26523. var normalizedZ = zRotationStep / totalZRotationSteps;
  26524. var angleZ = (normalizedZ * Math.PI);
  26525. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26526. var normalizedY = yRotationStep / totalYRotationSteps;
  26527. var angleY = normalizedY * Math.PI * 2;
  26528. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26529. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26530. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26531. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26532. var vertex = complete.multiply(radius);
  26533. var normal = BABYLON.Vector3.Normalize(vertex);
  26534. positions.push(vertex.x, vertex.y, vertex.z);
  26535. normals.push(normal.x, normal.y, normal.z);
  26536. uvs.push(normalizedY, normalizedZ);
  26537. }
  26538. if (zRotationStep > 0) {
  26539. var verticesCount = positions.length / 3;
  26540. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26541. indices.push((firstIndex));
  26542. indices.push((firstIndex + 1));
  26543. indices.push(firstIndex + totalYRotationSteps + 1);
  26544. indices.push((firstIndex + totalYRotationSteps + 1));
  26545. indices.push((firstIndex + 1));
  26546. indices.push((firstIndex + totalYRotationSteps + 2));
  26547. }
  26548. }
  26549. }
  26550. // Sides
  26551. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26552. // Result
  26553. var vertexData = new VertexData();
  26554. vertexData.indices = indices;
  26555. vertexData.positions = positions;
  26556. vertexData.normals = normals;
  26557. vertexData.uvs = uvs;
  26558. return vertexData;
  26559. };
  26560. VertexData.CreateCylinder = function (options, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26561. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26562. var height = height || options.height || 3;
  26563. diameterTop = diameterTop || options.diameterTop || 1;
  26564. diameterBottom = diameterBottom || options.diameterBottom || 1;
  26565. tessellation = tessellation || options.tessellation || 24;
  26566. subdivisions = subdivisions || options.subdivisions || 1;
  26567. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26568. var indices = [];
  26569. var positions = [];
  26570. var normals = [];
  26571. var uvs = [];
  26572. var angle_step = Math.PI * 2 / tessellation;
  26573. var angle;
  26574. var h;
  26575. var radius;
  26576. var tan = (diameterBottom - diameterTop) / 2 / height;
  26577. var ringVertex = BABYLON.Vector3.Zero();
  26578. var ringNormal = BABYLON.Vector3.Zero();
  26579. // positions, normals, uvs
  26580. var i;
  26581. var j;
  26582. for (i = 0; i <= subdivisions; i++) {
  26583. h = i / subdivisions;
  26584. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26585. for (j = 0; j <= tessellation; j++) {
  26586. angle = j * angle_step;
  26587. ringVertex.x = Math.cos(-angle) * radius;
  26588. ringVertex.y = -height / 2 + h * height;
  26589. ringVertex.z = Math.sin(-angle) * radius;
  26590. if (diameterTop === 0 && i === subdivisions) {
  26591. // if no top cap, reuse former normals
  26592. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26593. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26594. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26595. }
  26596. else {
  26597. ringNormal.x = ringVertex.x;
  26598. ringNormal.z = ringVertex.z;
  26599. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26600. ringNormal.normalize();
  26601. }
  26602. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26603. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26604. uvs.push(j / tessellation, 1 - h);
  26605. }
  26606. }
  26607. // indices
  26608. for (i = 0; i < subdivisions; i++) {
  26609. for (j = 0; j < tessellation; j++) {
  26610. var i0 = i * (tessellation + 1) + j;
  26611. var i1 = (i + 1) * (tessellation + 1) + j;
  26612. var i2 = i * (tessellation + 1) + (j + 1);
  26613. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26614. indices.push(i0, i1, i2);
  26615. indices.push(i3, i2, i1);
  26616. }
  26617. }
  26618. // Caps
  26619. var createCylinderCap = function (isTop) {
  26620. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26621. if (radius === 0) {
  26622. return;
  26623. }
  26624. var vbase = positions.length / 3;
  26625. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26626. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26627. // Cap positions, normals & uvs
  26628. var angle;
  26629. var circleVector;
  26630. var i;
  26631. for (i = 0; i < tessellation; i++) {
  26632. angle = Math.PI * 2 * i / tessellation;
  26633. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26634. var position = circleVector.scale(radius).add(offset);
  26635. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26636. positions.push(position.x, position.y, position.z);
  26637. normals.push(0, isTop ? 1 : -1, 0);
  26638. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26639. }
  26640. // Cap indices
  26641. for (i = 0; i < tessellation - 2; i++) {
  26642. if (!isTop) {
  26643. indices.push(vbase);
  26644. indices.push(vbase + (i + 1) % tessellation);
  26645. indices.push(vbase + (i + 2) % tessellation);
  26646. }
  26647. else {
  26648. indices.push(vbase);
  26649. indices.push(vbase + (i + 2) % tessellation);
  26650. indices.push(vbase + (i + 1) % tessellation);
  26651. }
  26652. }
  26653. };
  26654. // add caps to geometry
  26655. createCylinderCap(true);
  26656. createCylinderCap(false);
  26657. // Sides
  26658. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26659. var vertexData = new VertexData();
  26660. vertexData.indices = indices;
  26661. vertexData.positions = positions;
  26662. vertexData.normals = normals;
  26663. vertexData.uvs = uvs;
  26664. return vertexData;
  26665. };
  26666. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26667. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26668. var indices = [];
  26669. var positions = [];
  26670. var normals = [];
  26671. var uvs = [];
  26672. diameter = diameter || 1;
  26673. thickness = thickness || 0.5;
  26674. tessellation = tessellation || 16;
  26675. var stride = tessellation + 1;
  26676. for (var i = 0; i <= tessellation; i++) {
  26677. var u = i / tessellation;
  26678. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26679. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26680. for (var j = 0; j <= tessellation; j++) {
  26681. var v = 1 - j / tessellation;
  26682. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26683. var dx = Math.cos(innerAngle);
  26684. var dy = Math.sin(innerAngle);
  26685. // Create a vertex.
  26686. var normal = new BABYLON.Vector3(dx, dy, 0);
  26687. var position = normal.scale(thickness / 2);
  26688. var textureCoordinate = new BABYLON.Vector2(u, v);
  26689. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26690. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26691. positions.push(position.x, position.y, position.z);
  26692. normals.push(normal.x, normal.y, normal.z);
  26693. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26694. // And create indices for two triangles.
  26695. var nextI = (i + 1) % stride;
  26696. var nextJ = (j + 1) % stride;
  26697. indices.push(i * stride + j);
  26698. indices.push(i * stride + nextJ);
  26699. indices.push(nextI * stride + j);
  26700. indices.push(i * stride + nextJ);
  26701. indices.push(nextI * stride + nextJ);
  26702. indices.push(nextI * stride + j);
  26703. }
  26704. }
  26705. // Sides
  26706. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26707. // Result
  26708. var vertexData = new VertexData();
  26709. vertexData.indices = indices;
  26710. vertexData.positions = positions;
  26711. vertexData.normals = normals;
  26712. vertexData.uvs = uvs;
  26713. return vertexData;
  26714. };
  26715. VertexData.CreateLines = function (points) {
  26716. var indices = [];
  26717. var positions = [];
  26718. for (var index = 0; index < points.length; index++) {
  26719. positions.push(points[index].x, points[index].y, points[index].z);
  26720. if (index > 0) {
  26721. indices.push(index - 1);
  26722. indices.push(index);
  26723. }
  26724. }
  26725. // Result
  26726. var vertexData = new VertexData();
  26727. vertexData.indices = indices;
  26728. vertexData.positions = positions;
  26729. return vertexData;
  26730. };
  26731. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26732. dashSize = dashSize || 3;
  26733. gapSize = gapSize || 1;
  26734. dashNb = dashNb || 200;
  26735. var positions = new Array();
  26736. var indices = new Array();
  26737. var curvect = BABYLON.Vector3.Zero();
  26738. var lg = 0;
  26739. var nb = 0;
  26740. var shft = 0;
  26741. var dashshft = 0;
  26742. var curshft = 0;
  26743. var idx = 0;
  26744. var i = 0;
  26745. for (i = 0; i < points.length - 1; i++) {
  26746. points[i + 1].subtractToRef(points[i], curvect);
  26747. lg += curvect.length();
  26748. }
  26749. shft = lg / dashNb;
  26750. dashshft = dashSize * shft / (dashSize + gapSize);
  26751. for (i = 0; i < points.length - 1; i++) {
  26752. points[i + 1].subtractToRef(points[i], curvect);
  26753. nb = Math.floor(curvect.length() / shft);
  26754. curvect.normalize();
  26755. for (var j = 0; j < nb; j++) {
  26756. curshft = shft * j;
  26757. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26758. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26759. indices.push(idx, idx + 1);
  26760. idx += 2;
  26761. }
  26762. }
  26763. // Result
  26764. var vertexData = new VertexData();
  26765. vertexData.positions = positions;
  26766. vertexData.indices = indices;
  26767. return vertexData;
  26768. };
  26769. VertexData.CreateGround = function (options, height, subdivisions) {
  26770. var indices = [];
  26771. var positions = [];
  26772. var normals = [];
  26773. var uvs = [];
  26774. var row, col;
  26775. var width;
  26776. if (options.width) {
  26777. width = options.width || 1;
  26778. height = options.height || 1;
  26779. subdivisions = options.subdivisions || 1;
  26780. }
  26781. else {
  26782. width = options || 1;
  26783. height = height || 1;
  26784. subdivisions = subdivisions || 1;
  26785. }
  26786. for (row = 0; row <= subdivisions; row++) {
  26787. for (col = 0; col <= subdivisions; col++) {
  26788. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26789. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26790. positions.push(position.x, position.y, position.z);
  26791. normals.push(normal.x, normal.y, normal.z);
  26792. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26793. }
  26794. }
  26795. for (row = 0; row < subdivisions; row++) {
  26796. for (col = 0; col < subdivisions; col++) {
  26797. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26798. indices.push(col + 1 + row * (subdivisions + 1));
  26799. indices.push(col + row * (subdivisions + 1));
  26800. indices.push(col + (row + 1) * (subdivisions + 1));
  26801. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26802. indices.push(col + row * (subdivisions + 1));
  26803. }
  26804. }
  26805. // Result
  26806. var vertexData = new VertexData();
  26807. vertexData.indices = indices;
  26808. vertexData.positions = positions;
  26809. vertexData.normals = normals;
  26810. vertexData.uvs = uvs;
  26811. return vertexData;
  26812. };
  26813. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26814. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26815. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26816. var indices = [];
  26817. var positions = [];
  26818. var normals = [];
  26819. var uvs = [];
  26820. var row, col, tileRow, tileCol;
  26821. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26822. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26823. precision.w = (precision.w < 1) ? 1 : precision.w;
  26824. precision.h = (precision.h < 1) ? 1 : precision.h;
  26825. var tileSize = {
  26826. 'w': (xmax - xmin) / subdivisions.w,
  26827. 'h': (zmax - zmin) / subdivisions.h
  26828. };
  26829. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26830. // Indices
  26831. var base = positions.length / 3;
  26832. var rowLength = precision.w + 1;
  26833. for (row = 0; row < precision.h; row++) {
  26834. for (col = 0; col < precision.w; col++) {
  26835. var square = [
  26836. base + col + row * rowLength,
  26837. base + (col + 1) + row * rowLength,
  26838. base + (col + 1) + (row + 1) * rowLength,
  26839. base + col + (row + 1) * rowLength
  26840. ];
  26841. indices.push(square[1]);
  26842. indices.push(square[2]);
  26843. indices.push(square[3]);
  26844. indices.push(square[0]);
  26845. indices.push(square[1]);
  26846. indices.push(square[3]);
  26847. }
  26848. }
  26849. // Position, normals and uvs
  26850. var position = BABYLON.Vector3.Zero();
  26851. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26852. for (row = 0; row <= precision.h; row++) {
  26853. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26854. for (col = 0; col <= precision.w; col++) {
  26855. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26856. position.y = 0;
  26857. positions.push(position.x, position.y, position.z);
  26858. normals.push(normal.x, normal.y, normal.z);
  26859. uvs.push(col / precision.w, row / precision.h);
  26860. }
  26861. }
  26862. }
  26863. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26864. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26865. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26866. }
  26867. }
  26868. // Result
  26869. var vertexData = new VertexData();
  26870. vertexData.indices = indices;
  26871. vertexData.positions = positions;
  26872. vertexData.normals = normals;
  26873. vertexData.uvs = uvs;
  26874. return vertexData;
  26875. };
  26876. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26877. var indices = [];
  26878. var positions = [];
  26879. var normals = [];
  26880. var uvs = [];
  26881. var row, col;
  26882. // Vertices
  26883. for (row = 0; row <= subdivisions; row++) {
  26884. for (col = 0; col <= subdivisions; col++) {
  26885. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26886. // Compute height
  26887. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26888. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26889. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26890. var r = buffer[pos] / 255.0;
  26891. var g = buffer[pos + 1] / 255.0;
  26892. var b = buffer[pos + 2] / 255.0;
  26893. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26894. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26895. // Add vertex
  26896. positions.push(position.x, position.y, position.z);
  26897. normals.push(0, 0, 0);
  26898. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26899. }
  26900. }
  26901. // Indices
  26902. for (row = 0; row < subdivisions; row++) {
  26903. for (col = 0; col < subdivisions; col++) {
  26904. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26905. indices.push(col + 1 + row * (subdivisions + 1));
  26906. indices.push(col + row * (subdivisions + 1));
  26907. indices.push(col + (row + 1) * (subdivisions + 1));
  26908. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26909. indices.push(col + row * (subdivisions + 1));
  26910. }
  26911. }
  26912. // Normals
  26913. VertexData.ComputeNormals(positions, indices, normals);
  26914. // Result
  26915. var vertexData = new VertexData();
  26916. vertexData.indices = indices;
  26917. vertexData.positions = positions;
  26918. vertexData.normals = normals;
  26919. vertexData.uvs = uvs;
  26920. return vertexData;
  26921. };
  26922. VertexData.CreatePlane = function (options, sideOrientation) {
  26923. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26924. var indices = [];
  26925. var positions = [];
  26926. var normals = [];
  26927. var uvs = [];
  26928. var width;
  26929. var height;
  26930. if (options.width) {
  26931. width = options.width || 1;
  26932. height = options.height || 1;
  26933. sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26934. }
  26935. else {
  26936. width = options || 1;
  26937. height = options || 1;
  26938. }
  26939. // Vertices
  26940. var halfWidth = width / 2.0;
  26941. var halfHeight = height / 2.0;
  26942. positions.push(-halfWidth, -halfHeight, 0);
  26943. normals.push(0, 0, -1.0);
  26944. uvs.push(0.0, 0.0);
  26945. positions.push(halfWidth, -halfHeight, 0);
  26946. normals.push(0, 0, -1.0);
  26947. uvs.push(1.0, 0.0);
  26948. positions.push(halfWidth, halfHeight, 0);
  26949. normals.push(0, 0, -1.0);
  26950. uvs.push(1.0, 1.0);
  26951. positions.push(-halfWidth, halfHeight, 0);
  26952. normals.push(0, 0, -1.0);
  26953. uvs.push(0.0, 1.0);
  26954. // Indices
  26955. indices.push(0);
  26956. indices.push(1);
  26957. indices.push(2);
  26958. indices.push(0);
  26959. indices.push(2);
  26960. indices.push(3);
  26961. // Sides
  26962. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26963. // Result
  26964. var vertexData = new VertexData();
  26965. vertexData.indices = indices;
  26966. vertexData.positions = positions;
  26967. vertexData.normals = normals;
  26968. vertexData.uvs = uvs;
  26969. return vertexData;
  26970. };
  26971. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26972. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26973. var positions = [];
  26974. var indices = [];
  26975. var normals = [];
  26976. var uvs = [];
  26977. // positions and uvs
  26978. positions.push(0, 0, 0); // disc center first
  26979. uvs.push(0.5, 0.5);
  26980. var step = Math.PI * 2 / tessellation;
  26981. for (var a = 0; a < Math.PI * 2; a += step) {
  26982. var x = Math.cos(a);
  26983. var y = Math.sin(a);
  26984. var u = (x + 1) / 2;
  26985. var v = (1 - y) / 2;
  26986. positions.push(radius * x, radius * y, 0);
  26987. uvs.push(u, v);
  26988. }
  26989. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26990. uvs.push(uvs[2], uvs[3]);
  26991. //indices
  26992. var vertexNb = positions.length / 3;
  26993. for (var i = 1; i < vertexNb - 1; i++) {
  26994. indices.push(i + 1, 0, i);
  26995. }
  26996. // result
  26997. VertexData.ComputeNormals(positions, indices, normals);
  26998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26999. var vertexData = new VertexData();
  27000. vertexData.indices = indices;
  27001. vertexData.positions = positions;
  27002. vertexData.normals = normals;
  27003. vertexData.uvs = uvs;
  27004. return vertexData;
  27005. };
  27006. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27007. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  27008. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  27009. var indices = [];
  27010. var positions = [];
  27011. var normals = [];
  27012. var uvs = [];
  27013. radius = radius || 2;
  27014. tube = tube || 0.5;
  27015. radialSegments = radialSegments || 32;
  27016. tubularSegments = tubularSegments || 32;
  27017. p = p || 2;
  27018. q = q || 3;
  27019. // Helper
  27020. var getPos = function (angle) {
  27021. var cu = Math.cos(angle);
  27022. var su = Math.sin(angle);
  27023. var quOverP = q / p * angle;
  27024. var cs = Math.cos(quOverP);
  27025. var tx = radius * (2 + cs) * 0.5 * cu;
  27026. var ty = radius * (2 + cs) * su * 0.5;
  27027. var tz = radius * Math.sin(quOverP) * 0.5;
  27028. return new BABYLON.Vector3(tx, ty, tz);
  27029. };
  27030. // Vertices
  27031. var i;
  27032. var j;
  27033. for (i = 0; i <= radialSegments; i++) {
  27034. var modI = i % radialSegments;
  27035. var u = modI / radialSegments * 2 * p * Math.PI;
  27036. var p1 = getPos(u);
  27037. var p2 = getPos(u + 0.01);
  27038. var tang = p2.subtract(p1);
  27039. var n = p2.add(p1);
  27040. var bitan = BABYLON.Vector3.Cross(tang, n);
  27041. n = BABYLON.Vector3.Cross(bitan, tang);
  27042. bitan.normalize();
  27043. n.normalize();
  27044. for (j = 0; j < tubularSegments; j++) {
  27045. var modJ = j % tubularSegments;
  27046. var v = modJ / tubularSegments * 2 * Math.PI;
  27047. var cx = -tube * Math.cos(v);
  27048. var cy = tube * Math.sin(v);
  27049. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27050. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27051. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27052. uvs.push(i / radialSegments);
  27053. uvs.push(j / tubularSegments);
  27054. }
  27055. }
  27056. for (i = 0; i < radialSegments; i++) {
  27057. for (j = 0; j < tubularSegments; j++) {
  27058. var jNext = (j + 1) % tubularSegments;
  27059. var a = i * tubularSegments + j;
  27060. var b = (i + 1) * tubularSegments + j;
  27061. var c = (i + 1) * tubularSegments + jNext;
  27062. var d = i * tubularSegments + jNext;
  27063. indices.push(d);
  27064. indices.push(b);
  27065. indices.push(a);
  27066. indices.push(d);
  27067. indices.push(c);
  27068. indices.push(b);
  27069. }
  27070. }
  27071. // Normals
  27072. VertexData.ComputeNormals(positions, indices, normals);
  27073. // Sides
  27074. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27075. // Result
  27076. var vertexData = new VertexData();
  27077. vertexData.indices = indices;
  27078. vertexData.positions = positions;
  27079. vertexData.normals = normals;
  27080. vertexData.uvs = uvs;
  27081. return vertexData;
  27082. };
  27083. // Tools
  27084. /**
  27085. * @param {any} - positions (number[] or Float32Array)
  27086. * @param {any} - indices (number[] or Uint16Array)
  27087. * @param {any} - normals (number[] or Float32Array)
  27088. */
  27089. VertexData.ComputeNormals = function (positions, indices, normals) {
  27090. var index = 0;
  27091. // temp Vector3
  27092. var p1p2 = BABYLON.Vector3.Zero();
  27093. var p3p2 = BABYLON.Vector3.Zero();
  27094. var faceNormal = BABYLON.Vector3.Zero();
  27095. var vertexNormali1 = BABYLON.Vector3.Zero();
  27096. for (index = 0; index < positions.length; index++) {
  27097. normals[index] = 0.0;
  27098. }
  27099. // indice triplet = 1 face
  27100. var nbFaces = indices.length / 3;
  27101. for (index = 0; index < nbFaces; index++) {
  27102. var i1 = indices[index * 3];
  27103. var i2 = indices[index * 3 + 1];
  27104. var i3 = indices[index * 3 + 2];
  27105. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27106. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27107. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27108. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27109. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27110. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27111. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27112. faceNormal.normalize();
  27113. normals[i1 * 3] += faceNormal.x;
  27114. normals[i1 * 3 + 1] += faceNormal.y;
  27115. normals[i1 * 3 + 2] += faceNormal.z;
  27116. normals[i2 * 3] += faceNormal.x;
  27117. normals[i2 * 3 + 1] += faceNormal.y;
  27118. normals[i2 * 3 + 2] += faceNormal.z;
  27119. normals[i3 * 3] += faceNormal.x;
  27120. normals[i3 * 3 + 1] += faceNormal.y;
  27121. normals[i3 * 3 + 2] += faceNormal.z;
  27122. }
  27123. // last normalization
  27124. for (index = 0; index < normals.length / 3; index++) {
  27125. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27126. vertexNormali1.normalize();
  27127. normals[index * 3] = vertexNormali1.x;
  27128. normals[index * 3 + 1] = vertexNormali1.y;
  27129. normals[index * 3 + 2] = vertexNormali1.z;
  27130. }
  27131. };
  27132. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27133. var li = indices.length;
  27134. var ln = normals.length;
  27135. var i;
  27136. var n;
  27137. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27138. switch (sideOrientation) {
  27139. case BABYLON.Mesh.FRONTSIDE:
  27140. // nothing changed
  27141. break;
  27142. case BABYLON.Mesh.BACKSIDE:
  27143. var tmp;
  27144. // indices
  27145. for (i = 0; i < li; i += 3) {
  27146. tmp = indices[i];
  27147. indices[i] = indices[i + 2];
  27148. indices[i + 2] = tmp;
  27149. }
  27150. // normals
  27151. for (n = 0; n < ln; n++) {
  27152. normals[n] = -normals[n];
  27153. }
  27154. break;
  27155. case BABYLON.Mesh.DOUBLESIDE:
  27156. // positions
  27157. var lp = positions.length;
  27158. var l = lp / 3;
  27159. for (var p = 0; p < lp; p++) {
  27160. positions[lp + p] = positions[p];
  27161. }
  27162. // indices
  27163. for (i = 0; i < li; i += 3) {
  27164. indices[i + li] = indices[i + 2] + l;
  27165. indices[i + 1 + li] = indices[i + 1] + l;
  27166. indices[i + 2 + li] = indices[i] + l;
  27167. }
  27168. // normals
  27169. for (n = 0; n < ln; n++) {
  27170. normals[ln + n] = -normals[n];
  27171. }
  27172. // uvs
  27173. var lu = uvs.length;
  27174. for (var u = 0; u < lu; u++) {
  27175. uvs[u + lu] = uvs[u];
  27176. }
  27177. break;
  27178. }
  27179. };
  27180. return VertexData;
  27181. })();
  27182. BABYLON.VertexData = VertexData;
  27183. })(BABYLON || (BABYLON = {}));
  27184. var BABYLON;
  27185. (function (BABYLON) {
  27186. var AnaglyphPostProcess = (function (_super) {
  27187. __extends(AnaglyphPostProcess, _super);
  27188. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27189. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27190. }
  27191. return AnaglyphPostProcess;
  27192. })(BABYLON.PostProcess);
  27193. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27194. })(BABYLON || (BABYLON = {}));
  27195. var BABYLON;
  27196. (function (BABYLON) {
  27197. var Tags = (function () {
  27198. function Tags() {
  27199. }
  27200. Tags.EnableFor = function (obj) {
  27201. obj._tags = obj._tags || {};
  27202. obj.hasTags = function () {
  27203. return Tags.HasTags(obj);
  27204. };
  27205. obj.addTags = function (tagsString) {
  27206. return Tags.AddTagsTo(obj, tagsString);
  27207. };
  27208. obj.removeTags = function (tagsString) {
  27209. return Tags.RemoveTagsFrom(obj, tagsString);
  27210. };
  27211. obj.matchesTagsQuery = function (tagsQuery) {
  27212. return Tags.MatchesQuery(obj, tagsQuery);
  27213. };
  27214. };
  27215. Tags.DisableFor = function (obj) {
  27216. delete obj._tags;
  27217. delete obj.hasTags;
  27218. delete obj.addTags;
  27219. delete obj.removeTags;
  27220. delete obj.matchesTagsQuery;
  27221. };
  27222. Tags.HasTags = function (obj) {
  27223. if (!obj._tags) {
  27224. return false;
  27225. }
  27226. return !BABYLON.Tools.IsEmpty(obj._tags);
  27227. };
  27228. Tags.GetTags = function (obj) {
  27229. if (!obj._tags) {
  27230. return null;
  27231. }
  27232. return obj._tags;
  27233. };
  27234. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27235. // a tag cannot start with '||', '&&', and '!'
  27236. // it cannot contain whitespaces
  27237. Tags.AddTagsTo = function (obj, tagsString) {
  27238. if (!tagsString) {
  27239. return;
  27240. }
  27241. var tags = tagsString.split(" ");
  27242. for (var t in tags) {
  27243. Tags._AddTagTo(obj, tags[t]);
  27244. }
  27245. };
  27246. Tags._AddTagTo = function (obj, tag) {
  27247. tag = tag.trim();
  27248. if (tag === "" || tag === "true" || tag === "false") {
  27249. return;
  27250. }
  27251. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27252. return;
  27253. }
  27254. Tags.EnableFor(obj);
  27255. obj._tags[tag] = true;
  27256. };
  27257. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27258. if (!Tags.HasTags(obj)) {
  27259. return;
  27260. }
  27261. var tags = tagsString.split(" ");
  27262. for (var t in tags) {
  27263. Tags._RemoveTagFrom(obj, tags[t]);
  27264. }
  27265. };
  27266. Tags._RemoveTagFrom = function (obj, tag) {
  27267. delete obj._tags[tag];
  27268. };
  27269. Tags.MatchesQuery = function (obj, tagsQuery) {
  27270. if (tagsQuery === undefined) {
  27271. return true;
  27272. }
  27273. if (tagsQuery === "") {
  27274. return Tags.HasTags(obj);
  27275. }
  27276. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27277. };
  27278. return Tags;
  27279. })();
  27280. BABYLON.Tags = Tags;
  27281. })(BABYLON || (BABYLON = {}));
  27282. var BABYLON;
  27283. (function (BABYLON) {
  27284. var Internals;
  27285. (function (Internals) {
  27286. var AndOrNotEvaluator = (function () {
  27287. function AndOrNotEvaluator() {
  27288. }
  27289. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27290. if (!query.match(/\([^\(\)]*\)/g)) {
  27291. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27292. }
  27293. else {
  27294. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27295. // remove parenthesis
  27296. r = r.slice(1, r.length - 1);
  27297. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27298. });
  27299. }
  27300. if (query === "true") {
  27301. return true;
  27302. }
  27303. if (query === "false") {
  27304. return false;
  27305. }
  27306. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27307. };
  27308. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27309. evaluateCallback = evaluateCallback || (function (r) {
  27310. return r === "true" ? true : false;
  27311. });
  27312. var result;
  27313. var or = parenthesisContent.split("||");
  27314. for (var i in or) {
  27315. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27316. var and = ori.split("&&");
  27317. if (and.length > 1) {
  27318. for (var j = 0; j < and.length; ++j) {
  27319. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27320. if (andj !== "true" && andj !== "false") {
  27321. if (andj[0] === "!") {
  27322. result = !evaluateCallback(andj.substring(1));
  27323. }
  27324. else {
  27325. result = evaluateCallback(andj);
  27326. }
  27327. }
  27328. else {
  27329. result = andj === "true" ? true : false;
  27330. }
  27331. if (!result) {
  27332. ori = "false";
  27333. break;
  27334. }
  27335. }
  27336. }
  27337. if (result || ori === "true") {
  27338. result = true;
  27339. break;
  27340. }
  27341. // result equals false (or undefined)
  27342. if (ori !== "true" && ori !== "false") {
  27343. if (ori[0] === "!") {
  27344. result = !evaluateCallback(ori.substring(1));
  27345. }
  27346. else {
  27347. result = evaluateCallback(ori);
  27348. }
  27349. }
  27350. else {
  27351. result = ori === "true" ? true : false;
  27352. }
  27353. }
  27354. // the whole parenthesis scope is replaced by 'true' or 'false'
  27355. return result ? "true" : "false";
  27356. };
  27357. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27358. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27359. // remove whitespaces
  27360. r = r.replace(/[\s]/g, function () { return ""; });
  27361. return r.length % 2 ? "!" : "";
  27362. });
  27363. booleanString = booleanString.trim();
  27364. if (booleanString === "!true") {
  27365. booleanString = "false";
  27366. }
  27367. else if (booleanString === "!false") {
  27368. booleanString = "true";
  27369. }
  27370. return booleanString;
  27371. };
  27372. return AndOrNotEvaluator;
  27373. })();
  27374. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27375. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27376. })(BABYLON || (BABYLON = {}));
  27377. var BABYLON;
  27378. (function (BABYLON) {
  27379. var PostProcessRenderPass = (function () {
  27380. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27381. this._enabled = true;
  27382. this._refCount = 0;
  27383. this._name = name;
  27384. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27385. this.setRenderList(renderList);
  27386. this._renderTexture.onBeforeRender = beforeRender;
  27387. this._renderTexture.onAfterRender = afterRender;
  27388. this._scene = scene;
  27389. this._renderList = renderList;
  27390. }
  27391. // private
  27392. PostProcessRenderPass.prototype._incRefCount = function () {
  27393. if (this._refCount === 0) {
  27394. this._scene.customRenderTargets.push(this._renderTexture);
  27395. }
  27396. return ++this._refCount;
  27397. };
  27398. PostProcessRenderPass.prototype._decRefCount = function () {
  27399. this._refCount--;
  27400. if (this._refCount <= 0) {
  27401. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27402. }
  27403. return this._refCount;
  27404. };
  27405. PostProcessRenderPass.prototype._update = function () {
  27406. this.setRenderList(this._renderList);
  27407. };
  27408. // public
  27409. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27410. this._renderTexture.renderList = renderList;
  27411. };
  27412. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27413. return this._renderTexture;
  27414. };
  27415. return PostProcessRenderPass;
  27416. })();
  27417. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27418. })(BABYLON || (BABYLON = {}));
  27419. var BABYLON;
  27420. (function (BABYLON) {
  27421. var PostProcessRenderEffect = (function () {
  27422. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27423. this._engine = engine;
  27424. this._name = name;
  27425. this._singleInstance = singleInstance || true;
  27426. this._getPostProcess = getPostProcess;
  27427. this._cameras = [];
  27428. this._indicesForCamera = [];
  27429. this._postProcesses = {};
  27430. this._renderPasses = {};
  27431. this._renderEffectAsPasses = {};
  27432. }
  27433. PostProcessRenderEffect.prototype._update = function () {
  27434. for (var renderPassName in this._renderPasses) {
  27435. this._renderPasses[renderPassName]._update();
  27436. }
  27437. };
  27438. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27439. this._renderPasses[renderPass._name] = renderPass;
  27440. this._linkParameters();
  27441. };
  27442. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27443. delete this._renderPasses[renderPass._name];
  27444. this._linkParameters();
  27445. };
  27446. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27447. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27448. this._linkParameters();
  27449. };
  27450. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27451. for (var renderPassName in this._renderPasses) {
  27452. if (renderPassName === passName) {
  27453. return this._renderPasses[passName];
  27454. }
  27455. }
  27456. };
  27457. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27458. this._renderPasses = {};
  27459. this._linkParameters();
  27460. };
  27461. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27462. var cameraKey;
  27463. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27464. for (var i = 0; i < _cam.length; i++) {
  27465. var camera = _cam[i];
  27466. var cameraName = camera.name;
  27467. if (this._singleInstance) {
  27468. cameraKey = 0;
  27469. }
  27470. else {
  27471. cameraKey = cameraName;
  27472. }
  27473. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27474. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27475. if (!this._indicesForCamera[cameraName]) {
  27476. this._indicesForCamera[cameraName] = [];
  27477. }
  27478. this._indicesForCamera[cameraName].push(index);
  27479. if (this._cameras.indexOf(camera) === -1) {
  27480. this._cameras[cameraName] = camera;
  27481. }
  27482. for (var passName in this._renderPasses) {
  27483. this._renderPasses[passName]._incRefCount();
  27484. }
  27485. }
  27486. this._linkParameters();
  27487. };
  27488. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27489. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27490. for (var i = 0; i < _cam.length; i++) {
  27491. var camera = _cam[i];
  27492. var cameraName = camera.name;
  27493. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27494. var index = this._cameras.indexOf(cameraName);
  27495. this._indicesForCamera.splice(index, 1);
  27496. this._cameras.splice(index, 1);
  27497. for (var passName in this._renderPasses) {
  27498. this._renderPasses[passName]._decRefCount();
  27499. }
  27500. }
  27501. };
  27502. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27503. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27504. for (var i = 0; i < _cam.length; i++) {
  27505. var camera = _cam[i];
  27506. var cameraName = camera.name;
  27507. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27508. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27509. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27510. }
  27511. }
  27512. for (var passName in this._renderPasses) {
  27513. this._renderPasses[passName]._incRefCount();
  27514. }
  27515. }
  27516. };
  27517. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27518. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27519. for (var i = 0; i < _cam.length; i++) {
  27520. var camera = _cam[i];
  27521. var cameraName = camera.Name;
  27522. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27523. for (var passName in this._renderPasses) {
  27524. this._renderPasses[passName]._decRefCount();
  27525. }
  27526. }
  27527. };
  27528. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27529. if (this._singleInstance) {
  27530. return this._postProcesses[0];
  27531. }
  27532. else {
  27533. return this._postProcesses[camera.name];
  27534. }
  27535. };
  27536. PostProcessRenderEffect.prototype._linkParameters = function () {
  27537. var _this = this;
  27538. for (var index in this._postProcesses) {
  27539. if (this.applyParameters) {
  27540. this.applyParameters(this._postProcesses[index]);
  27541. }
  27542. this._postProcesses[index].onBeforeRender = function (effect) {
  27543. _this._linkTextures(effect);
  27544. };
  27545. }
  27546. };
  27547. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27548. for (var renderPassName in this._renderPasses) {
  27549. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27550. }
  27551. for (var renderEffectName in this._renderEffectAsPasses) {
  27552. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27553. }
  27554. };
  27555. return PostProcessRenderEffect;
  27556. })();
  27557. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27558. })(BABYLON || (BABYLON = {}));
  27559. var BABYLON;
  27560. (function (BABYLON) {
  27561. var PostProcessRenderPipeline = (function () {
  27562. function PostProcessRenderPipeline(engine, name) {
  27563. this._engine = engine;
  27564. this._name = name;
  27565. this._renderEffects = {};
  27566. this._renderEffectsForIsolatedPass = {};
  27567. this._cameras = [];
  27568. }
  27569. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27570. this._renderEffects[renderEffect._name] = renderEffect;
  27571. };
  27572. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27573. var renderEffects = this._renderEffects[renderEffectName];
  27574. if (!renderEffects) {
  27575. return;
  27576. }
  27577. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27578. };
  27579. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27580. var renderEffects = this._renderEffects[renderEffectName];
  27581. if (!renderEffects) {
  27582. return;
  27583. }
  27584. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27585. };
  27586. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27587. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27588. var indicesToDelete = [];
  27589. for (var i = 0; i < _cam.length; i++) {
  27590. var camera = _cam[i];
  27591. var cameraName = camera.name;
  27592. if (this._cameras.indexOf(camera) === -1) {
  27593. this._cameras[cameraName] = camera;
  27594. }
  27595. else if (unique) {
  27596. indicesToDelete.push(i);
  27597. }
  27598. }
  27599. for (var i = 0; i < indicesToDelete.length; i++) {
  27600. cameras.splice(indicesToDelete[i], 1);
  27601. }
  27602. for (var renderEffectName in this._renderEffects) {
  27603. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27604. }
  27605. };
  27606. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27607. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27608. for (var renderEffectName in this._renderEffects) {
  27609. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27610. }
  27611. for (var i = 0; i < _cam.length; i++) {
  27612. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27613. }
  27614. };
  27615. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27616. var _this = this;
  27617. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27618. var pass = null;
  27619. for (var renderEffectName in this._renderEffects) {
  27620. pass = this._renderEffects[renderEffectName].getPass(passName);
  27621. if (pass != null) {
  27622. break;
  27623. }
  27624. }
  27625. if (pass === null) {
  27626. return;
  27627. }
  27628. for (var renderEffectName in this._renderEffects) {
  27629. this._renderEffects[renderEffectName]._disable(_cam);
  27630. }
  27631. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27632. for (var i = 0; i < _cam.length; i++) {
  27633. var camera = _cam[i];
  27634. var cameraName = camera.name;
  27635. 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); });
  27636. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27637. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27638. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27639. }
  27640. };
  27641. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27642. var _this = this;
  27643. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27644. for (var i = 0; i < _cam.length; i++) {
  27645. var camera = _cam[i];
  27646. var cameraName = camera.name;
  27647. 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); });
  27648. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27649. }
  27650. for (var renderEffectName in this._renderEffects) {
  27651. this._renderEffects[renderEffectName]._enable(_cam);
  27652. }
  27653. };
  27654. PostProcessRenderPipeline.prototype._update = function () {
  27655. for (var renderEffectName in this._renderEffects) {
  27656. this._renderEffects[renderEffectName]._update();
  27657. }
  27658. for (var i = 0; i < this._cameras.length; i++) {
  27659. var cameraName = this._cameras[i].name;
  27660. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27661. this._renderEffectsForIsolatedPass[cameraName]._update();
  27662. }
  27663. }
  27664. };
  27665. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27666. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27667. return PostProcessRenderPipeline;
  27668. })();
  27669. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27670. })(BABYLON || (BABYLON = {}));
  27671. var BABYLON;
  27672. (function (BABYLON) {
  27673. var PostProcessRenderPipelineManager = (function () {
  27674. function PostProcessRenderPipelineManager() {
  27675. this._renderPipelines = {};
  27676. }
  27677. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27678. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27679. };
  27680. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27681. var renderPipeline = this._renderPipelines[renderPipelineName];
  27682. if (!renderPipeline) {
  27683. return;
  27684. }
  27685. renderPipeline._attachCameras(cameras, unique);
  27686. };
  27687. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27688. var renderPipeline = this._renderPipelines[renderPipelineName];
  27689. if (!renderPipeline) {
  27690. return;
  27691. }
  27692. renderPipeline._detachCameras(cameras);
  27693. };
  27694. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27695. var renderPipeline = this._renderPipelines[renderPipelineName];
  27696. if (!renderPipeline) {
  27697. return;
  27698. }
  27699. renderPipeline._enableEffect(renderEffectName, cameras);
  27700. };
  27701. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27702. var renderPipeline = this._renderPipelines[renderPipelineName];
  27703. if (!renderPipeline) {
  27704. return;
  27705. }
  27706. renderPipeline._disableEffect(renderEffectName, cameras);
  27707. };
  27708. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27709. var renderPipeline = this._renderPipelines[renderPipelineName];
  27710. if (!renderPipeline) {
  27711. return;
  27712. }
  27713. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27714. };
  27715. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27716. var renderPipeline = this._renderPipelines[renderPipelineName];
  27717. if (!renderPipeline) {
  27718. return;
  27719. }
  27720. renderPipeline._disableDisplayOnlyPass(cameras);
  27721. };
  27722. PostProcessRenderPipelineManager.prototype.update = function () {
  27723. for (var renderPipelineName in this._renderPipelines) {
  27724. this._renderPipelines[renderPipelineName]._update();
  27725. }
  27726. };
  27727. return PostProcessRenderPipelineManager;
  27728. })();
  27729. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27730. })(BABYLON || (BABYLON = {}));
  27731. var BABYLON;
  27732. (function (BABYLON) {
  27733. var DisplayPassPostProcess = (function (_super) {
  27734. __extends(DisplayPassPostProcess, _super);
  27735. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27736. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27737. }
  27738. return DisplayPassPostProcess;
  27739. })(BABYLON.PostProcess);
  27740. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27741. })(BABYLON || (BABYLON = {}));
  27742. var BABYLON;
  27743. (function (BABYLON) {
  27744. var BoundingBoxRenderer = (function () {
  27745. function BoundingBoxRenderer(scene) {
  27746. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27747. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27748. this.showBackLines = true;
  27749. this.renderList = new BABYLON.SmartArray(32);
  27750. this._scene = scene;
  27751. }
  27752. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27753. if (this._colorShader) {
  27754. return;
  27755. }
  27756. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27757. attributes: ["position"],
  27758. uniforms: ["worldViewProjection", "color"]
  27759. });
  27760. var engine = this._scene.getEngine();
  27761. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27762. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27763. 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]);
  27764. };
  27765. BoundingBoxRenderer.prototype.reset = function () {
  27766. this.renderList.reset();
  27767. };
  27768. BoundingBoxRenderer.prototype.render = function () {
  27769. if (this.renderList.length === 0) {
  27770. return;
  27771. }
  27772. this._prepareRessources();
  27773. if (!this._colorShader.isReady()) {
  27774. return;
  27775. }
  27776. var engine = this._scene.getEngine();
  27777. engine.setDepthWrite(false);
  27778. this._colorShader._preBind();
  27779. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27780. var boundingBox = this.renderList.data[boundingBoxIndex];
  27781. var min = boundingBox.minimum;
  27782. var max = boundingBox.maximum;
  27783. var diff = max.subtract(min);
  27784. var median = min.add(diff.scale(0.5));
  27785. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27786. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27787. .multiply(boundingBox.getWorldMatrix());
  27788. // VBOs
  27789. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27790. if (this.showBackLines) {
  27791. // Back
  27792. engine.setDepthFunctionToGreaterOrEqual();
  27793. this._scene.resetCachedMaterial();
  27794. this._colorShader.setColor4("color", this.backColor.toColor4());
  27795. this._colorShader.bind(worldMatrix);
  27796. // Draw order
  27797. engine.draw(false, 0, 24);
  27798. }
  27799. // Front
  27800. engine.setDepthFunctionToLess();
  27801. this._scene.resetCachedMaterial();
  27802. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27803. this._colorShader.bind(worldMatrix);
  27804. // Draw order
  27805. engine.draw(false, 0, 24);
  27806. }
  27807. this._colorShader.unbind();
  27808. engine.setDepthFunctionToLessOrEqual();
  27809. engine.setDepthWrite(true);
  27810. };
  27811. BoundingBoxRenderer.prototype.dispose = function () {
  27812. if (!this._colorShader) {
  27813. return;
  27814. }
  27815. this._colorShader.dispose();
  27816. this._vb.dispose();
  27817. this._scene.getEngine()._releaseBuffer(this._ib);
  27818. };
  27819. return BoundingBoxRenderer;
  27820. })();
  27821. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27822. })(BABYLON || (BABYLON = {}));
  27823. var BABYLON;
  27824. (function (BABYLON) {
  27825. var Condition = (function () {
  27826. function Condition(actionManager) {
  27827. this._actionManager = actionManager;
  27828. }
  27829. Condition.prototype.isValid = function () {
  27830. return true;
  27831. };
  27832. Condition.prototype._getProperty = function (propertyPath) {
  27833. return this._actionManager._getProperty(propertyPath);
  27834. };
  27835. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27836. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27837. };
  27838. return Condition;
  27839. })();
  27840. BABYLON.Condition = Condition;
  27841. var ValueCondition = (function (_super) {
  27842. __extends(ValueCondition, _super);
  27843. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27844. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27845. _super.call(this, actionManager);
  27846. this.propertyPath = propertyPath;
  27847. this.value = value;
  27848. this.operator = operator;
  27849. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27850. this._property = this._getProperty(this.propertyPath);
  27851. }
  27852. Object.defineProperty(ValueCondition, "IsEqual", {
  27853. get: function () {
  27854. return ValueCondition._IsEqual;
  27855. },
  27856. enumerable: true,
  27857. configurable: true
  27858. });
  27859. Object.defineProperty(ValueCondition, "IsDifferent", {
  27860. get: function () {
  27861. return ValueCondition._IsDifferent;
  27862. },
  27863. enumerable: true,
  27864. configurable: true
  27865. });
  27866. Object.defineProperty(ValueCondition, "IsGreater", {
  27867. get: function () {
  27868. return ValueCondition._IsGreater;
  27869. },
  27870. enumerable: true,
  27871. configurable: true
  27872. });
  27873. Object.defineProperty(ValueCondition, "IsLesser", {
  27874. get: function () {
  27875. return ValueCondition._IsLesser;
  27876. },
  27877. enumerable: true,
  27878. configurable: true
  27879. });
  27880. // Methods
  27881. ValueCondition.prototype.isValid = function () {
  27882. switch (this.operator) {
  27883. case ValueCondition.IsGreater:
  27884. return this._target[this._property] > this.value;
  27885. case ValueCondition.IsLesser:
  27886. return this._target[this._property] < this.value;
  27887. case ValueCondition.IsEqual:
  27888. case ValueCondition.IsDifferent:
  27889. var check;
  27890. if (this.value.equals) {
  27891. check = this.value.equals(this._target[this._property]);
  27892. }
  27893. else {
  27894. check = this.value === this._target[this._property];
  27895. }
  27896. return this.operator === ValueCondition.IsEqual ? check : !check;
  27897. }
  27898. return false;
  27899. };
  27900. // Statics
  27901. ValueCondition._IsEqual = 0;
  27902. ValueCondition._IsDifferent = 1;
  27903. ValueCondition._IsGreater = 2;
  27904. ValueCondition._IsLesser = 3;
  27905. return ValueCondition;
  27906. })(Condition);
  27907. BABYLON.ValueCondition = ValueCondition;
  27908. var PredicateCondition = (function (_super) {
  27909. __extends(PredicateCondition, _super);
  27910. function PredicateCondition(actionManager, predicate) {
  27911. _super.call(this, actionManager);
  27912. this.predicate = predicate;
  27913. }
  27914. PredicateCondition.prototype.isValid = function () {
  27915. return this.predicate();
  27916. };
  27917. return PredicateCondition;
  27918. })(Condition);
  27919. BABYLON.PredicateCondition = PredicateCondition;
  27920. var StateCondition = (function (_super) {
  27921. __extends(StateCondition, _super);
  27922. function StateCondition(actionManager, target, value) {
  27923. _super.call(this, actionManager);
  27924. this.value = value;
  27925. this._target = target;
  27926. }
  27927. // Methods
  27928. StateCondition.prototype.isValid = function () {
  27929. return this._target.state === this.value;
  27930. };
  27931. return StateCondition;
  27932. })(Condition);
  27933. BABYLON.StateCondition = StateCondition;
  27934. })(BABYLON || (BABYLON = {}));
  27935. var BABYLON;
  27936. (function (BABYLON) {
  27937. var Action = (function () {
  27938. function Action(triggerOptions, condition) {
  27939. this.triggerOptions = triggerOptions;
  27940. if (triggerOptions.parameter) {
  27941. this.trigger = triggerOptions.trigger;
  27942. this._triggerParameter = triggerOptions.parameter;
  27943. }
  27944. else {
  27945. this.trigger = triggerOptions;
  27946. }
  27947. this._nextActiveAction = this;
  27948. this._condition = condition;
  27949. }
  27950. // Methods
  27951. Action.prototype._prepare = function () {
  27952. };
  27953. Action.prototype.getTriggerParameter = function () {
  27954. return this._triggerParameter;
  27955. };
  27956. Action.prototype._executeCurrent = function (evt) {
  27957. if (this._nextActiveAction._condition) {
  27958. var condition = this._nextActiveAction._condition;
  27959. var currentRenderId = this._actionManager.getScene().getRenderId();
  27960. // We cache the current evaluation for the current frame
  27961. if (condition._evaluationId === currentRenderId) {
  27962. if (!condition._currentResult) {
  27963. return;
  27964. }
  27965. }
  27966. else {
  27967. condition._evaluationId = currentRenderId;
  27968. if (!condition.isValid()) {
  27969. condition._currentResult = false;
  27970. return;
  27971. }
  27972. condition._currentResult = true;
  27973. }
  27974. }
  27975. this._nextActiveAction.execute(evt);
  27976. if (this._nextActiveAction._child) {
  27977. if (!this._nextActiveAction._child._actionManager) {
  27978. this._nextActiveAction._child._actionManager = this._actionManager;
  27979. }
  27980. this._nextActiveAction = this._nextActiveAction._child;
  27981. }
  27982. else {
  27983. this._nextActiveAction = this;
  27984. }
  27985. };
  27986. Action.prototype.execute = function (evt) {
  27987. };
  27988. Action.prototype.then = function (action) {
  27989. this._child = action;
  27990. action._actionManager = this._actionManager;
  27991. action._prepare();
  27992. return action;
  27993. };
  27994. Action.prototype._getProperty = function (propertyPath) {
  27995. return this._actionManager._getProperty(propertyPath);
  27996. };
  27997. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27998. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27999. };
  28000. return Action;
  28001. })();
  28002. BABYLON.Action = Action;
  28003. })(BABYLON || (BABYLON = {}));
  28004. var BABYLON;
  28005. (function (BABYLON) {
  28006. /**
  28007. * ActionEvent is the event beint sent when an action is triggered.
  28008. */
  28009. var ActionEvent = (function () {
  28010. /**
  28011. * @constructor
  28012. * @param source The mesh that triggered the action.
  28013. * @param pointerX the X mouse cursor position at the time of the event
  28014. * @param pointerY the Y mouse cursor position at the time of the event
  28015. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28016. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28017. */
  28018. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28019. this.source = source;
  28020. this.pointerX = pointerX;
  28021. this.pointerY = pointerY;
  28022. this.meshUnderPointer = meshUnderPointer;
  28023. this.sourceEvent = sourceEvent;
  28024. this.additionalData = additionalData;
  28025. }
  28026. /**
  28027. * Helper function to auto-create an ActionEvent from a source mesh.
  28028. * @param source the source mesh that triggered the event
  28029. * @param evt {Event} The original (browser) event
  28030. */
  28031. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28032. var scene = source.getScene();
  28033. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28034. };
  28035. /**
  28036. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28037. * @param scene the scene where the event occurred
  28038. * @param evt {Event} The original (browser) event
  28039. */
  28040. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28041. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28042. };
  28043. return ActionEvent;
  28044. })();
  28045. BABYLON.ActionEvent = ActionEvent;
  28046. /**
  28047. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28048. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28049. */
  28050. var ActionManager = (function () {
  28051. function ActionManager(scene) {
  28052. // Members
  28053. this.actions = new Array();
  28054. this._scene = scene;
  28055. scene._actionManagers.push(this);
  28056. }
  28057. Object.defineProperty(ActionManager, "NothingTrigger", {
  28058. get: function () {
  28059. return ActionManager._NothingTrigger;
  28060. },
  28061. enumerable: true,
  28062. configurable: true
  28063. });
  28064. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28065. get: function () {
  28066. return ActionManager._OnPickTrigger;
  28067. },
  28068. enumerable: true,
  28069. configurable: true
  28070. });
  28071. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28072. get: function () {
  28073. return ActionManager._OnLeftPickTrigger;
  28074. },
  28075. enumerable: true,
  28076. configurable: true
  28077. });
  28078. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28079. get: function () {
  28080. return ActionManager._OnRightPickTrigger;
  28081. },
  28082. enumerable: true,
  28083. configurable: true
  28084. });
  28085. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28086. get: function () {
  28087. return ActionManager._OnCenterPickTrigger;
  28088. },
  28089. enumerable: true,
  28090. configurable: true
  28091. });
  28092. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28093. get: function () {
  28094. return ActionManager._OnPointerOverTrigger;
  28095. },
  28096. enumerable: true,
  28097. configurable: true
  28098. });
  28099. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28100. get: function () {
  28101. return ActionManager._OnPointerOutTrigger;
  28102. },
  28103. enumerable: true,
  28104. configurable: true
  28105. });
  28106. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28107. get: function () {
  28108. return ActionManager._OnEveryFrameTrigger;
  28109. },
  28110. enumerable: true,
  28111. configurable: true
  28112. });
  28113. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28114. get: function () {
  28115. return ActionManager._OnIntersectionEnterTrigger;
  28116. },
  28117. enumerable: true,
  28118. configurable: true
  28119. });
  28120. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28121. get: function () {
  28122. return ActionManager._OnIntersectionExitTrigger;
  28123. },
  28124. enumerable: true,
  28125. configurable: true
  28126. });
  28127. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28128. get: function () {
  28129. return ActionManager._OnKeyDownTrigger;
  28130. },
  28131. enumerable: true,
  28132. configurable: true
  28133. });
  28134. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28135. get: function () {
  28136. return ActionManager._OnKeyUpTrigger;
  28137. },
  28138. enumerable: true,
  28139. configurable: true
  28140. });
  28141. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28142. get: function () {
  28143. return ActionManager._OnPickUpTrigger;
  28144. },
  28145. enumerable: true,
  28146. configurable: true
  28147. });
  28148. // Methods
  28149. ActionManager.prototype.dispose = function () {
  28150. var index = this._scene._actionManagers.indexOf(this);
  28151. if (index > -1) {
  28152. this._scene._actionManagers.splice(index, 1);
  28153. }
  28154. };
  28155. ActionManager.prototype.getScene = function () {
  28156. return this._scene;
  28157. };
  28158. /**
  28159. * Does this action manager handles actions of any of the given triggers
  28160. * @param {number[]} triggers - the triggers to be tested
  28161. * @return {boolean} whether one (or more) of the triggers is handeled
  28162. */
  28163. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28164. for (var index = 0; index < this.actions.length; index++) {
  28165. var action = this.actions[index];
  28166. if (triggers.indexOf(action.trigger) > -1) {
  28167. return true;
  28168. }
  28169. }
  28170. return false;
  28171. };
  28172. /**
  28173. * Does this action manager handles actions of a given trigger
  28174. * @param {number} trigger - the trigger to be tested
  28175. * @return {boolean} whether the trigger is handeled
  28176. */
  28177. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28178. for (var index = 0; index < this.actions.length; index++) {
  28179. var action = this.actions[index];
  28180. if (action.trigger === trigger) {
  28181. return true;
  28182. }
  28183. }
  28184. return false;
  28185. };
  28186. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28187. /**
  28188. * Does this action manager has pointer triggers
  28189. * @return {boolean} whether or not it has pointer triggers
  28190. */
  28191. get: function () {
  28192. for (var index = 0; index < this.actions.length; index++) {
  28193. var action = this.actions[index];
  28194. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28195. return true;
  28196. }
  28197. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28198. return true;
  28199. }
  28200. }
  28201. return false;
  28202. },
  28203. enumerable: true,
  28204. configurable: true
  28205. });
  28206. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28207. /**
  28208. * Does this action manager has pick triggers
  28209. * @return {boolean} whether or not it has pick triggers
  28210. */
  28211. get: function () {
  28212. for (var index = 0; index < this.actions.length; index++) {
  28213. var action = this.actions[index];
  28214. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28215. return true;
  28216. }
  28217. }
  28218. return false;
  28219. },
  28220. enumerable: true,
  28221. configurable: true
  28222. });
  28223. /**
  28224. * Registers an action to this action manager
  28225. * @param {BABYLON.Action} action - the action to be registered
  28226. * @return {BABYLON.Action} the action amended (prepared) after registration
  28227. */
  28228. ActionManager.prototype.registerAction = function (action) {
  28229. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28230. if (this.getScene().actionManager !== this) {
  28231. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28232. return null;
  28233. }
  28234. }
  28235. this.actions.push(action);
  28236. action._actionManager = this;
  28237. action._prepare();
  28238. return action;
  28239. };
  28240. /**
  28241. * Process a specific trigger
  28242. * @param {number} trigger - the trigger to process
  28243. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28244. */
  28245. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28246. for (var index = 0; index < this.actions.length; index++) {
  28247. var action = this.actions[index];
  28248. if (action.trigger === trigger) {
  28249. if (trigger === ActionManager.OnKeyUpTrigger
  28250. || trigger === ActionManager.OnKeyDownTrigger) {
  28251. var parameter = action.getTriggerParameter();
  28252. if (parameter) {
  28253. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28254. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28255. if (actualkey !== parameter.toLowerCase()) {
  28256. continue;
  28257. }
  28258. }
  28259. }
  28260. action._executeCurrent(evt);
  28261. }
  28262. }
  28263. };
  28264. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28265. var properties = propertyPath.split(".");
  28266. for (var index = 0; index < properties.length - 1; index++) {
  28267. target = target[properties[index]];
  28268. }
  28269. return target;
  28270. };
  28271. ActionManager.prototype._getProperty = function (propertyPath) {
  28272. var properties = propertyPath.split(".");
  28273. return properties[properties.length - 1];
  28274. };
  28275. // Statics
  28276. ActionManager._NothingTrigger = 0;
  28277. ActionManager._OnPickTrigger = 1;
  28278. ActionManager._OnLeftPickTrigger = 2;
  28279. ActionManager._OnRightPickTrigger = 3;
  28280. ActionManager._OnCenterPickTrigger = 4;
  28281. ActionManager._OnPointerOverTrigger = 5;
  28282. ActionManager._OnPointerOutTrigger = 6;
  28283. ActionManager._OnEveryFrameTrigger = 7;
  28284. ActionManager._OnIntersectionEnterTrigger = 8;
  28285. ActionManager._OnIntersectionExitTrigger = 9;
  28286. ActionManager._OnKeyDownTrigger = 10;
  28287. ActionManager._OnKeyUpTrigger = 11;
  28288. ActionManager._OnPickUpTrigger = 12;
  28289. return ActionManager;
  28290. })();
  28291. BABYLON.ActionManager = ActionManager;
  28292. })(BABYLON || (BABYLON = {}));
  28293. var BABYLON;
  28294. (function (BABYLON) {
  28295. var InterpolateValueAction = (function (_super) {
  28296. __extends(InterpolateValueAction, _super);
  28297. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28298. if (duration === void 0) { duration = 1000; }
  28299. _super.call(this, triggerOptions, condition);
  28300. this.propertyPath = propertyPath;
  28301. this.value = value;
  28302. this.duration = duration;
  28303. this.stopOtherAnimations = stopOtherAnimations;
  28304. this._target = target;
  28305. }
  28306. InterpolateValueAction.prototype._prepare = function () {
  28307. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28308. this._property = this._getProperty(this.propertyPath);
  28309. };
  28310. InterpolateValueAction.prototype.execute = function () {
  28311. var scene = this._actionManager.getScene();
  28312. var keys = [
  28313. {
  28314. frame: 0,
  28315. value: this._target[this._property]
  28316. }, {
  28317. frame: 100,
  28318. value: this.value
  28319. }
  28320. ];
  28321. var dataType;
  28322. if (typeof this.value === "number") {
  28323. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28324. }
  28325. else if (this.value instanceof BABYLON.Color3) {
  28326. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28327. }
  28328. else if (this.value instanceof BABYLON.Vector3) {
  28329. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28330. }
  28331. else if (this.value instanceof BABYLON.Matrix) {
  28332. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28333. }
  28334. else if (this.value instanceof BABYLON.Quaternion) {
  28335. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28336. }
  28337. else {
  28338. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28339. return;
  28340. }
  28341. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28342. animation.setKeys(keys);
  28343. if (this.stopOtherAnimations) {
  28344. scene.stopAnimation(this._target);
  28345. }
  28346. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28347. };
  28348. return InterpolateValueAction;
  28349. })(BABYLON.Action);
  28350. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28351. })(BABYLON || (BABYLON = {}));
  28352. var BABYLON;
  28353. (function (BABYLON) {
  28354. var SwitchBooleanAction = (function (_super) {
  28355. __extends(SwitchBooleanAction, _super);
  28356. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28357. _super.call(this, triggerOptions, condition);
  28358. this.propertyPath = propertyPath;
  28359. this._target = target;
  28360. }
  28361. SwitchBooleanAction.prototype._prepare = function () {
  28362. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28363. this._property = this._getProperty(this.propertyPath);
  28364. };
  28365. SwitchBooleanAction.prototype.execute = function () {
  28366. this._target[this._property] = !this._target[this._property];
  28367. };
  28368. return SwitchBooleanAction;
  28369. })(BABYLON.Action);
  28370. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28371. var SetStateAction = (function (_super) {
  28372. __extends(SetStateAction, _super);
  28373. function SetStateAction(triggerOptions, target, value, condition) {
  28374. _super.call(this, triggerOptions, condition);
  28375. this.value = value;
  28376. this._target = target;
  28377. }
  28378. SetStateAction.prototype.execute = function () {
  28379. this._target.state = this.value;
  28380. };
  28381. return SetStateAction;
  28382. })(BABYLON.Action);
  28383. BABYLON.SetStateAction = SetStateAction;
  28384. var SetValueAction = (function (_super) {
  28385. __extends(SetValueAction, _super);
  28386. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28387. _super.call(this, triggerOptions, condition);
  28388. this.propertyPath = propertyPath;
  28389. this.value = value;
  28390. this._target = target;
  28391. }
  28392. SetValueAction.prototype._prepare = function () {
  28393. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28394. this._property = this._getProperty(this.propertyPath);
  28395. };
  28396. SetValueAction.prototype.execute = function () {
  28397. this._target[this._property] = this.value;
  28398. };
  28399. return SetValueAction;
  28400. })(BABYLON.Action);
  28401. BABYLON.SetValueAction = SetValueAction;
  28402. var IncrementValueAction = (function (_super) {
  28403. __extends(IncrementValueAction, _super);
  28404. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28405. _super.call(this, triggerOptions, condition);
  28406. this.propertyPath = propertyPath;
  28407. this.value = value;
  28408. this._target = target;
  28409. }
  28410. IncrementValueAction.prototype._prepare = function () {
  28411. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28412. this._property = this._getProperty(this.propertyPath);
  28413. if (typeof this._target[this._property] !== "number") {
  28414. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28415. }
  28416. };
  28417. IncrementValueAction.prototype.execute = function () {
  28418. this._target[this._property] += this.value;
  28419. };
  28420. return IncrementValueAction;
  28421. })(BABYLON.Action);
  28422. BABYLON.IncrementValueAction = IncrementValueAction;
  28423. var PlayAnimationAction = (function (_super) {
  28424. __extends(PlayAnimationAction, _super);
  28425. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28426. _super.call(this, triggerOptions, condition);
  28427. this.from = from;
  28428. this.to = to;
  28429. this.loop = loop;
  28430. this._target = target;
  28431. }
  28432. PlayAnimationAction.prototype._prepare = function () {
  28433. };
  28434. PlayAnimationAction.prototype.execute = function () {
  28435. var scene = this._actionManager.getScene();
  28436. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28437. };
  28438. return PlayAnimationAction;
  28439. })(BABYLON.Action);
  28440. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28441. var StopAnimationAction = (function (_super) {
  28442. __extends(StopAnimationAction, _super);
  28443. function StopAnimationAction(triggerOptions, target, condition) {
  28444. _super.call(this, triggerOptions, condition);
  28445. this._target = target;
  28446. }
  28447. StopAnimationAction.prototype._prepare = function () {
  28448. };
  28449. StopAnimationAction.prototype.execute = function () {
  28450. var scene = this._actionManager.getScene();
  28451. scene.stopAnimation(this._target);
  28452. };
  28453. return StopAnimationAction;
  28454. })(BABYLON.Action);
  28455. BABYLON.StopAnimationAction = StopAnimationAction;
  28456. var DoNothingAction = (function (_super) {
  28457. __extends(DoNothingAction, _super);
  28458. function DoNothingAction(triggerOptions, condition) {
  28459. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28460. _super.call(this, triggerOptions, condition);
  28461. }
  28462. DoNothingAction.prototype.execute = function () {
  28463. };
  28464. return DoNothingAction;
  28465. })(BABYLON.Action);
  28466. BABYLON.DoNothingAction = DoNothingAction;
  28467. var CombineAction = (function (_super) {
  28468. __extends(CombineAction, _super);
  28469. function CombineAction(triggerOptions, children, condition) {
  28470. _super.call(this, triggerOptions, condition);
  28471. this.children = children;
  28472. }
  28473. CombineAction.prototype._prepare = function () {
  28474. for (var index = 0; index < this.children.length; index++) {
  28475. this.children[index]._actionManager = this._actionManager;
  28476. this.children[index]._prepare();
  28477. }
  28478. };
  28479. CombineAction.prototype.execute = function (evt) {
  28480. for (var index = 0; index < this.children.length; index++) {
  28481. this.children[index].execute(evt);
  28482. }
  28483. };
  28484. return CombineAction;
  28485. })(BABYLON.Action);
  28486. BABYLON.CombineAction = CombineAction;
  28487. var ExecuteCodeAction = (function (_super) {
  28488. __extends(ExecuteCodeAction, _super);
  28489. function ExecuteCodeAction(triggerOptions, func, condition) {
  28490. _super.call(this, triggerOptions, condition);
  28491. this.func = func;
  28492. }
  28493. ExecuteCodeAction.prototype.execute = function (evt) {
  28494. this.func(evt);
  28495. };
  28496. return ExecuteCodeAction;
  28497. })(BABYLON.Action);
  28498. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28499. var SetParentAction = (function (_super) {
  28500. __extends(SetParentAction, _super);
  28501. function SetParentAction(triggerOptions, target, parent, condition) {
  28502. _super.call(this, triggerOptions, condition);
  28503. this._target = target;
  28504. this._parent = parent;
  28505. }
  28506. SetParentAction.prototype._prepare = function () {
  28507. };
  28508. SetParentAction.prototype.execute = function () {
  28509. if (this._target.parent === this._parent) {
  28510. return;
  28511. }
  28512. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28513. invertParentWorldMatrix.invert();
  28514. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28515. this._target.parent = this._parent;
  28516. };
  28517. return SetParentAction;
  28518. })(BABYLON.Action);
  28519. BABYLON.SetParentAction = SetParentAction;
  28520. var PlaySoundAction = (function (_super) {
  28521. __extends(PlaySoundAction, _super);
  28522. function PlaySoundAction(triggerOptions, sound, condition) {
  28523. _super.call(this, triggerOptions, condition);
  28524. this._sound = sound;
  28525. }
  28526. PlaySoundAction.prototype._prepare = function () {
  28527. };
  28528. PlaySoundAction.prototype.execute = function () {
  28529. if (this._sound !== undefined)
  28530. this._sound.play();
  28531. };
  28532. return PlaySoundAction;
  28533. })(BABYLON.Action);
  28534. BABYLON.PlaySoundAction = PlaySoundAction;
  28535. var StopSoundAction = (function (_super) {
  28536. __extends(StopSoundAction, _super);
  28537. function StopSoundAction(triggerOptions, sound, condition) {
  28538. _super.call(this, triggerOptions, condition);
  28539. this._sound = sound;
  28540. }
  28541. StopSoundAction.prototype._prepare = function () {
  28542. };
  28543. StopSoundAction.prototype.execute = function () {
  28544. if (this._sound !== undefined)
  28545. this._sound.stop();
  28546. };
  28547. return StopSoundAction;
  28548. })(BABYLON.Action);
  28549. BABYLON.StopSoundAction = StopSoundAction;
  28550. })(BABYLON || (BABYLON = {}));
  28551. var BABYLON;
  28552. (function (BABYLON) {
  28553. var Geometry = (function () {
  28554. function Geometry(id, scene, vertexData, updatable, mesh) {
  28555. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28556. this._totalVertices = 0;
  28557. this._indices = [];
  28558. this._isDisposed = false;
  28559. this.id = id;
  28560. this._engine = scene.getEngine();
  28561. this._meshes = [];
  28562. this._scene = scene;
  28563. // vertexData
  28564. if (vertexData) {
  28565. this.setAllVerticesData(vertexData, updatable);
  28566. }
  28567. else {
  28568. this._totalVertices = 0;
  28569. this._indices = [];
  28570. }
  28571. // applyToMesh
  28572. if (mesh) {
  28573. this.applyToMesh(mesh);
  28574. mesh.computeWorldMatrix(true);
  28575. }
  28576. }
  28577. Geometry.prototype.getScene = function () {
  28578. return this._scene;
  28579. };
  28580. Geometry.prototype.getEngine = function () {
  28581. return this._engine;
  28582. };
  28583. Geometry.prototype.isReady = function () {
  28584. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28585. };
  28586. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28587. vertexData.applyToGeometry(this, updatable);
  28588. this.notifyUpdate();
  28589. };
  28590. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28591. this._vertexBuffers = this._vertexBuffers || {};
  28592. if (this._vertexBuffers[kind]) {
  28593. this._vertexBuffers[kind].dispose();
  28594. }
  28595. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28596. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28597. stride = this._vertexBuffers[kind].getStrideSize();
  28598. this._totalVertices = data.length / stride;
  28599. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28600. var meshes = this._meshes;
  28601. var numOfMeshes = meshes.length;
  28602. for (var index = 0; index < numOfMeshes; index++) {
  28603. var mesh = meshes[index];
  28604. mesh._resetPointsArrayCache();
  28605. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28606. mesh._createGlobalSubMesh();
  28607. mesh.computeWorldMatrix(true);
  28608. }
  28609. }
  28610. this.notifyUpdate(kind);
  28611. };
  28612. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28613. var vertexBuffer = this.getVertexBuffer(kind);
  28614. if (!vertexBuffer) {
  28615. return;
  28616. }
  28617. vertexBuffer.updateDirectly(data, offset);
  28618. this.notifyUpdate(kind);
  28619. };
  28620. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28621. var vertexBuffer = this.getVertexBuffer(kind);
  28622. if (!vertexBuffer) {
  28623. return;
  28624. }
  28625. vertexBuffer.update(data);
  28626. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28627. var extend;
  28628. var stride = vertexBuffer.getStrideSize();
  28629. this._totalVertices = data.length / stride;
  28630. if (updateExtends) {
  28631. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28632. }
  28633. var meshes = this._meshes;
  28634. var numOfMeshes = meshes.length;
  28635. for (var index = 0; index < numOfMeshes; index++) {
  28636. var mesh = meshes[index];
  28637. mesh._resetPointsArrayCache();
  28638. if (updateExtends) {
  28639. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28640. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28641. var subMesh = mesh.subMeshes[subIndex];
  28642. subMesh.refreshBoundingInfo();
  28643. }
  28644. }
  28645. }
  28646. }
  28647. this.notifyUpdate(kind);
  28648. };
  28649. Geometry.prototype.getTotalVertices = function () {
  28650. if (!this.isReady()) {
  28651. return 0;
  28652. }
  28653. return this._totalVertices;
  28654. };
  28655. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28656. var vertexBuffer = this.getVertexBuffer(kind);
  28657. if (!vertexBuffer) {
  28658. return null;
  28659. }
  28660. var orig = vertexBuffer.getData();
  28661. if (!copyWhenShared || this._meshes.length === 1) {
  28662. return orig;
  28663. }
  28664. else {
  28665. var len = orig.length;
  28666. var copy = [];
  28667. for (var i = 0; i < len; i++) {
  28668. copy.push(orig[i]);
  28669. }
  28670. return copy;
  28671. }
  28672. };
  28673. Geometry.prototype.getVertexBuffer = function (kind) {
  28674. if (!this.isReady()) {
  28675. return null;
  28676. }
  28677. return this._vertexBuffers[kind];
  28678. };
  28679. Geometry.prototype.getVertexBuffers = function () {
  28680. if (!this.isReady()) {
  28681. return null;
  28682. }
  28683. return this._vertexBuffers;
  28684. };
  28685. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28686. if (!this._vertexBuffers) {
  28687. if (this._delayInfo) {
  28688. return this._delayInfo.indexOf(kind) !== -1;
  28689. }
  28690. return false;
  28691. }
  28692. return this._vertexBuffers[kind] !== undefined;
  28693. };
  28694. Geometry.prototype.getVerticesDataKinds = function () {
  28695. var result = [];
  28696. if (!this._vertexBuffers && this._delayInfo) {
  28697. for (var kind in this._delayInfo) {
  28698. result.push(kind);
  28699. }
  28700. }
  28701. else {
  28702. for (kind in this._vertexBuffers) {
  28703. result.push(kind);
  28704. }
  28705. }
  28706. return result;
  28707. };
  28708. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28709. if (this._indexBuffer) {
  28710. this._engine._releaseBuffer(this._indexBuffer);
  28711. }
  28712. this._indices = indices;
  28713. if (this._meshes.length !== 0 && this._indices) {
  28714. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28715. }
  28716. if (totalVertices !== undefined) {
  28717. this._totalVertices = totalVertices;
  28718. }
  28719. var meshes = this._meshes;
  28720. var numOfMeshes = meshes.length;
  28721. for (var index = 0; index < numOfMeshes; index++) {
  28722. meshes[index]._createGlobalSubMesh();
  28723. }
  28724. this.notifyUpdate();
  28725. };
  28726. Geometry.prototype.getTotalIndices = function () {
  28727. if (!this.isReady()) {
  28728. return 0;
  28729. }
  28730. return this._indices.length;
  28731. };
  28732. Geometry.prototype.getIndices = function (copyWhenShared) {
  28733. if (!this.isReady()) {
  28734. return null;
  28735. }
  28736. var orig = this._indices;
  28737. if (!copyWhenShared || this._meshes.length === 1) {
  28738. return orig;
  28739. }
  28740. else {
  28741. var len = orig.length;
  28742. var copy = [];
  28743. for (var i = 0; i < len; i++) {
  28744. copy.push(orig[i]);
  28745. }
  28746. return copy;
  28747. }
  28748. };
  28749. Geometry.prototype.getIndexBuffer = function () {
  28750. if (!this.isReady()) {
  28751. return null;
  28752. }
  28753. return this._indexBuffer;
  28754. };
  28755. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28756. var meshes = this._meshes;
  28757. var index = meshes.indexOf(mesh);
  28758. if (index === -1) {
  28759. return;
  28760. }
  28761. for (var kind in this._vertexBuffers) {
  28762. this._vertexBuffers[kind].dispose();
  28763. }
  28764. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28765. this._indexBuffer = null;
  28766. }
  28767. meshes.splice(index, 1);
  28768. mesh._geometry = null;
  28769. if (meshes.length === 0 && shouldDispose) {
  28770. this.dispose();
  28771. }
  28772. };
  28773. Geometry.prototype.applyToMesh = function (mesh) {
  28774. if (mesh._geometry === this) {
  28775. return;
  28776. }
  28777. var previousGeometry = mesh._geometry;
  28778. if (previousGeometry) {
  28779. previousGeometry.releaseForMesh(mesh);
  28780. }
  28781. var meshes = this._meshes;
  28782. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28783. mesh._geometry = this;
  28784. this._scene.pushGeometry(this);
  28785. meshes.push(mesh);
  28786. if (this.isReady()) {
  28787. this._applyToMesh(mesh);
  28788. }
  28789. else {
  28790. mesh._boundingInfo = this._boundingInfo;
  28791. }
  28792. };
  28793. Geometry.prototype._applyToMesh = function (mesh) {
  28794. var numOfMeshes = this._meshes.length;
  28795. // vertexBuffers
  28796. for (var kind in this._vertexBuffers) {
  28797. if (numOfMeshes === 1) {
  28798. this._vertexBuffers[kind].create();
  28799. }
  28800. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28801. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28802. mesh._resetPointsArrayCache();
  28803. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28804. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28805. mesh._createGlobalSubMesh();
  28806. //bounding info was just created again, world matrix should be applied again.
  28807. mesh._updateBoundingInfo();
  28808. }
  28809. }
  28810. // indexBuffer
  28811. if (numOfMeshes === 1 && this._indices) {
  28812. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28813. }
  28814. if (this._indexBuffer) {
  28815. this._indexBuffer.references = numOfMeshes;
  28816. }
  28817. };
  28818. Geometry.prototype.notifyUpdate = function (kind) {
  28819. if (this.onGeometryUpdated) {
  28820. this.onGeometryUpdated(this, kind);
  28821. }
  28822. };
  28823. Geometry.prototype.load = function (scene, onLoaded) {
  28824. var _this = this;
  28825. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28826. return;
  28827. }
  28828. if (this.isReady()) {
  28829. if (onLoaded) {
  28830. onLoaded();
  28831. }
  28832. return;
  28833. }
  28834. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28835. scene._addPendingData(this);
  28836. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28837. _this._delayLoadingFunction(JSON.parse(data), _this);
  28838. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28839. _this._delayInfo = [];
  28840. scene._removePendingData(_this);
  28841. var meshes = _this._meshes;
  28842. var numOfMeshes = meshes.length;
  28843. for (var index = 0; index < numOfMeshes; index++) {
  28844. _this._applyToMesh(meshes[index]);
  28845. }
  28846. if (onLoaded) {
  28847. onLoaded();
  28848. }
  28849. }, function () { }, scene.database);
  28850. };
  28851. Geometry.prototype.isDisposed = function () {
  28852. return this._isDisposed;
  28853. };
  28854. Geometry.prototype.dispose = function () {
  28855. var meshes = this._meshes;
  28856. var numOfMeshes = meshes.length;
  28857. var index;
  28858. for (index = 0; index < numOfMeshes; index++) {
  28859. this.releaseForMesh(meshes[index]);
  28860. }
  28861. this._meshes = [];
  28862. for (var kind in this._vertexBuffers) {
  28863. this._vertexBuffers[kind].dispose();
  28864. }
  28865. this._vertexBuffers = [];
  28866. this._totalVertices = 0;
  28867. if (this._indexBuffer) {
  28868. this._engine._releaseBuffer(this._indexBuffer);
  28869. }
  28870. this._indexBuffer = null;
  28871. this._indices = [];
  28872. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28873. this.delayLoadingFile = null;
  28874. this._delayLoadingFunction = null;
  28875. this._delayInfo = [];
  28876. this._boundingInfo = null; // todo: .dispose()
  28877. this._scene.removeGeometry(this);
  28878. this._isDisposed = true;
  28879. };
  28880. Geometry.prototype.copy = function (id) {
  28881. var vertexData = new BABYLON.VertexData();
  28882. vertexData.indices = [];
  28883. var indices = this.getIndices();
  28884. for (var index = 0; index < indices.length; index++) {
  28885. vertexData.indices.push(indices[index]);
  28886. }
  28887. var updatable = false;
  28888. var stopChecking = false;
  28889. for (var kind in this._vertexBuffers) {
  28890. // using slice() to make a copy of the array and not just reference it
  28891. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28892. if (!stopChecking) {
  28893. updatable = this.getVertexBuffer(kind).isUpdatable();
  28894. stopChecking = !updatable;
  28895. }
  28896. }
  28897. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28898. geometry.delayLoadState = this.delayLoadState;
  28899. geometry.delayLoadingFile = this.delayLoadingFile;
  28900. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28901. for (kind in this._delayInfo) {
  28902. geometry._delayInfo = geometry._delayInfo || [];
  28903. geometry._delayInfo.push(kind);
  28904. }
  28905. // Bounding info
  28906. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28907. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28908. return geometry;
  28909. };
  28910. // Statics
  28911. Geometry.ExtractFromMesh = function (mesh, id) {
  28912. var geometry = mesh._geometry;
  28913. if (!geometry) {
  28914. return null;
  28915. }
  28916. return geometry.copy(id);
  28917. };
  28918. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28919. // be aware Math.random() could cause collisions
  28920. Geometry.RandomId = function () {
  28921. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28922. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28923. return v.toString(16);
  28924. });
  28925. };
  28926. return Geometry;
  28927. })();
  28928. BABYLON.Geometry = Geometry;
  28929. /////// Primitives //////////////////////////////////////////////
  28930. var Geometry;
  28931. (function (Geometry) {
  28932. var Primitives;
  28933. (function (Primitives) {
  28934. /// Abstract class
  28935. var _Primitive = (function (_super) {
  28936. __extends(_Primitive, _super);
  28937. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28938. this._beingRegenerated = true;
  28939. this._canBeRegenerated = canBeRegenerated;
  28940. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28941. this._beingRegenerated = false;
  28942. }
  28943. _Primitive.prototype.canBeRegenerated = function () {
  28944. return this._canBeRegenerated;
  28945. };
  28946. _Primitive.prototype.regenerate = function () {
  28947. if (!this._canBeRegenerated) {
  28948. return;
  28949. }
  28950. this._beingRegenerated = true;
  28951. this.setAllVerticesData(this._regenerateVertexData(), false);
  28952. this._beingRegenerated = false;
  28953. };
  28954. _Primitive.prototype.asNewGeometry = function (id) {
  28955. return _super.prototype.copy.call(this, id);
  28956. };
  28957. // overrides
  28958. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28959. if (!this._beingRegenerated) {
  28960. return;
  28961. }
  28962. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28963. };
  28964. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28965. if (!this._beingRegenerated) {
  28966. return;
  28967. }
  28968. _super.prototype.setVerticesData.call(this, kind, data, false);
  28969. };
  28970. // to override
  28971. // protected
  28972. _Primitive.prototype._regenerateVertexData = function () {
  28973. throw new Error("Abstract method");
  28974. };
  28975. _Primitive.prototype.copy = function (id) {
  28976. throw new Error("Must be overriden in sub-classes.");
  28977. };
  28978. return _Primitive;
  28979. })(Geometry);
  28980. Primitives._Primitive = _Primitive;
  28981. var Ribbon = (function (_super) {
  28982. __extends(Ribbon, _super);
  28983. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28984. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28985. this.pathArray = pathArray;
  28986. this.closeArray = closeArray;
  28987. this.closePath = closePath;
  28988. this.offset = offset;
  28989. this.side = side;
  28990. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28991. }
  28992. Ribbon.prototype._regenerateVertexData = function () {
  28993. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28994. };
  28995. Ribbon.prototype.copy = function (id) {
  28996. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28997. };
  28998. return Ribbon;
  28999. })(_Primitive);
  29000. Primitives.Ribbon = Ribbon;
  29001. var Box = (function (_super) {
  29002. __extends(Box, _super);
  29003. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29004. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29005. this.size = size;
  29006. this.side = side;
  29007. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29008. }
  29009. Box.prototype._regenerateVertexData = function () {
  29010. return BABYLON.VertexData.CreateBox(this.size, this.side);
  29011. };
  29012. Box.prototype.copy = function (id) {
  29013. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29014. };
  29015. return Box;
  29016. })(_Primitive);
  29017. Primitives.Box = Box;
  29018. var Sphere = (function (_super) {
  29019. __extends(Sphere, _super);
  29020. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29022. this.segments = segments;
  29023. this.diameter = diameter;
  29024. this.side = side;
  29025. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29026. }
  29027. Sphere.prototype._regenerateVertexData = function () {
  29028. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  29029. };
  29030. Sphere.prototype.copy = function (id) {
  29031. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29032. };
  29033. return Sphere;
  29034. })(_Primitive);
  29035. Primitives.Sphere = Sphere;
  29036. var Cylinder = (function (_super) {
  29037. __extends(Cylinder, _super);
  29038. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29039. if (subdivisions === void 0) { subdivisions = 1; }
  29040. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29041. this.height = height;
  29042. this.diameterTop = diameterTop;
  29043. this.diameterBottom = diameterBottom;
  29044. this.tessellation = tessellation;
  29045. this.subdivisions = subdivisions;
  29046. this.side = side;
  29047. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29048. }
  29049. Cylinder.prototype._regenerateVertexData = function () {
  29050. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  29051. };
  29052. Cylinder.prototype.copy = function (id) {
  29053. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29054. };
  29055. return Cylinder;
  29056. })(_Primitive);
  29057. Primitives.Cylinder = Cylinder;
  29058. var Torus = (function (_super) {
  29059. __extends(Torus, _super);
  29060. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29062. this.diameter = diameter;
  29063. this.thickness = thickness;
  29064. this.tessellation = tessellation;
  29065. this.side = side;
  29066. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29067. }
  29068. Torus.prototype._regenerateVertexData = function () {
  29069. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  29070. };
  29071. Torus.prototype.copy = function (id) {
  29072. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29073. };
  29074. return Torus;
  29075. })(_Primitive);
  29076. Primitives.Torus = Torus;
  29077. var Ground = (function (_super) {
  29078. __extends(Ground, _super);
  29079. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29080. this.width = width;
  29081. this.height = height;
  29082. this.subdivisions = subdivisions;
  29083. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29084. }
  29085. Ground.prototype._regenerateVertexData = function () {
  29086. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  29087. };
  29088. Ground.prototype.copy = function (id) {
  29089. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29090. };
  29091. return Ground;
  29092. })(_Primitive);
  29093. Primitives.Ground = Ground;
  29094. var TiledGround = (function (_super) {
  29095. __extends(TiledGround, _super);
  29096. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29097. this.xmin = xmin;
  29098. this.zmin = zmin;
  29099. this.xmax = xmax;
  29100. this.zmax = zmax;
  29101. this.subdivisions = subdivisions;
  29102. this.precision = precision;
  29103. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29104. }
  29105. TiledGround.prototype._regenerateVertexData = function () {
  29106. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  29107. };
  29108. TiledGround.prototype.copy = function (id) {
  29109. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29110. };
  29111. return TiledGround;
  29112. })(_Primitive);
  29113. Primitives.TiledGround = TiledGround;
  29114. var Plane = (function (_super) {
  29115. __extends(Plane, _super);
  29116. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29117. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29118. this.size = size;
  29119. this.side = side;
  29120. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29121. }
  29122. Plane.prototype._regenerateVertexData = function () {
  29123. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  29124. };
  29125. Plane.prototype.copy = function (id) {
  29126. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29127. };
  29128. return Plane;
  29129. })(_Primitive);
  29130. Primitives.Plane = Plane;
  29131. var TorusKnot = (function (_super) {
  29132. __extends(TorusKnot, _super);
  29133. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29134. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29135. this.radius = radius;
  29136. this.tube = tube;
  29137. this.radialSegments = radialSegments;
  29138. this.tubularSegments = tubularSegments;
  29139. this.p = p;
  29140. this.q = q;
  29141. this.side = side;
  29142. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29143. }
  29144. TorusKnot.prototype._regenerateVertexData = function () {
  29145. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  29146. };
  29147. TorusKnot.prototype.copy = function (id) {
  29148. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29149. };
  29150. return TorusKnot;
  29151. })(_Primitive);
  29152. Primitives.TorusKnot = TorusKnot;
  29153. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29154. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29155. })(BABYLON || (BABYLON = {}));
  29156. var BABYLON;
  29157. (function (BABYLON) {
  29158. var GroundMesh = (function (_super) {
  29159. __extends(GroundMesh, _super);
  29160. function GroundMesh(name, scene) {
  29161. _super.call(this, name, scene);
  29162. this.generateOctree = false;
  29163. this._worldInverse = new BABYLON.Matrix();
  29164. }
  29165. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29166. get: function () {
  29167. return this._subdivisions;
  29168. },
  29169. enumerable: true,
  29170. configurable: true
  29171. });
  29172. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29173. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29174. this._subdivisions = chunksCount;
  29175. this.subdivide(this._subdivisions);
  29176. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29177. };
  29178. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29179. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29180. this.getWorldMatrix().invertToRef(this._worldInverse);
  29181. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29182. var pickInfo = this.intersects(ray);
  29183. if (pickInfo.hit) {
  29184. return pickInfo.pickedPoint.y;
  29185. }
  29186. return 0;
  29187. };
  29188. return GroundMesh;
  29189. })(BABYLON.Mesh);
  29190. BABYLON.GroundMesh = GroundMesh;
  29191. })(BABYLON || (BABYLON = {}));
  29192. var BABYLON;
  29193. (function (BABYLON) {
  29194. var LinesMesh = (function (_super) {
  29195. __extends(LinesMesh, _super);
  29196. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29197. if (parent === void 0) { parent = null; }
  29198. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29199. this.color = new BABYLON.Color3(1, 1, 1);
  29200. this.alpha = 1;
  29201. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29202. attributes: ["position"],
  29203. uniforms: ["worldViewProjection", "color"],
  29204. needAlphaBlending: true
  29205. });
  29206. }
  29207. Object.defineProperty(LinesMesh.prototype, "material", {
  29208. get: function () {
  29209. return this._colorShader;
  29210. },
  29211. enumerable: true,
  29212. configurable: true
  29213. });
  29214. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29215. get: function () {
  29216. return false;
  29217. },
  29218. enumerable: true,
  29219. configurable: true
  29220. });
  29221. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29222. get: function () {
  29223. return false;
  29224. },
  29225. enumerable: true,
  29226. configurable: true
  29227. });
  29228. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29229. var engine = this.getScene().getEngine();
  29230. var indexToBind = this._geometry.getIndexBuffer();
  29231. // VBOs
  29232. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29233. // Color
  29234. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29235. };
  29236. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29237. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29238. return;
  29239. }
  29240. var engine = this.getScene().getEngine();
  29241. // Draw order
  29242. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29243. };
  29244. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29245. return null;
  29246. };
  29247. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29248. this._colorShader.dispose();
  29249. _super.prototype.dispose.call(this, doNotRecurse);
  29250. };
  29251. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29252. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29253. };
  29254. return LinesMesh;
  29255. })(BABYLON.Mesh);
  29256. BABYLON.LinesMesh = LinesMesh;
  29257. })(BABYLON || (BABYLON = {}));
  29258. var BABYLON;
  29259. (function (BABYLON) {
  29260. var OutlineRenderer = (function () {
  29261. function OutlineRenderer(scene) {
  29262. this._scene = scene;
  29263. }
  29264. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29265. var _this = this;
  29266. if (useOverlay === void 0) { useOverlay = false; }
  29267. var scene = this._scene;
  29268. var engine = this._scene.getEngine();
  29269. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29270. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29271. return;
  29272. }
  29273. var mesh = subMesh.getRenderingMesh();
  29274. var material = subMesh.getMaterial();
  29275. engine.enableEffect(this._effect);
  29276. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29277. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29278. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29279. // Bones
  29280. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29281. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29282. }
  29283. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29284. // Alpha test
  29285. if (material && material.needAlphaTesting()) {
  29286. var alphaTexture = material.getAlphaTestTexture();
  29287. this._effect.setTexture("diffuseSampler", alphaTexture);
  29288. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29289. }
  29290. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29291. };
  29292. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29293. var defines = [];
  29294. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29295. var mesh = subMesh.getMesh();
  29296. var material = subMesh.getMaterial();
  29297. // Alpha test
  29298. if (material && material.needAlphaTesting()) {
  29299. defines.push("#define ALPHATEST");
  29300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29301. attribs.push(BABYLON.VertexBuffer.UVKind);
  29302. defines.push("#define UV1");
  29303. }
  29304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29305. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29306. defines.push("#define UV2");
  29307. }
  29308. }
  29309. // Bones
  29310. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29313. defines.push("#define BONES");
  29314. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29315. }
  29316. // Instances
  29317. if (useInstances) {
  29318. defines.push("#define INSTANCES");
  29319. attribs.push("world0");
  29320. attribs.push("world1");
  29321. attribs.push("world2");
  29322. attribs.push("world3");
  29323. }
  29324. // Get correct effect
  29325. var join = defines.join("\n");
  29326. if (this._cachedDefines !== join) {
  29327. this._cachedDefines = join;
  29328. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29329. }
  29330. return this._effect.isReady();
  29331. };
  29332. return OutlineRenderer;
  29333. })();
  29334. BABYLON.OutlineRenderer = OutlineRenderer;
  29335. })(BABYLON || (BABYLON = {}));
  29336. var BABYLON;
  29337. (function (BABYLON) {
  29338. var MeshAssetTask = (function () {
  29339. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29340. this.name = name;
  29341. this.meshesNames = meshesNames;
  29342. this.rootUrl = rootUrl;
  29343. this.sceneFilename = sceneFilename;
  29344. this.isCompleted = false;
  29345. }
  29346. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29347. var _this = this;
  29348. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29349. _this.loadedMeshes = meshes;
  29350. _this.loadedParticleSystems = particleSystems;
  29351. _this.loadedSkeletons = skeletons;
  29352. _this.isCompleted = true;
  29353. if (_this.onSuccess) {
  29354. _this.onSuccess(_this);
  29355. }
  29356. onSuccess();
  29357. }, null, function () {
  29358. if (_this.onError) {
  29359. _this.onError(_this);
  29360. }
  29361. onError();
  29362. });
  29363. };
  29364. return MeshAssetTask;
  29365. })();
  29366. BABYLON.MeshAssetTask = MeshAssetTask;
  29367. var TextFileAssetTask = (function () {
  29368. function TextFileAssetTask(name, url) {
  29369. this.name = name;
  29370. this.url = url;
  29371. this.isCompleted = false;
  29372. }
  29373. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29374. var _this = this;
  29375. BABYLON.Tools.LoadFile(this.url, function (data) {
  29376. _this.text = data;
  29377. _this.isCompleted = true;
  29378. if (_this.onSuccess) {
  29379. _this.onSuccess(_this);
  29380. }
  29381. onSuccess();
  29382. }, null, scene.database, false, function () {
  29383. if (_this.onError) {
  29384. _this.onError(_this);
  29385. }
  29386. onError();
  29387. });
  29388. };
  29389. return TextFileAssetTask;
  29390. })();
  29391. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29392. var BinaryFileAssetTask = (function () {
  29393. function BinaryFileAssetTask(name, url) {
  29394. this.name = name;
  29395. this.url = url;
  29396. this.isCompleted = false;
  29397. }
  29398. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29399. var _this = this;
  29400. BABYLON.Tools.LoadFile(this.url, function (data) {
  29401. _this.data = data;
  29402. _this.isCompleted = true;
  29403. if (_this.onSuccess) {
  29404. _this.onSuccess(_this);
  29405. }
  29406. onSuccess();
  29407. }, null, scene.database, true, function () {
  29408. if (_this.onError) {
  29409. _this.onError(_this);
  29410. }
  29411. onError();
  29412. });
  29413. };
  29414. return BinaryFileAssetTask;
  29415. })();
  29416. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29417. var ImageAssetTask = (function () {
  29418. function ImageAssetTask(name, url) {
  29419. this.name = name;
  29420. this.url = url;
  29421. this.isCompleted = false;
  29422. }
  29423. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29424. var _this = this;
  29425. var img = new Image();
  29426. img.onload = function () {
  29427. _this.image = img;
  29428. _this.isCompleted = true;
  29429. if (_this.onSuccess) {
  29430. _this.onSuccess(_this);
  29431. }
  29432. onSuccess();
  29433. };
  29434. img.onerror = function () {
  29435. if (_this.onError) {
  29436. _this.onError(_this);
  29437. }
  29438. onError();
  29439. };
  29440. img.src = this.url;
  29441. };
  29442. return ImageAssetTask;
  29443. })();
  29444. BABYLON.ImageAssetTask = ImageAssetTask;
  29445. var TextureAssetTask = (function () {
  29446. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29448. this.name = name;
  29449. this.url = url;
  29450. this.noMipmap = noMipmap;
  29451. this.invertY = invertY;
  29452. this.samplingMode = samplingMode;
  29453. this.isCompleted = false;
  29454. }
  29455. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29456. var _this = this;
  29457. var onload = function () {
  29458. _this.isCompleted = true;
  29459. if (_this.onSuccess) {
  29460. _this.onSuccess(_this);
  29461. }
  29462. onSuccess();
  29463. };
  29464. var onerror = function () {
  29465. if (_this.onError) {
  29466. _this.onError(_this);
  29467. }
  29468. onError();
  29469. };
  29470. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29471. };
  29472. return TextureAssetTask;
  29473. })();
  29474. BABYLON.TextureAssetTask = TextureAssetTask;
  29475. var AssetsManager = (function () {
  29476. function AssetsManager(scene) {
  29477. this._tasks = new Array();
  29478. this._waitingTasksCount = 0;
  29479. this.useDefaultLoadingScreen = true;
  29480. this._scene = scene;
  29481. }
  29482. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29483. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29484. this._tasks.push(task);
  29485. return task;
  29486. };
  29487. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29488. var task = new TextFileAssetTask(taskName, url);
  29489. this._tasks.push(task);
  29490. return task;
  29491. };
  29492. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29493. var task = new BinaryFileAssetTask(taskName, url);
  29494. this._tasks.push(task);
  29495. return task;
  29496. };
  29497. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29498. var task = new ImageAssetTask(taskName, url);
  29499. this._tasks.push(task);
  29500. return task;
  29501. };
  29502. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29504. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29505. this._tasks.push(task);
  29506. return task;
  29507. };
  29508. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29509. this._waitingTasksCount--;
  29510. if (this._waitingTasksCount === 0) {
  29511. if (this.onFinish) {
  29512. this.onFinish(this._tasks);
  29513. }
  29514. this._scene.getEngine().hideLoadingUI();
  29515. }
  29516. };
  29517. AssetsManager.prototype._runTask = function (task) {
  29518. var _this = this;
  29519. task.run(this._scene, function () {
  29520. if (_this.onTaskSuccess) {
  29521. _this.onTaskSuccess(task);
  29522. }
  29523. _this._decreaseWaitingTasksCount();
  29524. }, function () {
  29525. if (_this.onTaskError) {
  29526. _this.onTaskError(task);
  29527. }
  29528. _this._decreaseWaitingTasksCount();
  29529. });
  29530. };
  29531. AssetsManager.prototype.reset = function () {
  29532. this._tasks = new Array();
  29533. return this;
  29534. };
  29535. AssetsManager.prototype.load = function () {
  29536. this._waitingTasksCount = this._tasks.length;
  29537. if (this._waitingTasksCount === 0) {
  29538. if (this.onFinish) {
  29539. this.onFinish(this._tasks);
  29540. }
  29541. return this;
  29542. }
  29543. if (this.useDefaultLoadingScreen) {
  29544. this._scene.getEngine().displayLoadingUI();
  29545. }
  29546. for (var index = 0; index < this._tasks.length; index++) {
  29547. var task = this._tasks[index];
  29548. this._runTask(task);
  29549. }
  29550. return this;
  29551. };
  29552. return AssetsManager;
  29553. })();
  29554. BABYLON.AssetsManager = AssetsManager;
  29555. })(BABYLON || (BABYLON = {}));
  29556. var BABYLON;
  29557. (function (BABYLON) {
  29558. var VRDeviceOrientationFreeCamera = (function (_super) {
  29559. __extends(VRDeviceOrientationFreeCamera, _super);
  29560. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29561. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29562. _super.call(this, name, position, scene);
  29563. this._alpha = 0;
  29564. this._beta = 0;
  29565. this._gamma = 0;
  29566. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29567. metrics.compensateDistorsion = compensateDistorsion;
  29568. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29569. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29570. }
  29571. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29572. this._alpha = +evt.alpha | 0;
  29573. this._beta = +evt.beta | 0;
  29574. this._gamma = +evt.gamma | 0;
  29575. if (this._gamma < 0) {
  29576. this._gamma = 90 + this._gamma;
  29577. }
  29578. else {
  29579. // Incline it in the correct angle.
  29580. this._gamma = 270 - this._gamma;
  29581. }
  29582. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29583. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29584. this.rotation.z = this._beta / 180.0 * Math.PI;
  29585. };
  29586. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29587. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29588. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29589. };
  29590. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29591. _super.prototype.detachControl.call(this, element);
  29592. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29593. };
  29594. return VRDeviceOrientationFreeCamera;
  29595. })(BABYLON.FreeCamera);
  29596. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29597. })(BABYLON || (BABYLON = {}));
  29598. var BABYLON;
  29599. (function (BABYLON) {
  29600. var WebVRFreeCamera = (function (_super) {
  29601. __extends(WebVRFreeCamera, _super);
  29602. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29603. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29604. _super.call(this, name, position, scene);
  29605. this._hmdDevice = null;
  29606. this._sensorDevice = null;
  29607. this._cacheState = null;
  29608. this._cacheQuaternion = new BABYLON.Quaternion();
  29609. this._cacheRotation = BABYLON.Vector3.Zero();
  29610. this._vrEnabled = false;
  29611. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29612. metrics.compensateDistorsion = compensateDistorsion;
  29613. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29614. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29615. }
  29616. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29617. var size = devices.length;
  29618. var i = 0;
  29619. // Reset devices.
  29620. this._sensorDevice = null;
  29621. this._hmdDevice = null;
  29622. // Search for a HmdDevice.
  29623. while (i < size && this._hmdDevice === null) {
  29624. if (devices[i] instanceof HMDVRDevice) {
  29625. this._hmdDevice = devices[i];
  29626. }
  29627. i++;
  29628. }
  29629. i = 0;
  29630. while (i < size && this._sensorDevice === null) {
  29631. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29632. this._sensorDevice = devices[i];
  29633. }
  29634. i++;
  29635. }
  29636. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29637. };
  29638. WebVRFreeCamera.prototype._checkInputs = function () {
  29639. if (this._vrEnabled) {
  29640. this._cacheState = this._sensorDevice.getState();
  29641. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29642. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29643. this.rotation.x = -this._cacheRotation.z;
  29644. this.rotation.y = -this._cacheRotation.y;
  29645. this.rotation.z = this._cacheRotation.x;
  29646. }
  29647. _super.prototype._checkInputs.call(this);
  29648. };
  29649. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29650. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29651. if (navigator.getVRDevices) {
  29652. navigator.getVRDevices().then(this._getWebVRDevices);
  29653. }
  29654. else if (navigator.mozGetVRDevices) {
  29655. navigator.mozGetVRDevices(this._getWebVRDevices);
  29656. }
  29657. };
  29658. WebVRFreeCamera.prototype.detachControl = function (element) {
  29659. _super.prototype.detachControl.call(this, element);
  29660. this._vrEnabled = false;
  29661. };
  29662. return WebVRFreeCamera;
  29663. })(BABYLON.FreeCamera);
  29664. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29665. })(BABYLON || (BABYLON = {}));
  29666. var BABYLON;
  29667. (function (BABYLON) {
  29668. // Standard optimizations
  29669. var SceneOptimization = (function () {
  29670. function SceneOptimization(priority) {
  29671. if (priority === void 0) { priority = 0; }
  29672. this.priority = priority;
  29673. this.apply = function (scene) {
  29674. return true; // Return true if everything that can be done was applied
  29675. };
  29676. }
  29677. return SceneOptimization;
  29678. })();
  29679. BABYLON.SceneOptimization = SceneOptimization;
  29680. var TextureOptimization = (function (_super) {
  29681. __extends(TextureOptimization, _super);
  29682. function TextureOptimization(priority, maximumSize) {
  29683. var _this = this;
  29684. if (priority === void 0) { priority = 0; }
  29685. if (maximumSize === void 0) { maximumSize = 1024; }
  29686. _super.call(this, priority);
  29687. this.priority = priority;
  29688. this.maximumSize = maximumSize;
  29689. this.apply = function (scene) {
  29690. var allDone = true;
  29691. for (var index = 0; index < scene.textures.length; index++) {
  29692. var texture = scene.textures[index];
  29693. if (!texture.canRescale) {
  29694. continue;
  29695. }
  29696. var currentSize = texture.getSize();
  29697. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29698. if (maxDimension > _this.maximumSize) {
  29699. texture.scale(0.5);
  29700. allDone = false;
  29701. }
  29702. }
  29703. return allDone;
  29704. };
  29705. }
  29706. return TextureOptimization;
  29707. })(SceneOptimization);
  29708. BABYLON.TextureOptimization = TextureOptimization;
  29709. var HardwareScalingOptimization = (function (_super) {
  29710. __extends(HardwareScalingOptimization, _super);
  29711. function HardwareScalingOptimization(priority, maximumScale) {
  29712. var _this = this;
  29713. if (priority === void 0) { priority = 0; }
  29714. if (maximumScale === void 0) { maximumScale = 2; }
  29715. _super.call(this, priority);
  29716. this.priority = priority;
  29717. this.maximumScale = maximumScale;
  29718. this._currentScale = 1;
  29719. this.apply = function (scene) {
  29720. _this._currentScale++;
  29721. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29722. return _this._currentScale >= _this.maximumScale;
  29723. };
  29724. }
  29725. return HardwareScalingOptimization;
  29726. })(SceneOptimization);
  29727. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29728. var ShadowsOptimization = (function (_super) {
  29729. __extends(ShadowsOptimization, _super);
  29730. function ShadowsOptimization() {
  29731. _super.apply(this, arguments);
  29732. this.apply = function (scene) {
  29733. scene.shadowsEnabled = false;
  29734. return true;
  29735. };
  29736. }
  29737. return ShadowsOptimization;
  29738. })(SceneOptimization);
  29739. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29740. var PostProcessesOptimization = (function (_super) {
  29741. __extends(PostProcessesOptimization, _super);
  29742. function PostProcessesOptimization() {
  29743. _super.apply(this, arguments);
  29744. this.apply = function (scene) {
  29745. scene.postProcessesEnabled = false;
  29746. return true;
  29747. };
  29748. }
  29749. return PostProcessesOptimization;
  29750. })(SceneOptimization);
  29751. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29752. var LensFlaresOptimization = (function (_super) {
  29753. __extends(LensFlaresOptimization, _super);
  29754. function LensFlaresOptimization() {
  29755. _super.apply(this, arguments);
  29756. this.apply = function (scene) {
  29757. scene.lensFlaresEnabled = false;
  29758. return true;
  29759. };
  29760. }
  29761. return LensFlaresOptimization;
  29762. })(SceneOptimization);
  29763. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29764. var ParticlesOptimization = (function (_super) {
  29765. __extends(ParticlesOptimization, _super);
  29766. function ParticlesOptimization() {
  29767. _super.apply(this, arguments);
  29768. this.apply = function (scene) {
  29769. scene.particlesEnabled = false;
  29770. return true;
  29771. };
  29772. }
  29773. return ParticlesOptimization;
  29774. })(SceneOptimization);
  29775. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29776. var RenderTargetsOptimization = (function (_super) {
  29777. __extends(RenderTargetsOptimization, _super);
  29778. function RenderTargetsOptimization() {
  29779. _super.apply(this, arguments);
  29780. this.apply = function (scene) {
  29781. scene.renderTargetsEnabled = false;
  29782. return true;
  29783. };
  29784. }
  29785. return RenderTargetsOptimization;
  29786. })(SceneOptimization);
  29787. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29788. var MergeMeshesOptimization = (function (_super) {
  29789. __extends(MergeMeshesOptimization, _super);
  29790. function MergeMeshesOptimization() {
  29791. var _this = this;
  29792. _super.apply(this, arguments);
  29793. this._canBeMerged = function (abstractMesh) {
  29794. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29795. return false;
  29796. }
  29797. var mesh = abstractMesh;
  29798. if (!mesh.isVisible || !mesh.isEnabled()) {
  29799. return false;
  29800. }
  29801. if (mesh.instances.length > 0) {
  29802. return false;
  29803. }
  29804. if (mesh.skeleton || mesh.hasLODLevels) {
  29805. return false;
  29806. }
  29807. return true;
  29808. };
  29809. this.apply = function (scene, updateSelectionTree) {
  29810. var globalPool = scene.meshes.slice(0);
  29811. var globalLength = globalPool.length;
  29812. for (var index = 0; index < globalLength; index++) {
  29813. var currentPool = new Array();
  29814. var current = globalPool[index];
  29815. // Checks
  29816. if (!_this._canBeMerged(current)) {
  29817. continue;
  29818. }
  29819. currentPool.push(current);
  29820. // Find compatible meshes
  29821. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29822. var otherMesh = globalPool[subIndex];
  29823. if (!_this._canBeMerged(otherMesh)) {
  29824. continue;
  29825. }
  29826. if (otherMesh.material !== current.material) {
  29827. continue;
  29828. }
  29829. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29830. continue;
  29831. }
  29832. currentPool.push(otherMesh);
  29833. globalLength--;
  29834. globalPool.splice(subIndex, 1);
  29835. subIndex--;
  29836. }
  29837. if (currentPool.length < 2) {
  29838. continue;
  29839. }
  29840. // Merge meshes
  29841. BABYLON.Mesh.MergeMeshes(currentPool);
  29842. }
  29843. if (updateSelectionTree != undefined) {
  29844. if (updateSelectionTree) {
  29845. scene.createOrUpdateSelectionOctree();
  29846. }
  29847. }
  29848. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29849. scene.createOrUpdateSelectionOctree();
  29850. }
  29851. return true;
  29852. };
  29853. }
  29854. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29855. get: function () {
  29856. return MergeMeshesOptimization._UpdateSelectionTree;
  29857. },
  29858. set: function (value) {
  29859. MergeMeshesOptimization._UpdateSelectionTree = value;
  29860. },
  29861. enumerable: true,
  29862. configurable: true
  29863. });
  29864. MergeMeshesOptimization._UpdateSelectionTree = false;
  29865. return MergeMeshesOptimization;
  29866. })(SceneOptimization);
  29867. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29868. // Options
  29869. var SceneOptimizerOptions = (function () {
  29870. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29871. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29872. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29873. this.targetFrameRate = targetFrameRate;
  29874. this.trackerDuration = trackerDuration;
  29875. this.optimizations = new Array();
  29876. }
  29877. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29878. var result = new SceneOptimizerOptions(targetFrameRate);
  29879. var priority = 0;
  29880. result.optimizations.push(new MergeMeshesOptimization(priority));
  29881. result.optimizations.push(new ShadowsOptimization(priority));
  29882. result.optimizations.push(new LensFlaresOptimization(priority));
  29883. // Next priority
  29884. priority++;
  29885. result.optimizations.push(new PostProcessesOptimization(priority));
  29886. result.optimizations.push(new ParticlesOptimization(priority));
  29887. // Next priority
  29888. priority++;
  29889. result.optimizations.push(new TextureOptimization(priority, 1024));
  29890. return result;
  29891. };
  29892. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29893. var result = new SceneOptimizerOptions(targetFrameRate);
  29894. var priority = 0;
  29895. result.optimizations.push(new MergeMeshesOptimization(priority));
  29896. result.optimizations.push(new ShadowsOptimization(priority));
  29897. result.optimizations.push(new LensFlaresOptimization(priority));
  29898. // Next priority
  29899. priority++;
  29900. result.optimizations.push(new PostProcessesOptimization(priority));
  29901. result.optimizations.push(new ParticlesOptimization(priority));
  29902. // Next priority
  29903. priority++;
  29904. result.optimizations.push(new TextureOptimization(priority, 512));
  29905. // Next priority
  29906. priority++;
  29907. result.optimizations.push(new RenderTargetsOptimization(priority));
  29908. // Next priority
  29909. priority++;
  29910. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29911. return result;
  29912. };
  29913. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29914. var result = new SceneOptimizerOptions(targetFrameRate);
  29915. var priority = 0;
  29916. result.optimizations.push(new MergeMeshesOptimization(priority));
  29917. result.optimizations.push(new ShadowsOptimization(priority));
  29918. result.optimizations.push(new LensFlaresOptimization(priority));
  29919. // Next priority
  29920. priority++;
  29921. result.optimizations.push(new PostProcessesOptimization(priority));
  29922. result.optimizations.push(new ParticlesOptimization(priority));
  29923. // Next priority
  29924. priority++;
  29925. result.optimizations.push(new TextureOptimization(priority, 256));
  29926. // Next priority
  29927. priority++;
  29928. result.optimizations.push(new RenderTargetsOptimization(priority));
  29929. // Next priority
  29930. priority++;
  29931. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29932. return result;
  29933. };
  29934. return SceneOptimizerOptions;
  29935. })();
  29936. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29937. // Scene optimizer tool
  29938. var SceneOptimizer = (function () {
  29939. function SceneOptimizer() {
  29940. }
  29941. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29942. // TODO: add an epsilon
  29943. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29944. if (onSuccess) {
  29945. onSuccess();
  29946. }
  29947. return;
  29948. }
  29949. // Apply current level of optimizations
  29950. var allDone = true;
  29951. var noOptimizationApplied = true;
  29952. for (var index = 0; index < options.optimizations.length; index++) {
  29953. var optimization = options.optimizations[index];
  29954. if (optimization.priority === currentPriorityLevel) {
  29955. noOptimizationApplied = false;
  29956. allDone = allDone && optimization.apply(scene);
  29957. }
  29958. }
  29959. // If no optimization was applied, this is a failure :(
  29960. if (noOptimizationApplied) {
  29961. if (onFailure) {
  29962. onFailure();
  29963. }
  29964. return;
  29965. }
  29966. // If all optimizations were done, move to next level
  29967. if (allDone) {
  29968. currentPriorityLevel++;
  29969. }
  29970. // Let's the system running for a specific amount of time before checking FPS
  29971. scene.executeWhenReady(function () {
  29972. setTimeout(function () {
  29973. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29974. }, options.trackerDuration);
  29975. });
  29976. };
  29977. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29978. if (!options) {
  29979. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29980. }
  29981. // Let's the system running for a specific amount of time before checking FPS
  29982. scene.executeWhenReady(function () {
  29983. setTimeout(function () {
  29984. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29985. }, options.trackerDuration);
  29986. });
  29987. };
  29988. return SceneOptimizer;
  29989. })();
  29990. BABYLON.SceneOptimizer = SceneOptimizer;
  29991. })(BABYLON || (BABYLON = {}));
  29992. var BABYLON;
  29993. (function (BABYLON) {
  29994. var Internals;
  29995. (function (Internals) {
  29996. var MeshLODLevel = (function () {
  29997. function MeshLODLevel(distance, mesh) {
  29998. this.distance = distance;
  29999. this.mesh = mesh;
  30000. }
  30001. return MeshLODLevel;
  30002. })();
  30003. Internals.MeshLODLevel = MeshLODLevel;
  30004. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30005. })(BABYLON || (BABYLON = {}));
  30006. var BABYLON;
  30007. (function (BABYLON) {
  30008. var AudioEngine = (function () {
  30009. function AudioEngine() {
  30010. this._audioContext = null;
  30011. this._audioContextInitialized = false;
  30012. this.canUseWebAudio = false;
  30013. this.WarnedWebAudioUnsupported = false;
  30014. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  30015. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  30016. this.canUseWebAudio = true;
  30017. }
  30018. }
  30019. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30020. get: function () {
  30021. if (!this._audioContextInitialized) {
  30022. this._initializeAudioContext();
  30023. }
  30024. return this._audioContext;
  30025. },
  30026. enumerable: true,
  30027. configurable: true
  30028. });
  30029. AudioEngine.prototype._initializeAudioContext = function () {
  30030. try {
  30031. if (this.canUseWebAudio) {
  30032. this._audioContext = new AudioContext();
  30033. // create a global volume gain node
  30034. this.masterGain = this._audioContext.createGain();
  30035. this.masterGain.gain.value = 1;
  30036. this.masterGain.connect(this._audioContext.destination);
  30037. this._audioContextInitialized = true;
  30038. }
  30039. }
  30040. catch (e) {
  30041. this.canUseWebAudio = false;
  30042. BABYLON.Tools.Error("Web Audio: " + e.message);
  30043. }
  30044. };
  30045. AudioEngine.prototype.dispose = function () {
  30046. if (this.canUseWebAudio && this._audioContextInitialized) {
  30047. if (this._connectedAnalyser) {
  30048. this._connectedAnalyser.stopDebugCanvas();
  30049. this._connectedAnalyser.dispose();
  30050. this.masterGain.disconnect();
  30051. this.masterGain.connect(this._audioContext.destination);
  30052. this._connectedAnalyser = null;
  30053. }
  30054. this.masterGain.gain.value = 1;
  30055. }
  30056. this.WarnedWebAudioUnsupported = false;
  30057. };
  30058. AudioEngine.prototype.getGlobalVolume = function () {
  30059. if (this.canUseWebAudio && this._audioContextInitialized) {
  30060. return this.masterGain.gain.value;
  30061. }
  30062. else {
  30063. return -1;
  30064. }
  30065. };
  30066. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30067. if (this.canUseWebAudio && this._audioContextInitialized) {
  30068. this.masterGain.gain.value = newVolume;
  30069. }
  30070. };
  30071. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30072. if (this._connectedAnalyser) {
  30073. this._connectedAnalyser.stopDebugCanvas();
  30074. }
  30075. if (this.canUseWebAudio && this._audioContextInitialized) {
  30076. this._connectedAnalyser = analyser;
  30077. this.masterGain.disconnect();
  30078. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30079. }
  30080. };
  30081. return AudioEngine;
  30082. })();
  30083. BABYLON.AudioEngine = AudioEngine;
  30084. })(BABYLON || (BABYLON = {}));
  30085. var BABYLON;
  30086. (function (BABYLON) {
  30087. var Sound = (function () {
  30088. /**
  30089. * Create a sound and attach it to a scene
  30090. * @param name Name of your sound
  30091. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30092. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30093. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30094. */
  30095. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30096. var _this = this;
  30097. this.autoplay = false;
  30098. this.loop = false;
  30099. this.useCustomAttenuation = false;
  30100. this.spatialSound = false;
  30101. this.refDistance = 1;
  30102. this.rolloffFactor = 1;
  30103. this.maxDistance = 100;
  30104. this.distanceModel = "linear";
  30105. this._panningModel = "equalpower";
  30106. this._playbackRate = 1;
  30107. this._startTime = 0;
  30108. this._startOffset = 0;
  30109. this._position = BABYLON.Vector3.Zero();
  30110. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30111. this._volume = 1;
  30112. this._isLoaded = false;
  30113. this._isReadyToPlay = false;
  30114. this.isPlaying = false;
  30115. this.isPaused = false;
  30116. this._isDirectional = false;
  30117. // Used if you'd like to create a directional sound.
  30118. // If not set, the sound will be omnidirectional
  30119. this._coneInnerAngle = 360;
  30120. this._coneOuterAngle = 360;
  30121. this._coneOuterGain = 0;
  30122. this._isOutputConnected = false;
  30123. this.name = name;
  30124. this._scene = scene;
  30125. this._readyToPlayCallback = readyToPlayCallback;
  30126. // Default custom attenuation function is a linear attenuation
  30127. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30128. if (currentDistance < maxDistance) {
  30129. return currentVolume * (1 - currentDistance / maxDistance);
  30130. }
  30131. else {
  30132. return 0;
  30133. }
  30134. };
  30135. if (options) {
  30136. this.autoplay = options.autoplay || false;
  30137. this.loop = options.loop || false;
  30138. // if volume === 0, we need another way to check this option
  30139. if (options.volume !== undefined) {
  30140. this._volume = options.volume;
  30141. }
  30142. this.spatialSound = options.spatialSound || false;
  30143. this.maxDistance = options.maxDistance || 100;
  30144. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30145. this.rolloffFactor = options.rolloffFactor || 1;
  30146. this.refDistance = options.refDistance || 1;
  30147. this.distanceModel = options.distanceModel || "linear";
  30148. this._playbackRate = options.playbackRate || 1;
  30149. }
  30150. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30151. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30152. this._soundGain.gain.value = this._volume;
  30153. this._inputAudioNode = this._soundGain;
  30154. this._ouputAudioNode = this._soundGain;
  30155. if (this.spatialSound) {
  30156. this._createSpatialParameters();
  30157. }
  30158. this._scene.mainSoundTrack.AddSound(this);
  30159. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30160. if (urlOrArrayBuffer) {
  30161. // If it's an URL
  30162. if (typeof (urlOrArrayBuffer) === "string") {
  30163. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30164. }
  30165. else {
  30166. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30167. this._soundLoaded(urlOrArrayBuffer);
  30168. }
  30169. else {
  30170. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30171. }
  30172. }
  30173. }
  30174. }
  30175. else {
  30176. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30177. this._scene.mainSoundTrack.AddSound(this);
  30178. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30179. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30180. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30181. }
  30182. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30183. if (this._readyToPlayCallback) {
  30184. window.setTimeout(function () {
  30185. _this._readyToPlayCallback();
  30186. }, 1000);
  30187. }
  30188. }
  30189. }
  30190. Sound.prototype.dispose = function () {
  30191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30192. if (this.isPlaying) {
  30193. this.stop();
  30194. }
  30195. this._isReadyToPlay = false;
  30196. if (this.soundTrackId === -1) {
  30197. this._scene.mainSoundTrack.RemoveSound(this);
  30198. }
  30199. else {
  30200. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30201. }
  30202. if (this._soundGain) {
  30203. this._soundGain.disconnect();
  30204. this._soundGain = null;
  30205. }
  30206. if (this._soundPanner) {
  30207. this._soundPanner.disconnect();
  30208. this._soundPanner = null;
  30209. }
  30210. if (this._soundSource) {
  30211. this._soundSource.disconnect();
  30212. this._soundSource = null;
  30213. }
  30214. this._audioBuffer = null;
  30215. if (this._connectedMesh) {
  30216. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30217. this._connectedMesh = null;
  30218. }
  30219. }
  30220. };
  30221. Sound.prototype._soundLoaded = function (audioData) {
  30222. var _this = this;
  30223. this._isLoaded = true;
  30224. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30225. _this._audioBuffer = buffer;
  30226. _this._isReadyToPlay = true;
  30227. if (_this.autoplay) {
  30228. _this.play();
  30229. }
  30230. if (_this._readyToPlayCallback) {
  30231. _this._readyToPlayCallback();
  30232. }
  30233. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30234. };
  30235. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30236. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30237. this._audioBuffer = audioBuffer;
  30238. this._isReadyToPlay = true;
  30239. }
  30240. };
  30241. Sound.prototype.updateOptions = function (options) {
  30242. if (options) {
  30243. this.loop = options.loop || this.loop;
  30244. this.maxDistance = options.maxDistance || this.maxDistance;
  30245. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30246. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30247. this.refDistance = options.refDistance || this.refDistance;
  30248. this.distanceModel = options.distanceModel || this.distanceModel;
  30249. this._playbackRate = options.playbackRate || this._playbackRate;
  30250. this._updateSpatialParameters();
  30251. if (this.isPlaying) {
  30252. this._soundSource.playbackRate.value = this._playbackRate;
  30253. }
  30254. }
  30255. };
  30256. Sound.prototype._createSpatialParameters = function () {
  30257. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30258. if (this._scene.headphone) {
  30259. this._panningModel = "HRTF";
  30260. }
  30261. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30262. this._updateSpatialParameters();
  30263. this._soundPanner.connect(this._ouputAudioNode);
  30264. this._inputAudioNode = this._soundPanner;
  30265. }
  30266. };
  30267. Sound.prototype._updateSpatialParameters = function () {
  30268. if (this.spatialSound) {
  30269. if (this.useCustomAttenuation) {
  30270. // Tricks to disable in a way embedded Web Audio attenuation
  30271. this._soundPanner.distanceModel = "linear";
  30272. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30273. this._soundPanner.refDistance = 1;
  30274. this._soundPanner.rolloffFactor = 1;
  30275. this._soundPanner.panningModel = this._panningModel;
  30276. }
  30277. else {
  30278. this._soundPanner.distanceModel = this.distanceModel;
  30279. this._soundPanner.maxDistance = this.maxDistance;
  30280. this._soundPanner.refDistance = this.refDistance;
  30281. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30282. this._soundPanner.panningModel = this._panningModel;
  30283. }
  30284. }
  30285. };
  30286. Sound.prototype.switchPanningModelToHRTF = function () {
  30287. this._panningModel = "HRTF";
  30288. this._switchPanningModel();
  30289. };
  30290. Sound.prototype.switchPanningModelToEqualPower = function () {
  30291. this._panningModel = "equalpower";
  30292. this._switchPanningModel();
  30293. };
  30294. Sound.prototype._switchPanningModel = function () {
  30295. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30296. this._soundPanner.panningModel = this._panningModel;
  30297. }
  30298. };
  30299. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30300. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30301. if (this._isOutputConnected) {
  30302. this._ouputAudioNode.disconnect();
  30303. }
  30304. this._ouputAudioNode.connect(soundTrackAudioNode);
  30305. this._isOutputConnected = true;
  30306. }
  30307. };
  30308. /**
  30309. * Transform this sound into a directional source
  30310. * @param coneInnerAngle Size of the inner cone in degree
  30311. * @param coneOuterAngle Size of the outer cone in degree
  30312. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30313. */
  30314. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30315. if (coneOuterAngle < coneInnerAngle) {
  30316. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30317. return;
  30318. }
  30319. this._coneInnerAngle = coneInnerAngle;
  30320. this._coneOuterAngle = coneOuterAngle;
  30321. this._coneOuterGain = coneOuterGain;
  30322. this._isDirectional = true;
  30323. if (this.isPlaying && this.loop) {
  30324. this.stop();
  30325. this.play();
  30326. }
  30327. };
  30328. Sound.prototype.setPosition = function (newPosition) {
  30329. this._position = newPosition;
  30330. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30331. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30332. }
  30333. };
  30334. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30335. this._localDirection = newLocalDirection;
  30336. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30337. this._updateDirection();
  30338. }
  30339. };
  30340. Sound.prototype._updateDirection = function () {
  30341. var mat = this._connectedMesh.getWorldMatrix();
  30342. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30343. direction.normalize();
  30344. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30345. };
  30346. Sound.prototype.updateDistanceFromListener = function () {
  30347. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30348. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30349. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30350. }
  30351. };
  30352. Sound.prototype.setAttenuationFunction = function (callback) {
  30353. this._customAttenuationFunction = callback;
  30354. };
  30355. /**
  30356. * Play the sound
  30357. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30358. */
  30359. Sound.prototype.play = function (time) {
  30360. var _this = this;
  30361. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30362. try {
  30363. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30364. if (!this._soundSource) {
  30365. if (this.spatialSound) {
  30366. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30367. if (this._isDirectional) {
  30368. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30369. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30370. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30371. if (this._connectedMesh) {
  30372. this._updateDirection();
  30373. }
  30374. else {
  30375. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30376. }
  30377. }
  30378. }
  30379. }
  30380. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30381. this._soundSource.buffer = this._audioBuffer;
  30382. this._soundSource.connect(this._inputAudioNode);
  30383. this._soundSource.loop = this.loop;
  30384. this._soundSource.playbackRate.value = this._playbackRate;
  30385. this._startTime = startTime;
  30386. this._soundSource.onended = function () { _this._onended(); };
  30387. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30388. this.isPlaying = true;
  30389. this.isPaused = false;
  30390. }
  30391. catch (ex) {
  30392. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30393. }
  30394. }
  30395. };
  30396. Sound.prototype._onended = function () {
  30397. this.isPlaying = false;
  30398. if (this.onended) {
  30399. this.onended();
  30400. }
  30401. };
  30402. /**
  30403. * Stop the sound
  30404. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30405. */
  30406. Sound.prototype.stop = function (time) {
  30407. if (this.isPlaying) {
  30408. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30409. this._soundSource.stop(stopTime);
  30410. this.isPlaying = false;
  30411. }
  30412. };
  30413. Sound.prototype.pause = function () {
  30414. if (this.isPlaying) {
  30415. this.stop(0);
  30416. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30417. this.isPaused = true;
  30418. }
  30419. };
  30420. Sound.prototype.setVolume = function (newVolume, time) {
  30421. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30422. if (time) {
  30423. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30424. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30425. }
  30426. else {
  30427. this._soundGain.gain.value = newVolume;
  30428. }
  30429. }
  30430. this._volume = newVolume;
  30431. };
  30432. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30433. this._playbackRate = newPlaybackRate;
  30434. if (this.isPlaying) {
  30435. this._soundSource.playbackRate.value = this._playbackRate;
  30436. }
  30437. };
  30438. Sound.prototype.getVolume = function () {
  30439. return this._volume;
  30440. };
  30441. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30442. var _this = this;
  30443. this._connectedMesh = meshToConnectTo;
  30444. if (!this.spatialSound) {
  30445. this.spatialSound = true;
  30446. this._createSpatialParameters();
  30447. if (this.isPlaying && this.loop) {
  30448. this.stop();
  30449. this.play();
  30450. }
  30451. }
  30452. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30453. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30454. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30455. };
  30456. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30457. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30458. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30459. this._updateDirection();
  30460. }
  30461. };
  30462. return Sound;
  30463. })();
  30464. BABYLON.Sound = Sound;
  30465. })(BABYLON || (BABYLON = {}));
  30466. var BABYLON;
  30467. (function (BABYLON) {
  30468. var SoundTrack = (function () {
  30469. function SoundTrack(scene, options) {
  30470. this.id = -1;
  30471. this._isMainTrack = false;
  30472. this._scene = scene;
  30473. this._audioEngine = BABYLON.Engine.audioEngine;
  30474. this.soundCollection = new Array();
  30475. if (this._audioEngine.canUseWebAudio) {
  30476. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30477. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30478. if (options) {
  30479. if (options.volume) {
  30480. this._outputAudioNode.gain.value = options.volume;
  30481. }
  30482. if (options.mainTrack) {
  30483. this._isMainTrack = options.mainTrack;
  30484. }
  30485. }
  30486. }
  30487. if (!this._isMainTrack) {
  30488. this._scene.soundTracks.push(this);
  30489. this.id = this._scene.soundTracks.length - 1;
  30490. }
  30491. }
  30492. SoundTrack.prototype.dispose = function () {
  30493. if (this._audioEngine.canUseWebAudio) {
  30494. if (this._connectedAnalyser) {
  30495. this._connectedAnalyser.stopDebugCanvas();
  30496. }
  30497. while (this.soundCollection.length) {
  30498. this.soundCollection[0].dispose();
  30499. }
  30500. if (this._outputAudioNode) {
  30501. this._outputAudioNode.disconnect();
  30502. }
  30503. this._outputAudioNode = null;
  30504. }
  30505. };
  30506. SoundTrack.prototype.AddSound = function (sound) {
  30507. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30508. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30509. }
  30510. if (sound.soundTrackId) {
  30511. if (sound.soundTrackId === -1) {
  30512. this._scene.mainSoundTrack.RemoveSound(sound);
  30513. }
  30514. else {
  30515. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30516. }
  30517. }
  30518. this.soundCollection.push(sound);
  30519. sound.soundTrackId = this.id;
  30520. };
  30521. SoundTrack.prototype.RemoveSound = function (sound) {
  30522. var index = this.soundCollection.indexOf(sound);
  30523. if (index !== -1) {
  30524. this.soundCollection.splice(index, 1);
  30525. }
  30526. };
  30527. SoundTrack.prototype.setVolume = function (newVolume) {
  30528. if (this._audioEngine.canUseWebAudio) {
  30529. this._outputAudioNode.gain.value = newVolume;
  30530. }
  30531. };
  30532. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30533. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30534. for (var i = 0; i < this.soundCollection.length; i++) {
  30535. this.soundCollection[i].switchPanningModelToHRTF();
  30536. }
  30537. }
  30538. };
  30539. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30540. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30541. for (var i = 0; i < this.soundCollection.length; i++) {
  30542. this.soundCollection[i].switchPanningModelToEqualPower();
  30543. }
  30544. }
  30545. };
  30546. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30547. if (this._connectedAnalyser) {
  30548. this._connectedAnalyser.stopDebugCanvas();
  30549. }
  30550. this._connectedAnalyser = analyser;
  30551. if (this._audioEngine.canUseWebAudio) {
  30552. this._outputAudioNode.disconnect();
  30553. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30554. }
  30555. };
  30556. return SoundTrack;
  30557. })();
  30558. BABYLON.SoundTrack = SoundTrack;
  30559. })(BABYLON || (BABYLON = {}));
  30560. var BABYLON;
  30561. (function (BABYLON) {
  30562. var DebugLayer = (function () {
  30563. function DebugLayer(scene) {
  30564. var _this = this;
  30565. this._transformationMatrix = BABYLON.Matrix.Identity();
  30566. this._enabled = false;
  30567. this._labelsEnabled = false;
  30568. this._displayStatistics = true;
  30569. this._displayTree = false;
  30570. this._displayLogs = false;
  30571. this._identityMatrix = BABYLON.Matrix.Identity();
  30572. this.axisRatio = 0.02;
  30573. this.accentColor = "orange";
  30574. this._scene = scene;
  30575. this._syncPositions = function () {
  30576. var engine = _this._scene.getEngine();
  30577. var canvasRect = engine.getRenderingCanvasClientRect();
  30578. if (_this._showUI) {
  30579. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30580. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30581. _this._statsDiv.style.width = "400px";
  30582. _this._statsDiv.style.height = "auto";
  30583. _this._statsSubsetDiv.style.maxHeight = "240px";
  30584. _this._optionsDiv.style.left = "0px";
  30585. _this._optionsDiv.style.top = "10px";
  30586. _this._optionsDiv.style.width = "200px";
  30587. _this._optionsDiv.style.height = "auto";
  30588. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30589. _this._logDiv.style.left = "0px";
  30590. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30591. _this._logDiv.style.width = "600px";
  30592. _this._logDiv.style.height = "160px";
  30593. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30594. _this._treeDiv.style.top = "10px";
  30595. _this._treeDiv.style.width = "300px";
  30596. _this._treeDiv.style.height = "auto";
  30597. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30598. }
  30599. _this._globalDiv.style.left = canvasRect.left + "px";
  30600. _this._globalDiv.style.top = canvasRect.top + "px";
  30601. _this._drawingCanvas.style.left = "0px";
  30602. _this._drawingCanvas.style.top = "0px";
  30603. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30604. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30605. var devicePixelRatio = window.devicePixelRatio || 1;
  30606. var context = _this._drawingContext;
  30607. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30608. context.mozBackingStorePixelRatio ||
  30609. context.msBackingStorePixelRatio ||
  30610. context.oBackingStorePixelRatio ||
  30611. context.backingStorePixelRatio || 1;
  30612. _this._ratio = devicePixelRatio / backingStoreRatio;
  30613. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30614. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30615. };
  30616. this._onCanvasClick = function (evt) {
  30617. _this._clickPosition = {
  30618. x: evt.clientX * _this._ratio,
  30619. y: evt.clientY * _this._ratio
  30620. };
  30621. };
  30622. this._syncUI = function () {
  30623. if (_this._showUI) {
  30624. if (_this._displayStatistics) {
  30625. _this._displayStats();
  30626. _this._statsDiv.style.display = "";
  30627. }
  30628. else {
  30629. _this._statsDiv.style.display = "none";
  30630. }
  30631. if (_this._displayLogs) {
  30632. _this._logDiv.style.display = "";
  30633. }
  30634. else {
  30635. _this._logDiv.style.display = "none";
  30636. }
  30637. if (_this._displayTree) {
  30638. _this._treeDiv.style.display = "";
  30639. if (_this._needToRefreshMeshesTree) {
  30640. _this._needToRefreshMeshesTree = false;
  30641. _this._refreshMeshesTreeContent();
  30642. }
  30643. }
  30644. else {
  30645. _this._treeDiv.style.display = "none";
  30646. }
  30647. }
  30648. };
  30649. this._syncData = function () {
  30650. if (_this._labelsEnabled || !_this._showUI) {
  30651. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30652. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30653. var engine = _this._scene.getEngine();
  30654. var viewport = _this._camera.viewport;
  30655. var globalViewport = viewport.toGlobal(engine);
  30656. // Meshes
  30657. var meshes = _this._camera.getActiveMeshes();
  30658. for (var index = 0; index < meshes.length; index++) {
  30659. var mesh = meshes.data[index];
  30660. var position = mesh.getBoundingInfo().boundingSphere.center;
  30661. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30662. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30663. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30664. }
  30665. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30666. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30667. }
  30668. }
  30669. // Cameras
  30670. var cameras = _this._scene.cameras;
  30671. for (index = 0; index < cameras.length; index++) {
  30672. var camera = cameras[index];
  30673. if (camera === _this._camera) {
  30674. continue;
  30675. }
  30676. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30677. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30678. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30679. _this._camera.detachControl(engine.getRenderingCanvas());
  30680. _this._camera = camera;
  30681. _this._camera.attachControl(engine.getRenderingCanvas());
  30682. }, function () { return "purple"; });
  30683. }
  30684. }
  30685. // Lights
  30686. var lights = _this._scene.lights;
  30687. for (index = 0; index < lights.length; index++) {
  30688. var light = lights[index];
  30689. if (light.position) {
  30690. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30691. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30692. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30693. light.setEnabled(!light.isEnabled());
  30694. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30695. }
  30696. }
  30697. }
  30698. }
  30699. _this._clickPosition = undefined;
  30700. };
  30701. }
  30702. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30703. while (this._treeSubsetDiv.hasChildNodes()) {
  30704. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30705. }
  30706. // Add meshes
  30707. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30708. sortedArray.sort(function (a, b) {
  30709. if (a.name === b.name) {
  30710. return 0;
  30711. }
  30712. return (a.name > b.name) ? 1 : -1;
  30713. });
  30714. for (var index = 0; index < sortedArray.length; index++) {
  30715. var mesh = sortedArray[index];
  30716. if (!mesh.isEnabled()) {
  30717. continue;
  30718. }
  30719. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30720. m.isVisible = element.checked;
  30721. }, mesh);
  30722. }
  30723. };
  30724. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30725. this._drawingContext.beginPath();
  30726. this._drawingContext.moveTo(zero.x, zero.y);
  30727. this._drawingContext.lineTo(unit.x, unit.y);
  30728. this._drawingContext.strokeStyle = color;
  30729. this._drawingContext.lineWidth = 4;
  30730. this._drawingContext.stroke();
  30731. this._drawingContext.font = "normal 14px Segoe UI";
  30732. this._drawingContext.fillStyle = color;
  30733. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30734. };
  30735. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30736. var position = mesh.getBoundingInfo().boundingSphere.center;
  30737. var worldMatrix = mesh.getWorldMatrix();
  30738. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30739. var unit = (unprojectedVector.subtract(position)).length();
  30740. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30741. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30742. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30743. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30744. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30745. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30746. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30747. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30748. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30749. };
  30750. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30751. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30752. this._drawingContext.font = "normal 12px Segoe UI";
  30753. var textMetrics = this._drawingContext.measureText(text);
  30754. var centerX = projectedPosition.x - textMetrics.width / 2;
  30755. var centerY = projectedPosition.y;
  30756. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30757. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30758. onClick();
  30759. }
  30760. this._drawingContext.beginPath();
  30761. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30762. this._drawingContext.fillStyle = getFillStyle();
  30763. this._drawingContext.globalAlpha = 0.5;
  30764. this._drawingContext.fill();
  30765. this._drawingContext.globalAlpha = 1.0;
  30766. this._drawingContext.strokeStyle = '#FFFFFF';
  30767. this._drawingContext.lineWidth = 1;
  30768. this._drawingContext.stroke();
  30769. this._drawingContext.fillStyle = "#FFFFFF";
  30770. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30771. this._drawingContext.beginPath();
  30772. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30773. this._drawingContext.fill();
  30774. }
  30775. };
  30776. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30777. if (!this._clickPosition) {
  30778. return false;
  30779. }
  30780. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30781. return false;
  30782. }
  30783. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30784. return false;
  30785. }
  30786. return true;
  30787. };
  30788. DebugLayer.prototype.isVisible = function () {
  30789. return this._enabled;
  30790. };
  30791. DebugLayer.prototype.hide = function () {
  30792. if (!this._enabled) {
  30793. return;
  30794. }
  30795. this._enabled = false;
  30796. var engine = this._scene.getEngine();
  30797. this._scene.unregisterBeforeRender(this._syncData);
  30798. this._scene.unregisterAfterRender(this._syncUI);
  30799. document.body.removeChild(this._globalDiv);
  30800. window.removeEventListener("resize", this._syncPositions);
  30801. this._scene.forceShowBoundingBoxes = false;
  30802. this._scene.forceWireframe = false;
  30803. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30804. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30805. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30806. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30807. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30808. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30809. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30810. this._scene.shadowsEnabled = true;
  30811. this._scene.particlesEnabled = true;
  30812. this._scene.postProcessesEnabled = true;
  30813. this._scene.collisionsEnabled = true;
  30814. this._scene.lightsEnabled = true;
  30815. this._scene.texturesEnabled = true;
  30816. this._scene.lensFlaresEnabled = true;
  30817. this._scene.proceduralTexturesEnabled = true;
  30818. this._scene.renderTargetsEnabled = true;
  30819. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30820. };
  30821. DebugLayer.prototype.show = function (showUI, camera) {
  30822. if (showUI === void 0) { showUI = true; }
  30823. if (camera === void 0) { camera = null; }
  30824. if (this._enabled) {
  30825. return;
  30826. }
  30827. this._enabled = true;
  30828. if (camera) {
  30829. this._camera = camera;
  30830. }
  30831. else {
  30832. this._camera = this._scene.activeCamera;
  30833. }
  30834. this._showUI = showUI;
  30835. var engine = this._scene.getEngine();
  30836. this._globalDiv = document.createElement("div");
  30837. document.body.appendChild(this._globalDiv);
  30838. this._generateDOMelements();
  30839. window.addEventListener("resize", this._syncPositions);
  30840. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30841. this._syncPositions();
  30842. this._scene.registerBeforeRender(this._syncData);
  30843. this._scene.registerAfterRender(this._syncUI);
  30844. };
  30845. DebugLayer.prototype._clearLabels = function () {
  30846. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30847. for (var index = 0; index < this._scene.meshes.length; index++) {
  30848. var mesh = this._scene.meshes[index];
  30849. mesh.renderOverlay = false;
  30850. }
  30851. };
  30852. DebugLayer.prototype._generateheader = function (root, text) {
  30853. var header = document.createElement("div");
  30854. header.innerHTML = text + "&nbsp;";
  30855. header.style.textAlign = "right";
  30856. header.style.width = "100%";
  30857. header.style.color = "white";
  30858. header.style.backgroundColor = "Black";
  30859. header.style.padding = "5px 5px 4px 0px";
  30860. header.style.marginLeft = "-5px";
  30861. header.style.fontWeight = "bold";
  30862. root.appendChild(header);
  30863. };
  30864. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30865. var label = document.createElement("label");
  30866. label.innerHTML = title;
  30867. label.style.color = color;
  30868. root.appendChild(label);
  30869. root.appendChild(document.createElement("br"));
  30870. };
  30871. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30872. if (tag === void 0) { tag = null; }
  30873. var label = document.createElement("label");
  30874. var boundingBoxesCheckbox = document.createElement("input");
  30875. boundingBoxesCheckbox.type = "checkbox";
  30876. boundingBoxesCheckbox.checked = initialState;
  30877. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30878. task(evt.target, tag);
  30879. });
  30880. label.appendChild(boundingBoxesCheckbox);
  30881. var container = document.createElement("span");
  30882. var leftPart = document.createElement("span");
  30883. var rightPart = document.createElement("span");
  30884. rightPart.style.cssFloat = "right";
  30885. leftPart.innerHTML = leftTitle;
  30886. rightPart.innerHTML = rightTitle;
  30887. rightPart.style.fontSize = "12px";
  30888. rightPart.style.maxWidth = "200px";
  30889. container.appendChild(leftPart);
  30890. container.appendChild(rightPart);
  30891. label.appendChild(container);
  30892. root.appendChild(label);
  30893. root.appendChild(document.createElement("br"));
  30894. };
  30895. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30896. if (tag === void 0) { tag = null; }
  30897. var label = document.createElement("label");
  30898. var checkBox = document.createElement("input");
  30899. checkBox.type = "checkbox";
  30900. checkBox.checked = initialState;
  30901. checkBox.addEventListener("change", function (evt) {
  30902. task(evt.target, tag);
  30903. });
  30904. label.appendChild(checkBox);
  30905. label.appendChild(document.createTextNode(title));
  30906. root.appendChild(label);
  30907. root.appendChild(document.createElement("br"));
  30908. };
  30909. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30910. if (tag === void 0) { tag = null; }
  30911. var button = document.createElement("button");
  30912. button.innerHTML = title;
  30913. button.style.height = "24px";
  30914. button.style.color = "#444444";
  30915. button.style.border = "1px solid white";
  30916. button.className = "debugLayerButton";
  30917. button.addEventListener("click", function (evt) {
  30918. task(evt.target, tag);
  30919. });
  30920. root.appendChild(button);
  30921. root.appendChild(document.createElement("br"));
  30922. };
  30923. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30924. if (tag === void 0) { tag = null; }
  30925. var label = document.createElement("label");
  30926. var boundingBoxesRadio = document.createElement("input");
  30927. boundingBoxesRadio.type = "radio";
  30928. boundingBoxesRadio.name = name;
  30929. boundingBoxesRadio.checked = initialState;
  30930. boundingBoxesRadio.addEventListener("change", function (evt) {
  30931. task(evt.target, tag);
  30932. });
  30933. label.appendChild(boundingBoxesRadio);
  30934. label.appendChild(document.createTextNode(title));
  30935. root.appendChild(label);
  30936. root.appendChild(document.createElement("br"));
  30937. };
  30938. DebugLayer.prototype._generateDOMelements = function () {
  30939. var _this = this;
  30940. this._globalDiv.id = "DebugLayer";
  30941. this._globalDiv.style.position = "absolute";
  30942. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30943. this._globalDiv.style.fontSize = "14px";
  30944. this._globalDiv.style.color = "white";
  30945. // Drawing canvas
  30946. this._drawingCanvas = document.createElement("canvas");
  30947. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30948. this._drawingCanvas.style.position = "absolute";
  30949. this._drawingCanvas.style.pointerEvents = "none";
  30950. this._drawingContext = this._drawingCanvas.getContext("2d");
  30951. this._globalDiv.appendChild(this._drawingCanvas);
  30952. if (this._showUI) {
  30953. var background = "rgba(128, 128, 128, 0.4)";
  30954. var border = "rgb(180, 180, 180) solid 1px";
  30955. // Stats
  30956. this._statsDiv = document.createElement("div");
  30957. this._statsDiv.id = "DebugLayerStats";
  30958. this._statsDiv.style.border = border;
  30959. this._statsDiv.style.position = "absolute";
  30960. this._statsDiv.style.background = background;
  30961. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30962. this._generateheader(this._statsDiv, "STATISTICS");
  30963. this._statsSubsetDiv = document.createElement("div");
  30964. this._statsSubsetDiv.style.paddingTop = "5px";
  30965. this._statsSubsetDiv.style.paddingBottom = "5px";
  30966. this._statsSubsetDiv.style.overflowY = "auto";
  30967. this._statsDiv.appendChild(this._statsSubsetDiv);
  30968. // Tree
  30969. this._treeDiv = document.createElement("div");
  30970. this._treeDiv.id = "DebugLayerTree";
  30971. this._treeDiv.style.border = border;
  30972. this._treeDiv.style.position = "absolute";
  30973. this._treeDiv.style.background = background;
  30974. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30975. this._treeDiv.style.display = "none";
  30976. this._generateheader(this._treeDiv, "MESHES TREE");
  30977. this._treeSubsetDiv = document.createElement("div");
  30978. this._treeSubsetDiv.style.paddingTop = "5px";
  30979. this._treeSubsetDiv.style.paddingRight = "5px";
  30980. this._treeSubsetDiv.style.overflowY = "auto";
  30981. this._treeSubsetDiv.style.maxHeight = "300px";
  30982. this._treeDiv.appendChild(this._treeSubsetDiv);
  30983. this._needToRefreshMeshesTree = true;
  30984. // Logs
  30985. this._logDiv = document.createElement("div");
  30986. this._logDiv.style.border = border;
  30987. this._logDiv.id = "DebugLayerLogs";
  30988. this._logDiv.style.position = "absolute";
  30989. this._logDiv.style.background = background;
  30990. this._logDiv.style.padding = "0px 0px 0px 5px";
  30991. this._logDiv.style.display = "none";
  30992. this._generateheader(this._logDiv, "LOGS");
  30993. this._logSubsetDiv = document.createElement("div");
  30994. this._logSubsetDiv.style.height = "127px";
  30995. this._logSubsetDiv.style.paddingTop = "5px";
  30996. this._logSubsetDiv.style.overflowY = "auto";
  30997. this._logSubsetDiv.style.fontSize = "12px";
  30998. this._logSubsetDiv.style.fontFamily = "consolas";
  30999. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31000. this._logDiv.appendChild(this._logSubsetDiv);
  31001. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31002. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31003. };
  31004. // Options
  31005. this._optionsDiv = document.createElement("div");
  31006. this._optionsDiv.id = "DebugLayerOptions";
  31007. this._optionsDiv.style.border = border;
  31008. this._optionsDiv.style.position = "absolute";
  31009. this._optionsDiv.style.background = background;
  31010. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31011. this._optionsDiv.style.overflowY = "auto";
  31012. this._generateheader(this._optionsDiv, "OPTIONS");
  31013. this._optionsSubsetDiv = document.createElement("div");
  31014. this._optionsSubsetDiv.style.paddingTop = "5px";
  31015. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31016. this._optionsSubsetDiv.style.overflowY = "auto";
  31017. this._optionsSubsetDiv.style.maxHeight = "200px";
  31018. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31019. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31020. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31021. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31022. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31023. _this._displayTree = element.checked;
  31024. _this._needToRefreshMeshesTree = true;
  31025. });
  31026. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31027. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31028. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31029. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31030. _this._labelsEnabled = element.checked;
  31031. if (!_this._labelsEnabled) {
  31032. _this._clearLabels();
  31033. }
  31034. });
  31035. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31036. if (element.checked) {
  31037. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31038. }
  31039. else {
  31040. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31041. }
  31042. });
  31043. ;
  31044. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31045. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31046. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31047. if (element.checked) {
  31048. _this._scene.forceWireframe = false;
  31049. _this._scene.forcePointsCloud = false;
  31050. }
  31051. });
  31052. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31053. if (element.checked) {
  31054. _this._scene.forceWireframe = true;
  31055. _this._scene.forcePointsCloud = false;
  31056. }
  31057. });
  31058. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31059. if (element.checked) {
  31060. _this._scene.forceWireframe = false;
  31061. _this._scene.forcePointsCloud = true;
  31062. }
  31063. });
  31064. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31065. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31066. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31067. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31068. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31069. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31070. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31071. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31072. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31073. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31074. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31075. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31076. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31077. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31078. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31079. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31080. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31081. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31082. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31083. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31084. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31085. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31086. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31087. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31088. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31089. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31090. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31091. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31092. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31093. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31094. if (element.checked) {
  31095. _this._scene.headphone = true;
  31096. }
  31097. });
  31098. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31099. if (element.checked) {
  31100. _this._scene.headphone = false;
  31101. }
  31102. });
  31103. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31104. _this._scene.audioEnabled = !element.checked;
  31105. });
  31106. }
  31107. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31108. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31109. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31110. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31111. this._globalDiv.appendChild(this._statsDiv);
  31112. this._globalDiv.appendChild(this._logDiv);
  31113. this._globalDiv.appendChild(this._optionsDiv);
  31114. this._globalDiv.appendChild(this._treeDiv);
  31115. }
  31116. };
  31117. DebugLayer.prototype._displayStats = function () {
  31118. var scene = this._scene;
  31119. var engine = scene.getEngine();
  31120. var glInfo = engine.getGlInfo();
  31121. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31122. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31123. + "<b>Count</b><br>"
  31124. + "Total meshes: " + scene.meshes.length + "<br>"
  31125. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31126. + "Total materials: " + scene.materials.length + "<br>"
  31127. + "Total textures: " + scene.textures.length + "<br>"
  31128. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31129. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31130. + "Active bones: " + scene.getActiveBones() + "<br>"
  31131. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31132. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31133. + "<b>Duration</b><br>"
  31134. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31135. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31136. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31137. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31138. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31139. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31140. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31141. + "</div>"
  31142. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31143. + "<b>Extensions</b><br>"
  31144. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31145. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31146. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31147. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31148. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31149. + "<b>Caps.</b><br>"
  31150. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31151. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31152. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31153. + "</div><br>"
  31154. + "<b>Info</b><br>"
  31155. + glInfo.version + "<br>"
  31156. + glInfo.renderer + "<br>";
  31157. if (this.customStatsFunction) {
  31158. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31159. }
  31160. };
  31161. return DebugLayer;
  31162. })();
  31163. BABYLON.DebugLayer = DebugLayer;
  31164. })(BABYLON || (BABYLON = {}));
  31165. var BABYLON;
  31166. (function (BABYLON) {
  31167. var RawTexture = (function (_super) {
  31168. __extends(RawTexture, _super);
  31169. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31170. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31171. if (invertY === void 0) { invertY = false; }
  31172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31173. _super.call(this, null, scene, !generateMipMaps, invertY);
  31174. this.format = format;
  31175. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31176. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31177. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31178. }
  31179. RawTexture.prototype.update = function (data) {
  31180. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31181. };
  31182. // Statics
  31183. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31184. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31185. if (invertY === void 0) { invertY = false; }
  31186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31187. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31188. };
  31189. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31190. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31191. if (invertY === void 0) { invertY = false; }
  31192. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31193. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31194. };
  31195. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31196. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31197. if (invertY === void 0) { invertY = false; }
  31198. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31199. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31200. };
  31201. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31202. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31203. if (invertY === void 0) { invertY = false; }
  31204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31205. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31206. };
  31207. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31208. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31209. if (invertY === void 0) { invertY = false; }
  31210. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31211. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31212. };
  31213. return RawTexture;
  31214. })(BABYLON.Texture);
  31215. BABYLON.RawTexture = RawTexture;
  31216. })(BABYLON || (BABYLON = {}));
  31217. var BABYLON;
  31218. (function (BABYLON) {
  31219. var IndexedVector2 = (function (_super) {
  31220. __extends(IndexedVector2, _super);
  31221. function IndexedVector2(original, index) {
  31222. _super.call(this, original.x, original.y);
  31223. this.index = index;
  31224. }
  31225. return IndexedVector2;
  31226. })(BABYLON.Vector2);
  31227. var PolygonPoints = (function () {
  31228. function PolygonPoints() {
  31229. this.elements = new Array();
  31230. }
  31231. PolygonPoints.prototype.add = function (originalPoints) {
  31232. var _this = this;
  31233. var result = new Array();
  31234. originalPoints.forEach(function (point) {
  31235. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31236. var newPoint = new IndexedVector2(point, _this.elements.length);
  31237. result.push(newPoint);
  31238. _this.elements.push(newPoint);
  31239. }
  31240. });
  31241. return result;
  31242. };
  31243. PolygonPoints.prototype.computeBounds = function () {
  31244. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31245. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31246. this.elements.forEach(function (point) {
  31247. // x
  31248. if (point.x < lmin.x) {
  31249. lmin.x = point.x;
  31250. }
  31251. else if (point.x > lmax.x) {
  31252. lmax.x = point.x;
  31253. }
  31254. // y
  31255. if (point.y < lmin.y) {
  31256. lmin.y = point.y;
  31257. }
  31258. else if (point.y > lmax.y) {
  31259. lmax.y = point.y;
  31260. }
  31261. });
  31262. return {
  31263. min: lmin,
  31264. max: lmax,
  31265. width: lmax.x - lmin.x,
  31266. height: lmax.y - lmin.y
  31267. };
  31268. };
  31269. return PolygonPoints;
  31270. })();
  31271. var Polygon = (function () {
  31272. function Polygon() {
  31273. }
  31274. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31275. return [
  31276. new BABYLON.Vector2(xmin, ymin),
  31277. new BABYLON.Vector2(xmax, ymin),
  31278. new BABYLON.Vector2(xmax, ymax),
  31279. new BABYLON.Vector2(xmin, ymax)
  31280. ];
  31281. };
  31282. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31283. if (cx === void 0) { cx = 0; }
  31284. if (cy === void 0) { cy = 0; }
  31285. if (numberOfSides === void 0) { numberOfSides = 32; }
  31286. var result = new Array();
  31287. var angle = 0;
  31288. var increment = (Math.PI * 2) / numberOfSides;
  31289. for (var i = 0; i < numberOfSides; i++) {
  31290. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31291. angle -= increment;
  31292. }
  31293. return result;
  31294. };
  31295. Polygon.Parse = function (input) {
  31296. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31297. var i, result = [];
  31298. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31299. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31300. }
  31301. return result;
  31302. };
  31303. Polygon.StartingAt = function (x, y) {
  31304. return BABYLON.Path2.StartingAt(x, y);
  31305. };
  31306. return Polygon;
  31307. })();
  31308. BABYLON.Polygon = Polygon;
  31309. var PolygonMeshBuilder = (function () {
  31310. function PolygonMeshBuilder(name, contours, scene) {
  31311. this._points = new PolygonPoints();
  31312. this._outlinepoints = new PolygonPoints();
  31313. this._holes = [];
  31314. if (!("poly2tri" in window)) {
  31315. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31316. }
  31317. this._name = name;
  31318. this._scene = scene;
  31319. var points;
  31320. if (contours instanceof BABYLON.Path2) {
  31321. points = contours.getPoints();
  31322. }
  31323. else {
  31324. points = contours;
  31325. }
  31326. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31327. this._outlinepoints.add(points);
  31328. }
  31329. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31330. this._swctx.addHole(this._points.add(hole));
  31331. var holepoints = new PolygonPoints();
  31332. holepoints.add(hole);
  31333. this._holes.push(holepoints);
  31334. return this;
  31335. };
  31336. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31337. var _this = this;
  31338. if (updatable === void 0) { updatable = false; }
  31339. var result = new BABYLON.Mesh(this._name, this._scene);
  31340. var normals = [];
  31341. var positions = [];
  31342. var uvs = [];
  31343. var bounds = this._points.computeBounds();
  31344. this._points.elements.forEach(function (p) {
  31345. normals.push(0, 1.0, 0);
  31346. positions.push(p.x, 0, p.y);
  31347. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31348. });
  31349. var indices = [];
  31350. this._swctx.triangulate();
  31351. this._swctx.getTriangles().forEach(function (triangle) {
  31352. triangle.getPoints().forEach(function (point) {
  31353. indices.push(point.index);
  31354. });
  31355. });
  31356. if (depth > 0) {
  31357. var positionscount = (positions.length / 3); //get the current pointcount
  31358. this._points.elements.forEach(function (p) {
  31359. normals.push(0, -1.0, 0);
  31360. positions.push(p.x, -depth, p.y);
  31361. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31362. });
  31363. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31364. var p2;
  31365. var poscounter = 0;
  31366. this._swctx.getTriangles().forEach(function (triangle) {
  31367. triangle.getPoints().forEach(function (point) {
  31368. switch (poscounter) {
  31369. case 0:
  31370. p1 = point;
  31371. break;
  31372. case 1:
  31373. p2 = point;
  31374. break;
  31375. case 2:
  31376. indices.push(point.index + positionscount);
  31377. indices.push(p2.index + positionscount);
  31378. indices.push(p1.index + positionscount);
  31379. poscounter = -1;
  31380. break;
  31381. }
  31382. poscounter++;
  31383. //indices.push((<IndexedVector2>point).index + positionscount);
  31384. });
  31385. });
  31386. //Add the sides
  31387. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31388. this._holes.forEach(function (hole) {
  31389. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31390. });
  31391. }
  31392. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31393. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31394. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31395. result.setIndices(indices);
  31396. return result;
  31397. };
  31398. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31399. var StartIndex = positions.length / 3;
  31400. var ulength = 0;
  31401. for (var i = 0; i < points.elements.length; i++) {
  31402. var p = points.elements[i];
  31403. var p1;
  31404. if ((i + 1) > points.elements.length - 1) {
  31405. p1 = points.elements[0];
  31406. }
  31407. else {
  31408. p1 = points.elements[i + 1];
  31409. }
  31410. positions.push(p.x, 0, p.y);
  31411. positions.push(p.x, -depth, p.y);
  31412. positions.push(p1.x, 0, p1.y);
  31413. positions.push(p1.x, -depth, p1.y);
  31414. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31415. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31416. var v3 = v2.subtract(v1);
  31417. var v4 = new BABYLON.Vector3(0, 1, 0);
  31418. var vn = BABYLON.Vector3.Cross(v3, v4);
  31419. vn = vn.normalize();
  31420. uvs.push(ulength / bounds.width, 0);
  31421. uvs.push(ulength / bounds.width, 1);
  31422. ulength += v3.length();
  31423. uvs.push((ulength / bounds.width), 0);
  31424. uvs.push((ulength / bounds.width), 1);
  31425. if (!flip) {
  31426. normals.push(-vn.x, -vn.y, -vn.z);
  31427. normals.push(-vn.x, -vn.y, -vn.z);
  31428. normals.push(-vn.x, -vn.y, -vn.z);
  31429. normals.push(-vn.x, -vn.y, -vn.z);
  31430. indices.push(StartIndex);
  31431. indices.push(StartIndex + 1);
  31432. indices.push(StartIndex + 2);
  31433. indices.push(StartIndex + 1);
  31434. indices.push(StartIndex + 3);
  31435. indices.push(StartIndex + 2);
  31436. }
  31437. else {
  31438. normals.push(vn.x, vn.y, vn.z);
  31439. normals.push(vn.x, vn.y, vn.z);
  31440. normals.push(vn.x, vn.y, vn.z);
  31441. normals.push(vn.x, vn.y, vn.z);
  31442. indices.push(StartIndex);
  31443. indices.push(StartIndex + 2);
  31444. indices.push(StartIndex + 1);
  31445. indices.push(StartIndex + 1);
  31446. indices.push(StartIndex + 2);
  31447. indices.push(StartIndex + 3);
  31448. }
  31449. StartIndex += 4;
  31450. }
  31451. ;
  31452. };
  31453. return PolygonMeshBuilder;
  31454. })();
  31455. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31456. })(BABYLON || (BABYLON = {}));
  31457. var BABYLON;
  31458. (function (BABYLON) {
  31459. var SimplificationSettings = (function () {
  31460. function SimplificationSettings(quality, distance, optimizeMesh) {
  31461. this.quality = quality;
  31462. this.distance = distance;
  31463. this.optimizeMesh = optimizeMesh;
  31464. }
  31465. return SimplificationSettings;
  31466. })();
  31467. BABYLON.SimplificationSettings = SimplificationSettings;
  31468. var SimplificationQueue = (function () {
  31469. function SimplificationQueue() {
  31470. this.running = false;
  31471. this._simplificationArray = [];
  31472. }
  31473. SimplificationQueue.prototype.addTask = function (task) {
  31474. this._simplificationArray.push(task);
  31475. };
  31476. SimplificationQueue.prototype.executeNext = function () {
  31477. var task = this._simplificationArray.pop();
  31478. if (task) {
  31479. this.running = true;
  31480. this.runSimplification(task);
  31481. }
  31482. else {
  31483. this.running = false;
  31484. }
  31485. };
  31486. SimplificationQueue.prototype.runSimplification = function (task) {
  31487. var _this = this;
  31488. if (task.parallelProcessing) {
  31489. //parallel simplifier
  31490. task.settings.forEach(function (setting) {
  31491. var simplifier = _this.getSimplifier(task);
  31492. simplifier.simplify(setting, function (newMesh) {
  31493. task.mesh.addLODLevel(setting.distance, newMesh);
  31494. newMesh.isVisible = true;
  31495. //check if it is the last
  31496. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31497. //all done, run the success callback.
  31498. task.successCallback();
  31499. }
  31500. _this.executeNext();
  31501. });
  31502. });
  31503. }
  31504. else {
  31505. //single simplifier.
  31506. var simplifier = this.getSimplifier(task);
  31507. var runDecimation = function (setting, callback) {
  31508. simplifier.simplify(setting, function (newMesh) {
  31509. task.mesh.addLODLevel(setting.distance, newMesh);
  31510. newMesh.isVisible = true;
  31511. //run the next quality level
  31512. callback();
  31513. });
  31514. };
  31515. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31516. runDecimation(task.settings[loop.index], function () {
  31517. loop.executeNext();
  31518. });
  31519. }, function () {
  31520. //execution ended, run the success callback.
  31521. if (task.successCallback) {
  31522. task.successCallback();
  31523. }
  31524. _this.executeNext();
  31525. });
  31526. }
  31527. };
  31528. SimplificationQueue.prototype.getSimplifier = function (task) {
  31529. switch (task.simplificationType) {
  31530. case SimplificationType.QUADRATIC:
  31531. default:
  31532. return new QuadraticErrorSimplification(task.mesh);
  31533. }
  31534. };
  31535. return SimplificationQueue;
  31536. })();
  31537. BABYLON.SimplificationQueue = SimplificationQueue;
  31538. /**
  31539. * The implemented types of simplification.
  31540. * At the moment only Quadratic Error Decimation is implemented.
  31541. */
  31542. (function (SimplificationType) {
  31543. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31544. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31545. var SimplificationType = BABYLON.SimplificationType;
  31546. var DecimationTriangle = (function () {
  31547. function DecimationTriangle(vertices) {
  31548. this.vertices = vertices;
  31549. this.error = new Array(4);
  31550. this.deleted = false;
  31551. this.isDirty = false;
  31552. this.deletePending = false;
  31553. this.borderFactor = 0;
  31554. }
  31555. return DecimationTriangle;
  31556. })();
  31557. BABYLON.DecimationTriangle = DecimationTriangle;
  31558. var DecimationVertex = (function () {
  31559. function DecimationVertex(position, id) {
  31560. this.position = position;
  31561. this.id = id;
  31562. this.isBorder = true;
  31563. this.q = new QuadraticMatrix();
  31564. this.triangleCount = 0;
  31565. this.triangleStart = 0;
  31566. this.originalOffsets = [];
  31567. }
  31568. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31569. this.position.copyFrom(newPosition);
  31570. };
  31571. return DecimationVertex;
  31572. })();
  31573. BABYLON.DecimationVertex = DecimationVertex;
  31574. var QuadraticMatrix = (function () {
  31575. function QuadraticMatrix(data) {
  31576. this.data = new Array(10);
  31577. for (var i = 0; i < 10; ++i) {
  31578. if (data && data[i]) {
  31579. this.data[i] = data[i];
  31580. }
  31581. else {
  31582. this.data[i] = 0;
  31583. }
  31584. }
  31585. }
  31586. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31587. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31588. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31589. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31590. return det;
  31591. };
  31592. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31593. for (var i = 0; i < 10; ++i) {
  31594. this.data[i] += matrix.data[i];
  31595. }
  31596. };
  31597. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31598. for (var i = 0; i < 10; ++i) {
  31599. this.data[i] += data[i];
  31600. }
  31601. };
  31602. QuadraticMatrix.prototype.add = function (matrix) {
  31603. var m = new QuadraticMatrix();
  31604. for (var i = 0; i < 10; ++i) {
  31605. m.data[i] = this.data[i] + matrix.data[i];
  31606. }
  31607. return m;
  31608. };
  31609. QuadraticMatrix.FromData = function (a, b, c, d) {
  31610. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31611. };
  31612. //returning an array to avoid garbage collection
  31613. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31614. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31615. };
  31616. return QuadraticMatrix;
  31617. })();
  31618. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31619. var Reference = (function () {
  31620. function Reference(vertexId, triangleId) {
  31621. this.vertexId = vertexId;
  31622. this.triangleId = triangleId;
  31623. }
  31624. return Reference;
  31625. })();
  31626. BABYLON.Reference = Reference;
  31627. /**
  31628. * An implementation of the Quadratic Error simplification algorithm.
  31629. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31630. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31631. * @author RaananW
  31632. */
  31633. var QuadraticErrorSimplification = (function () {
  31634. function QuadraticErrorSimplification(_mesh) {
  31635. this._mesh = _mesh;
  31636. this.initialized = false;
  31637. this.syncIterations = 5000;
  31638. this.aggressiveness = 7;
  31639. this.decimationIterations = 100;
  31640. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31641. }
  31642. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31643. var _this = this;
  31644. this.initDecimatedMesh();
  31645. //iterating through the submeshes array, one after the other.
  31646. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31647. _this.initWithMesh(loop.index, function () {
  31648. _this.runDecimation(settings, loop.index, function () {
  31649. loop.executeNext();
  31650. });
  31651. }, settings.optimizeMesh);
  31652. }, function () {
  31653. setTimeout(function () {
  31654. successCallback(_this._reconstructedMesh);
  31655. }, 0);
  31656. });
  31657. };
  31658. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31659. var _this = this;
  31660. var gCount = 0;
  31661. triangle.vertices.forEach(function (vertex) {
  31662. var count = 0;
  31663. var vPos = vertex.position;
  31664. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31665. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31666. ++count;
  31667. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31668. ++count;
  31669. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31670. ++count;
  31671. if (count > 1) {
  31672. ++gCount;
  31673. }
  31674. ;
  31675. });
  31676. if (gCount > 1) {
  31677. console.log(triangle, gCount);
  31678. }
  31679. return gCount > 1;
  31680. };
  31681. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31682. var _this = this;
  31683. var targetCount = ~~(this.triangles.length * settings.quality);
  31684. var deletedTriangles = 0;
  31685. var triangleCount = this.triangles.length;
  31686. var iterationFunction = function (iteration, callback) {
  31687. setTimeout(function () {
  31688. if (iteration % 5 === 0) {
  31689. _this.updateMesh(iteration === 0);
  31690. }
  31691. for (var i = 0; i < _this.triangles.length; ++i) {
  31692. _this.triangles[i].isDirty = false;
  31693. }
  31694. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31695. var trianglesIterator = function (i) {
  31696. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31697. var t = _this.triangles[tIdx];
  31698. if (!t)
  31699. return;
  31700. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31701. return;
  31702. }
  31703. for (var j = 0; j < 3; ++j) {
  31704. if (t.error[j] < threshold) {
  31705. var deleted0 = [];
  31706. var deleted1 = [];
  31707. var v0 = t.vertices[j];
  31708. var v1 = t.vertices[(j + 1) % 3];
  31709. if (v0.isBorder !== v1.isBorder)
  31710. continue;
  31711. var p = BABYLON.Vector3.Zero();
  31712. var n = BABYLON.Vector3.Zero();
  31713. var uv = BABYLON.Vector2.Zero();
  31714. var color = new BABYLON.Color4(0, 0, 0, 1);
  31715. _this.calculateError(v0, v1, p, n, uv, color);
  31716. var delTr = [];
  31717. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31718. continue;
  31719. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31720. continue;
  31721. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31722. continue;
  31723. var uniqueArray = [];
  31724. delTr.forEach(function (deletedT) {
  31725. if (uniqueArray.indexOf(deletedT) === -1) {
  31726. deletedT.deletePending = true;
  31727. uniqueArray.push(deletedT);
  31728. }
  31729. });
  31730. if (uniqueArray.length % 2 != 0) {
  31731. continue;
  31732. }
  31733. v0.q = v1.q.add(v0.q);
  31734. v0.updatePosition(p);
  31735. var tStart = _this.references.length;
  31736. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31737. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31738. var tCount = _this.references.length - tStart;
  31739. if (tCount <= v0.triangleCount) {
  31740. if (tCount) {
  31741. for (var c = 0; c < tCount; c++) {
  31742. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31743. }
  31744. }
  31745. }
  31746. else {
  31747. v0.triangleStart = tStart;
  31748. }
  31749. v0.triangleCount = tCount;
  31750. break;
  31751. }
  31752. }
  31753. };
  31754. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31755. }, 0);
  31756. };
  31757. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31758. if (triangleCount - deletedTriangles <= targetCount)
  31759. loop.breakLoop();
  31760. else {
  31761. iterationFunction(loop.index, function () {
  31762. loop.executeNext();
  31763. });
  31764. }
  31765. }, function () {
  31766. setTimeout(function () {
  31767. //reconstruct this part of the mesh
  31768. _this.reconstructMesh(submeshIndex);
  31769. successCallback();
  31770. }, 0);
  31771. });
  31772. };
  31773. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31774. var _this = this;
  31775. this.vertices = [];
  31776. this.triangles = [];
  31777. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31778. var indices = this._mesh.getIndices();
  31779. var submesh = this._mesh.subMeshes[submeshIndex];
  31780. var findInVertices = function (positionToSearch) {
  31781. if (optimizeMesh) {
  31782. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31783. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31784. return _this.vertices[ii];
  31785. }
  31786. }
  31787. }
  31788. return null;
  31789. };
  31790. var vertexReferences = [];
  31791. var vertexInit = function (i) {
  31792. var offset = i + submesh.verticesStart;
  31793. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31794. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31795. vertex.originalOffsets.push(offset);
  31796. if (vertex.id == _this.vertices.length) {
  31797. _this.vertices.push(vertex);
  31798. }
  31799. vertexReferences.push(vertex.id);
  31800. };
  31801. //var totalVertices = mesh.getTotalVertices();
  31802. var totalVertices = submesh.verticesCount;
  31803. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31804. var indicesInit = function (i) {
  31805. var offset = (submesh.indexStart / 3) + i;
  31806. var pos = (offset * 3);
  31807. var i0 = indices[pos + 0];
  31808. var i1 = indices[pos + 1];
  31809. var i2 = indices[pos + 2];
  31810. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31811. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31812. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31813. var triangle = new DecimationTriangle([v0, v1, v2]);
  31814. triangle.originalOffset = pos;
  31815. _this.triangles.push(triangle);
  31816. };
  31817. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31818. _this.init(callback);
  31819. });
  31820. });
  31821. };
  31822. QuadraticErrorSimplification.prototype.init = function (callback) {
  31823. var _this = this;
  31824. var triangleInit1 = function (i) {
  31825. var t = _this.triangles[i];
  31826. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31827. for (var j = 0; j < 3; j++) {
  31828. 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))));
  31829. }
  31830. };
  31831. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31832. var triangleInit2 = function (i) {
  31833. var t = _this.triangles[i];
  31834. for (var j = 0; j < 3; ++j) {
  31835. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31836. }
  31837. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31838. };
  31839. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31840. _this.initialized = true;
  31841. callback();
  31842. });
  31843. });
  31844. };
  31845. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31846. var newTriangles = [];
  31847. var i;
  31848. for (i = 0; i < this.vertices.length; ++i) {
  31849. this.vertices[i].triangleCount = 0;
  31850. }
  31851. var t;
  31852. var j;
  31853. for (i = 0; i < this.triangles.length; ++i) {
  31854. if (!this.triangles[i].deleted) {
  31855. t = this.triangles[i];
  31856. for (j = 0; j < 3; ++j) {
  31857. t.vertices[j].triangleCount = 1;
  31858. }
  31859. newTriangles.push(t);
  31860. }
  31861. }
  31862. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31863. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31864. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31865. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31866. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31867. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31868. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31869. var vertexCount = 0;
  31870. for (i = 0; i < this.vertices.length; ++i) {
  31871. var vertex = this.vertices[i];
  31872. vertex.id = vertexCount;
  31873. if (vertex.triangleCount) {
  31874. vertex.originalOffsets.forEach(function (originalOffset) {
  31875. newPositionData.push(vertex.position.x);
  31876. newPositionData.push(vertex.position.y);
  31877. newPositionData.push(vertex.position.z);
  31878. newNormalData.push(normalData[originalOffset * 3]);
  31879. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31880. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31881. if (uvs && uvs.length) {
  31882. newUVsData.push(uvs[(originalOffset * 2)]);
  31883. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31884. }
  31885. else if (colorsData && colorsData.length) {
  31886. newColorsData.push(colorsData[(originalOffset * 4)]);
  31887. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31888. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31889. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31890. }
  31891. ++vertexCount;
  31892. });
  31893. }
  31894. }
  31895. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31896. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31897. var submeshesArray = this._reconstructedMesh.subMeshes;
  31898. this._reconstructedMesh.subMeshes = [];
  31899. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31900. var originalIndices = this._mesh.getIndices();
  31901. for (i = 0; i < newTriangles.length; ++i) {
  31902. var t = newTriangles[i];
  31903. //now get the new referencing point for each vertex
  31904. [0, 1, 2].forEach(function (idx) {
  31905. var id = originalIndices[t.originalOffset + idx];
  31906. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31907. if (offset < 0)
  31908. offset = 0;
  31909. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31910. });
  31911. }
  31912. //overwriting the old vertex buffers and indices.
  31913. this._reconstructedMesh.setIndices(newIndicesArray);
  31914. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31915. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31916. if (newUVsData.length > 0)
  31917. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31918. if (newColorsData.length > 0)
  31919. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31920. //create submesh
  31921. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31922. if (submeshIndex > 0) {
  31923. this._reconstructedMesh.subMeshes = [];
  31924. submeshesArray.forEach(function (submesh) {
  31925. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31926. });
  31927. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31928. }
  31929. };
  31930. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31931. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31932. this._reconstructedMesh.material = this._mesh.material;
  31933. this._reconstructedMesh.parent = this._mesh.parent;
  31934. this._reconstructedMesh.isVisible = false;
  31935. };
  31936. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31937. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31938. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31939. if (t.deleted)
  31940. continue;
  31941. var s = this.references[vertex1.triangleStart + i].vertexId;
  31942. var v1 = t.vertices[(s + 1) % 3];
  31943. var v2 = t.vertices[(s + 2) % 3];
  31944. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31945. deletedArray[i] = true;
  31946. delTr.push(t);
  31947. continue;
  31948. }
  31949. var d1 = v1.position.subtract(point);
  31950. d1 = d1.normalize();
  31951. var d2 = v2.position.subtract(point);
  31952. d2 = d2.normalize();
  31953. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31954. return true;
  31955. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31956. deletedArray[i] = false;
  31957. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31958. return true;
  31959. }
  31960. return false;
  31961. };
  31962. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31963. var newDeleted = deletedTriangles;
  31964. for (var i = 0; i < vertex.triangleCount; ++i) {
  31965. var ref = this.references[vertex.triangleStart + i];
  31966. var t = this.triangles[ref.triangleId];
  31967. if (t.deleted)
  31968. continue;
  31969. if (deletedArray[i] && t.deletePending) {
  31970. t.deleted = true;
  31971. newDeleted++;
  31972. continue;
  31973. }
  31974. t.vertices[ref.vertexId] = origVertex;
  31975. t.isDirty = true;
  31976. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31977. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31978. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31979. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31980. this.references.push(ref);
  31981. }
  31982. return newDeleted;
  31983. };
  31984. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31985. for (var i = 0; i < this.vertices.length; ++i) {
  31986. var vCount = [];
  31987. var vId = [];
  31988. var v = this.vertices[i];
  31989. var j;
  31990. for (j = 0; j < v.triangleCount; ++j) {
  31991. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31992. for (var ii = 0; ii < 3; ii++) {
  31993. var ofs = 0;
  31994. var vv = triangle.vertices[ii];
  31995. while (ofs < vCount.length) {
  31996. if (vId[ofs] === vv.id)
  31997. break;
  31998. ++ofs;
  31999. }
  32000. if (ofs === vCount.length) {
  32001. vCount.push(1);
  32002. vId.push(vv.id);
  32003. }
  32004. else {
  32005. vCount[ofs]++;
  32006. }
  32007. }
  32008. }
  32009. for (j = 0; j < vCount.length; ++j) {
  32010. if (vCount[j] === 1) {
  32011. this.vertices[vId[j]].isBorder = true;
  32012. }
  32013. else {
  32014. this.vertices[vId[j]].isBorder = false;
  32015. }
  32016. }
  32017. }
  32018. };
  32019. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32020. if (identifyBorders === void 0) { identifyBorders = false; }
  32021. var i;
  32022. if (!identifyBorders) {
  32023. var newTrianglesVector = [];
  32024. for (i = 0; i < this.triangles.length; ++i) {
  32025. if (!this.triangles[i].deleted) {
  32026. newTrianglesVector.push(this.triangles[i]);
  32027. }
  32028. }
  32029. this.triangles = newTrianglesVector;
  32030. }
  32031. for (i = 0; i < this.vertices.length; ++i) {
  32032. this.vertices[i].triangleCount = 0;
  32033. this.vertices[i].triangleStart = 0;
  32034. }
  32035. var t;
  32036. var j;
  32037. var v;
  32038. for (i = 0; i < this.triangles.length; ++i) {
  32039. t = this.triangles[i];
  32040. for (j = 0; j < 3; ++j) {
  32041. v = t.vertices[j];
  32042. v.triangleCount++;
  32043. }
  32044. }
  32045. var tStart = 0;
  32046. for (i = 0; i < this.vertices.length; ++i) {
  32047. this.vertices[i].triangleStart = tStart;
  32048. tStart += this.vertices[i].triangleCount;
  32049. this.vertices[i].triangleCount = 0;
  32050. }
  32051. var newReferences = new Array(this.triangles.length * 3);
  32052. for (i = 0; i < this.triangles.length; ++i) {
  32053. t = this.triangles[i];
  32054. for (j = 0; j < 3; ++j) {
  32055. v = t.vertices[j];
  32056. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32057. v.triangleCount++;
  32058. }
  32059. }
  32060. this.references = newReferences;
  32061. if (identifyBorders) {
  32062. this.identifyBorder();
  32063. }
  32064. };
  32065. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32066. var x = point.x;
  32067. var y = point.y;
  32068. var z = point.z;
  32069. 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
  32070. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32071. };
  32072. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32073. var q = vertex1.q.add(vertex2.q);
  32074. var border = vertex1.isBorder && vertex2.isBorder;
  32075. var error = 0;
  32076. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32077. if (qDet !== 0 && !border) {
  32078. if (!pointResult) {
  32079. pointResult = BABYLON.Vector3.Zero();
  32080. }
  32081. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32082. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32083. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32084. error = this.vertexError(q, pointResult);
  32085. }
  32086. else {
  32087. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32088. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32089. var error1 = this.vertexError(q, vertex1.position);
  32090. var error2 = this.vertexError(q, vertex2.position);
  32091. var error3 = this.vertexError(q, p3);
  32092. error = Math.min(error1, error2, error3);
  32093. if (error === error1) {
  32094. if (pointResult) {
  32095. pointResult.copyFrom(vertex1.position);
  32096. }
  32097. }
  32098. else if (error === error2) {
  32099. if (pointResult) {
  32100. pointResult.copyFrom(vertex2.position);
  32101. }
  32102. }
  32103. else {
  32104. if (pointResult) {
  32105. pointResult.copyFrom(p3);
  32106. }
  32107. }
  32108. }
  32109. return error;
  32110. };
  32111. return QuadraticErrorSimplification;
  32112. })();
  32113. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32114. })(BABYLON || (BABYLON = {}));
  32115. var BABYLON;
  32116. (function (BABYLON) {
  32117. var Analyser = (function () {
  32118. function Analyser(scene) {
  32119. this.SMOOTHING = 0.75;
  32120. this.FFT_SIZE = 512;
  32121. this.BARGRAPHAMPLITUDE = 256;
  32122. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32123. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32124. this._scene = scene;
  32125. this._audioEngine = BABYLON.Engine.audioEngine;
  32126. if (this._audioEngine.canUseWebAudio) {
  32127. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32128. this._webAudioAnalyser.minDecibels = -140;
  32129. this._webAudioAnalyser.maxDecibels = 0;
  32130. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32131. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32132. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32133. }
  32134. }
  32135. Analyser.prototype.getFrequencyBinCount = function () {
  32136. if (this._audioEngine.canUseWebAudio) {
  32137. return this._webAudioAnalyser.frequencyBinCount;
  32138. }
  32139. else {
  32140. return 0;
  32141. }
  32142. };
  32143. Analyser.prototype.getByteFrequencyData = function () {
  32144. if (this._audioEngine.canUseWebAudio) {
  32145. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32146. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32147. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32148. }
  32149. return this._byteFreqs;
  32150. };
  32151. Analyser.prototype.getByteTimeDomainData = function () {
  32152. if (this._audioEngine.canUseWebAudio) {
  32153. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32154. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32155. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32156. }
  32157. return this._byteTime;
  32158. };
  32159. Analyser.prototype.getFloatFrequencyData = function () {
  32160. if (this._audioEngine.canUseWebAudio) {
  32161. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32162. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32163. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32164. }
  32165. return this._floatFreqs;
  32166. };
  32167. Analyser.prototype.drawDebugCanvas = function () {
  32168. var _this = this;
  32169. if (this._audioEngine.canUseWebAudio) {
  32170. if (!this._debugCanvas) {
  32171. this._debugCanvas = document.createElement("canvas");
  32172. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32173. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32174. this._debugCanvas.style.position = "absolute";
  32175. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32176. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32177. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32178. document.body.appendChild(this._debugCanvas);
  32179. this._registerFunc = function () {
  32180. _this.drawDebugCanvas();
  32181. };
  32182. this._scene.registerBeforeRender(this._registerFunc);
  32183. }
  32184. if (this._registerFunc) {
  32185. var workingArray = this.getByteFrequencyData();
  32186. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32187. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32188. // Draw the frequency domain chart.
  32189. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32190. var value = workingArray[i];
  32191. var percent = value / this.BARGRAPHAMPLITUDE;
  32192. var height = this.DEBUGCANVASSIZE.height * percent;
  32193. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32194. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32195. var hue = i / this.getFrequencyBinCount() * 360;
  32196. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32197. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32198. }
  32199. }
  32200. }
  32201. };
  32202. Analyser.prototype.stopDebugCanvas = function () {
  32203. if (this._debugCanvas) {
  32204. this._scene.unregisterBeforeRender(this._registerFunc);
  32205. this._registerFunc = null;
  32206. document.body.removeChild(this._debugCanvas);
  32207. this._debugCanvas = null;
  32208. this._debugCanvasContext = null;
  32209. }
  32210. };
  32211. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32212. if (this._audioEngine.canUseWebAudio) {
  32213. inputAudioNode.connect(this._webAudioAnalyser);
  32214. this._webAudioAnalyser.connect(outputAudioNode);
  32215. }
  32216. };
  32217. Analyser.prototype.dispose = function () {
  32218. if (this._audioEngine.canUseWebAudio) {
  32219. this._webAudioAnalyser.disconnect();
  32220. }
  32221. };
  32222. return Analyser;
  32223. })();
  32224. BABYLON.Analyser = Analyser;
  32225. })(BABYLON || (BABYLON = {}));
  32226. var BABYLON;
  32227. (function (BABYLON) {
  32228. var DepthRenderer = (function () {
  32229. function DepthRenderer(scene, type) {
  32230. var _this = this;
  32231. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32232. this._viewMatrix = BABYLON.Matrix.Zero();
  32233. this._projectionMatrix = BABYLON.Matrix.Zero();
  32234. this._transformMatrix = BABYLON.Matrix.Zero();
  32235. this._worldViewProjection = BABYLON.Matrix.Zero();
  32236. this._scene = scene;
  32237. var engine = scene.getEngine();
  32238. // Render target
  32239. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32240. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32241. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32242. this._depthMap.refreshRate = 1;
  32243. this._depthMap.renderParticles = false;
  32244. this._depthMap.renderList = null;
  32245. // set default depth value to 1.0 (far away)
  32246. this._depthMap.onClear = function (engine) {
  32247. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32248. };
  32249. // Custom render function
  32250. var renderSubMesh = function (subMesh) {
  32251. var mesh = subMesh.getRenderingMesh();
  32252. var scene = _this._scene;
  32253. var engine = scene.getEngine();
  32254. // Culling
  32255. engine.setState(subMesh.getMaterial().backFaceCulling);
  32256. // Managing instances
  32257. var batch = mesh._getInstancesRenderList(subMesh._id);
  32258. if (batch.mustReturn) {
  32259. return;
  32260. }
  32261. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32262. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32263. engine.enableEffect(_this._effect);
  32264. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32265. var material = subMesh.getMaterial();
  32266. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32267. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32268. // Alpha test
  32269. if (material && material.needAlphaTesting()) {
  32270. var alphaTexture = material.getAlphaTestTexture();
  32271. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32272. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32273. }
  32274. // Bones
  32275. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32276. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32277. }
  32278. // Draw
  32279. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32280. }
  32281. };
  32282. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32283. var index;
  32284. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32285. renderSubMesh(opaqueSubMeshes.data[index]);
  32286. }
  32287. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32288. renderSubMesh(alphaTestSubMeshes.data[index]);
  32289. }
  32290. };
  32291. }
  32292. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32293. var defines = [];
  32294. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32295. var mesh = subMesh.getMesh();
  32296. var scene = mesh.getScene();
  32297. var material = subMesh.getMaterial();
  32298. // Alpha test
  32299. if (material && material.needAlphaTesting()) {
  32300. defines.push("#define ALPHATEST");
  32301. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32302. attribs.push(BABYLON.VertexBuffer.UVKind);
  32303. defines.push("#define UV1");
  32304. }
  32305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32306. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32307. defines.push("#define UV2");
  32308. }
  32309. }
  32310. // Bones
  32311. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32312. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32313. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32314. defines.push("#define BONES");
  32315. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32316. }
  32317. // Instances
  32318. if (useInstances) {
  32319. defines.push("#define INSTANCES");
  32320. attribs.push("world0");
  32321. attribs.push("world1");
  32322. attribs.push("world2");
  32323. attribs.push("world3");
  32324. }
  32325. // Get correct effect
  32326. var join = defines.join("\n");
  32327. if (this._cachedDefines !== join) {
  32328. this._cachedDefines = join;
  32329. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32330. }
  32331. return this._effect.isReady();
  32332. };
  32333. DepthRenderer.prototype.getDepthMap = function () {
  32334. return this._depthMap;
  32335. };
  32336. // Methods
  32337. DepthRenderer.prototype.dispose = function () {
  32338. this._depthMap.dispose();
  32339. };
  32340. return DepthRenderer;
  32341. })();
  32342. BABYLON.DepthRenderer = DepthRenderer;
  32343. })(BABYLON || (BABYLON = {}));
  32344. var BABYLON;
  32345. (function (BABYLON) {
  32346. var SSAORenderingPipeline = (function (_super) {
  32347. __extends(SSAORenderingPipeline, _super);
  32348. /**
  32349. * @constructor
  32350. * @param {string} name - The rendering pipeline name
  32351. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32352. * @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 }
  32353. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32354. */
  32355. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32356. var _this = this;
  32357. _super.call(this, scene.getEngine(), name);
  32358. // Members
  32359. /**
  32360. * The PassPostProcess id in the pipeline that contains the original scene color
  32361. * @type {string}
  32362. */
  32363. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32364. /**
  32365. * The SSAO PostProcess id in the pipeline
  32366. * @type {string}
  32367. */
  32368. this.SSAORenderEffect = "SSAORenderEffect";
  32369. /**
  32370. * The horizontal blur PostProcess id in the pipeline
  32371. * @type {string}
  32372. */
  32373. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32374. /**
  32375. * The vertical blur PostProcess id in the pipeline
  32376. * @type {string}
  32377. */
  32378. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32379. /**
  32380. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32381. * @type {string}
  32382. */
  32383. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32384. /**
  32385. * The output strength of the SSAO post-process. Default value is 1.0.
  32386. * @type {number}
  32387. */
  32388. this.totalStrength = 1.0;
  32389. /**
  32390. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32391. * @type {number}
  32392. */
  32393. this.radius = 0.0002;
  32394. /**
  32395. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32396. * Must not be equal to fallOff and superior to fallOff.
  32397. * Default value is 0.0075
  32398. * @type {number}
  32399. */
  32400. this.area = 0.0075;
  32401. /**
  32402. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32403. * Must not be equal to area and inferior to area.
  32404. * Default value is 0.0002
  32405. * @type {number}
  32406. */
  32407. this.fallOff = 0.0002;
  32408. this._firstUpdate = true;
  32409. this._scene = scene;
  32410. // Set up assets
  32411. this._createRandomTexture();
  32412. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32413. var ssaoRatio = ratio.ssaoRatio || ratio;
  32414. var combineRatio = ratio.combineRatio || ratio;
  32415. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32416. this._createSSAOPostProcess(ssaoRatio);
  32417. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32418. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32419. this._createSSAOCombinePostProcess(combineRatio);
  32420. // Set up pipeline
  32421. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32422. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32426. // Finish
  32427. scene.postProcessRenderPipelineManager.addPipeline(this);
  32428. if (cameras)
  32429. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32430. }
  32431. // Public Methods
  32432. /**
  32433. * Returns the horizontal blur PostProcess
  32434. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32435. */
  32436. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32437. return this._blurHPostProcess;
  32438. };
  32439. /**
  32440. * Returns the vertical blur PostProcess
  32441. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32442. */
  32443. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32444. return this._blurVPostProcess;
  32445. };
  32446. /**
  32447. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32448. */
  32449. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32450. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32451. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32452. this._originalColorPostProcess = undefined;
  32453. this._ssaoPostProcess = undefined;
  32454. this._blurHPostProcess = undefined;
  32455. this._blurVPostProcess = undefined;
  32456. this._ssaoCombinePostProcess = undefined;
  32457. this._randomTexture.dispose();
  32458. if (disableDepthRender)
  32459. this._scene.disableDepthRenderer();
  32460. };
  32461. // Private Methods
  32462. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32463. var _this = this;
  32464. var sampleSphere = [
  32465. 0.5381, 0.1856, -0.4319,
  32466. 0.1379, 0.2486, 0.4430,
  32467. 0.3371, 0.5679, -0.0057,
  32468. -0.6999, -0.0451, -0.0019,
  32469. 0.0689, -0.1598, -0.8547,
  32470. 0.0560, 0.0069, -0.1843,
  32471. -0.0146, 0.1402, 0.0762,
  32472. 0.0100, -0.1924, -0.0344,
  32473. -0.3577, -0.5301, -0.4358,
  32474. -0.3169, 0.1063, 0.0158,
  32475. 0.0103, -0.5869, 0.0046,
  32476. -0.0897, -0.4940, 0.3287,
  32477. 0.7119, -0.0154, -0.0918,
  32478. -0.0533, 0.0596, -0.5411,
  32479. 0.0352, -0.0631, 0.5460,
  32480. -0.4776, 0.2847, -0.0271
  32481. ];
  32482. var samplesFactor = 1.0 / 16.0;
  32483. 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);
  32484. this._ssaoPostProcess.onApply = function (effect) {
  32485. if (_this._firstUpdate) {
  32486. effect.setArray3("sampleSphere", sampleSphere);
  32487. effect.setFloat("samplesFactor", samplesFactor);
  32488. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32489. _this._firstUpdate = false;
  32490. }
  32491. effect.setFloat("totalStrength", _this.totalStrength);
  32492. effect.setFloat("radius", _this.radius);
  32493. effect.setFloat("area", _this.area);
  32494. effect.setFloat("fallOff", _this.fallOff);
  32495. effect.setTexture("textureSampler", _this._depthTexture);
  32496. effect.setTexture("randomSampler", _this._randomTexture);
  32497. };
  32498. };
  32499. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32500. var _this = this;
  32501. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32502. this._ssaoCombinePostProcess.onApply = function (effect) {
  32503. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32504. };
  32505. };
  32506. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32507. var size = 512;
  32508. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32509. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32510. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32511. var context = this._randomTexture.getContext();
  32512. var rand = function (min, max) {
  32513. return Math.random() * (max - min) + min;
  32514. };
  32515. for (var x = 0; x < size; x++) {
  32516. for (var y = 0; y < size; y++) {
  32517. var randVector = BABYLON.Vector3.Zero();
  32518. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32519. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32520. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32521. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32522. context.fillRect(x, y, 1, 1);
  32523. }
  32524. }
  32525. this._randomTexture.update(false);
  32526. };
  32527. return SSAORenderingPipeline;
  32528. })(BABYLON.PostProcessRenderPipeline);
  32529. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32530. })(BABYLON || (BABYLON = {}));
  32531. var BABYLON;
  32532. (function (BABYLON) {
  32533. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32534. var VolumetricLightScatteringPostProcess = (function (_super) {
  32535. __extends(VolumetricLightScatteringPostProcess, _super);
  32536. /**
  32537. * @constructor
  32538. * @param {string} name - The post-process name
  32539. * @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)
  32540. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32541. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32542. * @param {number} samples - The post-process quality, default 100
  32543. * @param {number} samplingMode - The post-process filtering mode
  32544. * @param {BABYLON.Engine} engine - The babylon engine
  32545. * @param {boolean} reusable - If the post-process is reusable
  32546. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32547. */
  32548. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32549. var _this = this;
  32550. if (samples === void 0) { samples = 100; }
  32551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32552. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32553. this._screenCoordinates = BABYLON.Vector2.Zero();
  32554. /**
  32555. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32556. * @type {boolean}
  32557. */
  32558. this.useCustomMeshPosition = false;
  32559. /**
  32560. * If the post-process should inverse the light scattering direction
  32561. * @type {boolean}
  32562. */
  32563. this.invert = true;
  32564. /**
  32565. * Set to true to use the diffuseColor instead of the diffuseTexture
  32566. * @type {boolean}
  32567. */
  32568. this.useDiffuseColor = false;
  32569. /**
  32570. * Array containing the excluded meshes not rendered in the internal pass
  32571. */
  32572. this.excludedMeshes = new Array();
  32573. /**
  32574. * Controls the overall intensity of the post-process
  32575. * @type {number}
  32576. */
  32577. this.exposure = 0.3;
  32578. /**
  32579. * Dissipates each sample's contribution in range [0, 1]
  32580. * @type {number}
  32581. */
  32582. this.decay = 0.96815;
  32583. /**
  32584. * Controls the overall intensity of each sample
  32585. * @type {number}
  32586. */
  32587. this.weight = 0.58767;
  32588. /**
  32589. * Controls the density of each sample
  32590. * @type {number}
  32591. */
  32592. this.density = 0.926;
  32593. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32594. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32595. // Configure mesh
  32596. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32597. // Configure
  32598. this._createPass(scene, ratio.passRatio || ratio);
  32599. this.onApply = function (effect) {
  32600. _this._updateMeshScreenCoordinates(scene);
  32601. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32602. effect.setFloat("exposure", _this.exposure);
  32603. effect.setFloat("decay", _this.decay);
  32604. effect.setFloat("weight", _this.weight);
  32605. effect.setFloat("density", _this.density);
  32606. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32607. };
  32608. }
  32609. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32610. var mesh = subMesh.getMesh();
  32611. var defines = [];
  32612. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32613. var material = subMesh.getMaterial();
  32614. var needUV = false;
  32615. // Render this.mesh as default
  32616. if (mesh === this.mesh) {
  32617. if (this.useDiffuseColor) {
  32618. defines.push("#define DIFFUSE_COLOR_RENDER");
  32619. }
  32620. else if (material) {
  32621. if (material.diffuseTexture !== undefined) {
  32622. defines.push("#define BASIC_RENDER");
  32623. }
  32624. else {
  32625. defines.push("#define DIFFUSE_COLOR_RENDER");
  32626. }
  32627. }
  32628. defines.push("#define NEED_UV");
  32629. needUV = true;
  32630. }
  32631. // Alpha test
  32632. if (material) {
  32633. if (material.needAlphaTesting()) {
  32634. defines.push("#define ALPHATEST");
  32635. }
  32636. if (material.opacityTexture !== undefined) {
  32637. defines.push("#define OPACITY");
  32638. if (material.opacityTexture.getAlphaFromRGB) {
  32639. defines.push("#define OPACITYRGB");
  32640. }
  32641. if (!needUV) {
  32642. defines.push("#define NEED_UV");
  32643. }
  32644. }
  32645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32646. attribs.push(BABYLON.VertexBuffer.UVKind);
  32647. defines.push("#define UV1");
  32648. }
  32649. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32650. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32651. defines.push("#define UV2");
  32652. }
  32653. }
  32654. // Bones
  32655. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32658. defines.push("#define BONES");
  32659. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32660. }
  32661. // Instances
  32662. if (useInstances) {
  32663. defines.push("#define INSTANCES");
  32664. attribs.push("world0");
  32665. attribs.push("world1");
  32666. attribs.push("world2");
  32667. attribs.push("world3");
  32668. }
  32669. // Get correct effect
  32670. var join = defines.join("\n");
  32671. if (this._cachedDefines !== join) {
  32672. this._cachedDefines = join;
  32673. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32674. }
  32675. return this._volumetricLightScatteringPass.isReady();
  32676. };
  32677. /**
  32678. * Sets the new light position for light scattering effect
  32679. * @param {BABYLON.Vector3} The new custom light position
  32680. */
  32681. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32682. this._customMeshPosition = position;
  32683. };
  32684. /**
  32685. * Returns the light position for light scattering effect
  32686. * @return {BABYLON.Vector3} The custom light position
  32687. */
  32688. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32689. return this._customMeshPosition;
  32690. };
  32691. /**
  32692. * Disposes the internal assets and detaches the post-process from the camera
  32693. */
  32694. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32695. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32696. if (rttIndex !== -1) {
  32697. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32698. }
  32699. this._volumetricLightScatteringRTT.dispose();
  32700. _super.prototype.dispose.call(this, camera);
  32701. };
  32702. /**
  32703. * Returns the render target texture used by the post-process
  32704. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32705. */
  32706. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32707. return this._volumetricLightScatteringRTT;
  32708. };
  32709. // Private methods
  32710. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32711. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32712. return true;
  32713. }
  32714. return false;
  32715. };
  32716. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32717. var _this = this;
  32718. var engine = scene.getEngine();
  32719. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32720. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32721. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32722. this._volumetricLightScatteringRTT.renderList = null;
  32723. this._volumetricLightScatteringRTT.renderParticles = false;
  32724. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32725. // Custom render function for submeshes
  32726. var renderSubMesh = function (subMesh) {
  32727. var mesh = subMesh.getRenderingMesh();
  32728. if (_this._meshExcluded(mesh)) {
  32729. return;
  32730. }
  32731. var scene = mesh.getScene();
  32732. var engine = scene.getEngine();
  32733. // Culling
  32734. engine.setState(subMesh.getMaterial().backFaceCulling);
  32735. // Managing instances
  32736. var batch = mesh._getInstancesRenderList(subMesh._id);
  32737. if (batch.mustReturn) {
  32738. return;
  32739. }
  32740. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32741. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32742. engine.enableEffect(_this._volumetricLightScatteringPass);
  32743. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32744. var material = subMesh.getMaterial();
  32745. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32746. // Alpha test
  32747. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32748. var alphaTexture = material.getAlphaTestTexture();
  32749. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32750. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32751. }
  32752. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32753. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32754. if (alphaTexture) {
  32755. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32756. }
  32757. }
  32758. if (material.opacityTexture !== undefined) {
  32759. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32760. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32761. }
  32762. }
  32763. // Bones
  32764. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32765. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32766. }
  32767. // Draw
  32768. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32769. }
  32770. };
  32771. // Render target texture callbacks
  32772. var savedSceneClearColor;
  32773. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32774. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32775. savedSceneClearColor = scene.clearColor;
  32776. scene.clearColor = sceneClearColor;
  32777. };
  32778. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32779. scene.clearColor = savedSceneClearColor;
  32780. };
  32781. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32782. var engine = scene.getEngine();
  32783. var index;
  32784. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32785. renderSubMesh(opaqueSubMeshes.data[index]);
  32786. }
  32787. engine.setAlphaTesting(true);
  32788. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32789. renderSubMesh(alphaTestSubMeshes.data[index]);
  32790. }
  32791. engine.setAlphaTesting(false);
  32792. if (transparentSubMeshes.length) {
  32793. // Sort sub meshes
  32794. for (index = 0; index < transparentSubMeshes.length; index++) {
  32795. var submesh = transparentSubMeshes.data[index];
  32796. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32797. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32798. }
  32799. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32800. sortedArray.sort(function (a, b) {
  32801. // Alpha index first
  32802. if (a._alphaIndex > b._alphaIndex) {
  32803. return 1;
  32804. }
  32805. if (a._alphaIndex < b._alphaIndex) {
  32806. return -1;
  32807. }
  32808. // Then distance to camera
  32809. if (a._distanceToCamera < b._distanceToCamera) {
  32810. return 1;
  32811. }
  32812. if (a._distanceToCamera > b._distanceToCamera) {
  32813. return -1;
  32814. }
  32815. return 0;
  32816. });
  32817. // Render sub meshes
  32818. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32819. for (index = 0; index < sortedArray.length; index++) {
  32820. renderSubMesh(sortedArray[index]);
  32821. }
  32822. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32823. }
  32824. };
  32825. };
  32826. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32827. var transform = scene.getTransformMatrix();
  32828. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32829. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32830. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32831. if (this.invert)
  32832. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32833. };
  32834. // Static methods
  32835. /**
  32836. * Creates a default mesh for the Volumeric Light Scattering post-process
  32837. * @param {string} The mesh name
  32838. * @param {BABYLON.Scene} The scene where to create the mesh
  32839. * @return {BABYLON.Mesh} the default mesh
  32840. */
  32841. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32842. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32843. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32844. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32845. return mesh;
  32846. };
  32847. return VolumetricLightScatteringPostProcess;
  32848. })(BABYLON.PostProcess);
  32849. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32850. })(BABYLON || (BABYLON = {}));
  32851. var BABYLON;
  32852. (function (BABYLON) {
  32853. var LensRenderingPipeline = (function (_super) {
  32854. __extends(LensRenderingPipeline, _super);
  32855. /**
  32856. * @constructor
  32857. *
  32858. * Effect parameters are as follow:
  32859. * {
  32860. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32861. * edge_blur: number; // from 0 to x (1 for realism)
  32862. * distortion: number; // from 0 to x (1 for realism)
  32863. * grain_amount: number; // from 0 to 1
  32864. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32865. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32866. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32867. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32868. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32869. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32870. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32871. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32872. * }
  32873. * Note: if an effect parameter is unset, effect is disabled
  32874. *
  32875. * @param {string} name - The rendering pipeline name
  32876. * @param {object} parameters - An object containing all parameters (see above)
  32877. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32878. * @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)
  32879. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32880. */
  32881. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32882. var _this = this;
  32883. if (ratio === void 0) { ratio = 1.0; }
  32884. _super.call(this, scene.getEngine(), name);
  32885. // Lens effects can be of the following:
  32886. // - chromatic aberration (slight shift of RGB colors)
  32887. // - blur on the edge of the lens
  32888. // - lens distortion
  32889. // - depth-of-field blur & highlights enhancing
  32890. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32891. // - grain effect (noise or custom texture)
  32892. // Two additional texture samplers are needed:
  32893. // - depth map (for depth-of-field)
  32894. // - grain texture
  32895. /**
  32896. * The chromatic aberration PostProcess id in the pipeline
  32897. * @type {string}
  32898. */
  32899. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32900. /**
  32901. * The highlights enhancing PostProcess id in the pipeline
  32902. * @type {string}
  32903. */
  32904. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32905. /**
  32906. * The depth-of-field PostProcess id in the pipeline
  32907. * @type {string}
  32908. */
  32909. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32910. this._scene = scene;
  32911. // Fetch texture samplers
  32912. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32913. if (parameters.grain_texture) {
  32914. this._grainTexture = parameters.grain_texture;
  32915. }
  32916. else {
  32917. this._createGrainTexture();
  32918. }
  32919. // save parameters
  32920. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32921. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32922. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32923. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32924. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32925. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32926. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32927. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32928. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32929. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32930. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32931. // Create effects
  32932. this._createChromaticAberrationPostProcess(ratio);
  32933. this._createHighlightsPostProcess(ratio);
  32934. this._createDepthOfFieldPostProcess(ratio / 4);
  32935. // Set up pipeline
  32936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32937. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32938. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32939. if (this._highlightsGain == -1) {
  32940. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32941. }
  32942. // Finish
  32943. scene.postProcessRenderPipelineManager.addPipeline(this);
  32944. if (cameras) {
  32945. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32946. }
  32947. }
  32948. // public methods (self explanatory)
  32949. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32950. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32951. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32952. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32953. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32954. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32955. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32956. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32957. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32958. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32959. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32960. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32961. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32962. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32963. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32964. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32965. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32966. this._highlightsGain = amount;
  32967. };
  32968. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32969. if (this._highlightsGain == -1) {
  32970. this._highlightsGain = 1.0;
  32971. }
  32972. this._highlightsThreshold = amount;
  32973. };
  32974. LensRenderingPipeline.prototype.disableHighlights = function () {
  32975. this._highlightsGain = -1;
  32976. };
  32977. /**
  32978. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32979. */
  32980. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32981. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32982. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32983. this._chromaticAberrationPostProcess = undefined;
  32984. this._highlightsPostProcess = undefined;
  32985. this._depthOfFieldPostProcess = undefined;
  32986. this._grainTexture.dispose();
  32987. if (disableDepthRender)
  32988. this._scene.disableDepthRenderer();
  32989. };
  32990. // colors shifting and distortion
  32991. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32992. var _this = this;
  32993. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  32994. [], // samplers
  32995. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32996. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32997. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32998. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32999. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33000. };
  33001. };
  33002. // highlights enhancing
  33003. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33004. var _this = this;
  33005. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33006. [], // samplers
  33007. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33008. this._highlightsPostProcess.onApply = function (effect) {
  33009. effect.setFloat('gain', _this._highlightsGain);
  33010. effect.setFloat('threshold', _this._highlightsThreshold);
  33011. effect.setBool('pentagon', _this._dofPentagon);
  33012. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33013. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33014. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33015. };
  33016. };
  33017. // colors shifting and distortion
  33018. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33019. var _this = this;
  33020. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33021. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33022. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33023. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33024. this._depthOfFieldPostProcess.onApply = function (effect) {
  33025. effect.setTexture("depthSampler", _this._depthTexture);
  33026. effect.setTexture("grainSampler", _this._grainTexture);
  33027. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33028. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33029. effect.setFloat('grain_amount', _this._grainAmount);
  33030. effect.setBool('blur_noise', _this._blurNoise);
  33031. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33032. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33033. effect.setFloat('distortion', _this._distortion);
  33034. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33035. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33036. effect.setFloat('aperture', _this._dofAperture);
  33037. effect.setFloat('darken', _this._dofDarken);
  33038. effect.setFloat('edge_blur', _this._edgeBlur);
  33039. effect.setBool('highlights', (_this._highlightsGain != -1));
  33040. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33041. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33042. };
  33043. };
  33044. // creates a black and white random noise texture, 512x512
  33045. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33046. var size = 512;
  33047. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33048. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33049. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33050. var context = this._grainTexture.getContext();
  33051. var rand = function (min, max) {
  33052. return Math.random() * (max - min) + min;
  33053. };
  33054. var value;
  33055. for (var x = 0; x < size; x++) {
  33056. for (var y = 0; y < size; y++) {
  33057. value = Math.floor(rand(0.42, 0.58) * 255);
  33058. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33059. context.fillRect(x, y, 1, 1);
  33060. }
  33061. }
  33062. this._grainTexture.update(false);
  33063. };
  33064. return LensRenderingPipeline;
  33065. })(BABYLON.PostProcessRenderPipeline);
  33066. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33067. })(BABYLON || (BABYLON = {}));
  33068. //
  33069. // This post-process allows the modification of rendered colors by using
  33070. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33071. //
  33072. // The object needs to be provided an url to a texture containing the color
  33073. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33074. // Use an image editing software to tweak the LUT to match your needs.
  33075. //
  33076. // For an example of a color LUT, see here:
  33077. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33078. // For explanations on color grading, see here:
  33079. // http://udn.epicgames.com/Three/ColorGrading.html
  33080. //
  33081. var BABYLON;
  33082. (function (BABYLON) {
  33083. var ColorCorrectionPostProcess = (function (_super) {
  33084. __extends(ColorCorrectionPostProcess, _super);
  33085. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33086. var _this = this;
  33087. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33088. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33089. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33090. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33091. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33092. this.onApply = function (effect) {
  33093. effect.setTexture("colorTable", _this._colorTableTexture);
  33094. };
  33095. }
  33096. return ColorCorrectionPostProcess;
  33097. })(BABYLON.PostProcess);
  33098. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33099. })(BABYLON || (BABYLON = {}));
  33100. var BABYLON;
  33101. (function (BABYLON) {
  33102. var AnaglyphFreeCamera = (function (_super) {
  33103. __extends(AnaglyphFreeCamera, _super);
  33104. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33105. _super.call(this, name, position, scene);
  33106. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33107. }
  33108. return AnaglyphFreeCamera;
  33109. })(BABYLON.FreeCamera);
  33110. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33111. var AnaglyphArcRotateCamera = (function (_super) {
  33112. __extends(AnaglyphArcRotateCamera, _super);
  33113. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33114. _super.call(this, name, alpha, beta, radius, target, scene);
  33115. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33116. }
  33117. return AnaglyphArcRotateCamera;
  33118. })(BABYLON.ArcRotateCamera);
  33119. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33120. var AnaglyphGamepadCamera = (function (_super) {
  33121. __extends(AnaglyphGamepadCamera, _super);
  33122. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33123. _super.call(this, name, position, scene);
  33124. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33125. }
  33126. return AnaglyphGamepadCamera;
  33127. })(BABYLON.GamepadCamera);
  33128. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33129. var StereoscopicFreeCamera = (function (_super) {
  33130. __extends(StereoscopicFreeCamera, _super);
  33131. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33132. _super.call(this, name, position, scene);
  33133. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33134. }
  33135. return StereoscopicFreeCamera;
  33136. })(BABYLON.FreeCamera);
  33137. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33138. var StereoscopicArcRotateCamera = (function (_super) {
  33139. __extends(StereoscopicArcRotateCamera, _super);
  33140. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33141. _super.call(this, name, alpha, beta, radius, target, scene);
  33142. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33143. }
  33144. return StereoscopicArcRotateCamera;
  33145. })(BABYLON.ArcRotateCamera);
  33146. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33147. var StereoscopicGamepadCamera = (function (_super) {
  33148. __extends(StereoscopicGamepadCamera, _super);
  33149. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33150. _super.call(this, name, position, scene);
  33151. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33152. }
  33153. return StereoscopicGamepadCamera;
  33154. })(BABYLON.GamepadCamera);
  33155. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33156. })(BABYLON || (BABYLON = {}));
  33157. var BABYLON;
  33158. (function (BABYLON) {
  33159. var HDRRenderingPipeline = (function (_super) {
  33160. __extends(HDRRenderingPipeline, _super);
  33161. /**
  33162. * @constructor
  33163. * @param {string} name - The rendering pipeline name
  33164. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33165. * @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)
  33166. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33167. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33168. */
  33169. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33170. var _this = this;
  33171. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33172. _super.call(this, scene.getEngine(), name);
  33173. /**
  33174. * Public members
  33175. */
  33176. // Gaussian Blur
  33177. /**
  33178. * Gaussian blur coefficient
  33179. * @type {number}
  33180. */
  33181. this.gaussCoeff = 0.3;
  33182. /**
  33183. * Gaussian blur mean
  33184. * @type {number}
  33185. */
  33186. this.gaussMean = 1.0;
  33187. /**
  33188. * Gaussian blur standard deviation
  33189. * @type {number}
  33190. */
  33191. this.gaussStandDev = 0.8;
  33192. // HDR
  33193. /**
  33194. * Exposure, controls the overall intensity of the pipeline
  33195. * @type {number}
  33196. */
  33197. this.exposure = 1.0;
  33198. /**
  33199. * Minimum luminance that the post-process can output. Luminance is >= 0
  33200. * @type {number}
  33201. */
  33202. this.minimumLuminance = 1.0;
  33203. /**
  33204. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33205. * @type {number}
  33206. */
  33207. this.maximumLuminance = 1e20;
  33208. /**
  33209. * Increase rate for luminance: eye adaptation speed to dark
  33210. * @type {number}
  33211. */
  33212. this.luminanceIncreaserate = 0.5;
  33213. /**
  33214. * Decrease rate for luminance: eye adaptation speed to bright
  33215. * @type {number}
  33216. */
  33217. this.luminanceDecreaseRate = 0.5;
  33218. // Bright pass
  33219. /**
  33220. * Minimum luminance needed to compute HDR
  33221. * @type {number}
  33222. */
  33223. this.brightThreshold = 0.8;
  33224. this._needUpdate = true;
  33225. this._scene = scene;
  33226. // Bright pass
  33227. this._createBrightPassPostProcess(scene, ratio);
  33228. // Down sample X4
  33229. this._createDownSampleX4PostProcess(scene, ratio);
  33230. // Create gaussian blur post-processes
  33231. this._createGaussianBlurPostProcess(scene, ratio);
  33232. // Texture adder
  33233. this._createTextureAdderPostProcess(scene, ratio);
  33234. // Luminance generator
  33235. this._createLuminanceGeneratorPostProcess(scene);
  33236. // HDR
  33237. this._createHDRPostProcess(scene, ratio);
  33238. // Pass postprocess
  33239. if (originalPostProcess === null) {
  33240. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33241. }
  33242. else {
  33243. this._originalPostProcess = originalPostProcess;
  33244. }
  33245. // Configure pipeline
  33246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33250. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33251. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33252. var addDownSamplerPostProcess = function (id) {
  33253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33254. };
  33255. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33256. addDownSamplerPostProcess(i);
  33257. }
  33258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33259. // Finish
  33260. scene.postProcessRenderPipelineManager.addPipeline(this);
  33261. if (cameras !== null) {
  33262. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33263. }
  33264. this.update();
  33265. }
  33266. /**
  33267. * Tells the pipeline to update its post-processes
  33268. */
  33269. HDRRenderingPipeline.prototype.update = function () {
  33270. this._needUpdate = true;
  33271. };
  33272. /**
  33273. * Returns the current calculated luminance
  33274. */
  33275. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33276. return this._hdrCurrentLuminance;
  33277. };
  33278. /**
  33279. * Returns the currently drawn luminance
  33280. */
  33281. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33282. return this._hdrOutputLuminance;
  33283. };
  33284. /**
  33285. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33286. */
  33287. HDRRenderingPipeline.prototype.dispose = function () {
  33288. this._originalPostProcess = undefined;
  33289. this._brightPassPostProcess = undefined;
  33290. this._downSampleX4PostProcess = undefined;
  33291. this._guassianBlurHPostProcess = undefined;
  33292. this._guassianBlurVPostProcess = undefined;
  33293. this._textureAdderPostProcess = undefined;
  33294. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33295. this._downSamplePostProcesses[i] = undefined;
  33296. }
  33297. this._hdrPostProcess = undefined;
  33298. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33299. };
  33300. /**
  33301. * Creates the HDR post-process and computes the luminance adaptation
  33302. */
  33303. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33304. var _this = this;
  33305. var hdrLastLuminance = 0.0;
  33306. this._hdrOutputLuminance = -1.0;
  33307. this._hdrCurrentLuminance = 1.0;
  33308. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33309. this._hdrPostProcess.onApply = function (effect) {
  33310. if (_this._hdrOutputLuminance < 0.0) {
  33311. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33312. }
  33313. else {
  33314. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33315. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33316. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33317. }
  33318. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33319. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33320. }
  33321. else {
  33322. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33323. }
  33324. }
  33325. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33326. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33327. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33328. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33329. effect.setFloat("exposure", _this.exposure);
  33330. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33331. _this._needUpdate = false;
  33332. };
  33333. };
  33334. /**
  33335. * Texture Adder post-process
  33336. */
  33337. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33338. var _this = this;
  33339. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33340. this._textureAdderPostProcess.onApply = function (effect) {
  33341. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33342. };
  33343. };
  33344. /**
  33345. * Down sample X4 post-process
  33346. */
  33347. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33348. var _this = this;
  33349. var downSampleX4Offsets = new Array(32);
  33350. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33351. this._downSampleX4PostProcess.onApply = function (effect) {
  33352. if (_this._needUpdate) {
  33353. var id = 0;
  33354. for (var i = -2; i < 2; i++) {
  33355. for (var j = -2; j < 2; j++) {
  33356. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33357. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33358. id += 2;
  33359. }
  33360. }
  33361. }
  33362. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33363. };
  33364. };
  33365. /**
  33366. * Bright pass post-process
  33367. */
  33368. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33369. var _this = this;
  33370. var brightOffsets = new Array(8);
  33371. var brightPassCallback = function (effect) {
  33372. if (_this._needUpdate) {
  33373. var sU = (1.0 / _this._brightPassPostProcess.width);
  33374. var sV = (1.0 / _this._brightPassPostProcess.height);
  33375. brightOffsets[0] = -0.5 * sU;
  33376. brightOffsets[1] = 0.5 * sV;
  33377. brightOffsets[2] = 0.5 * sU;
  33378. brightOffsets[3] = 0.5 * sV;
  33379. brightOffsets[4] = -0.5 * sU;
  33380. brightOffsets[5] = -0.5 * sV;
  33381. brightOffsets[6] = 0.5 * sU;
  33382. brightOffsets[7] = -0.5 * sV;
  33383. }
  33384. effect.setArray2("dsOffsets", brightOffsets);
  33385. effect.setFloat("brightThreshold", _this.brightThreshold);
  33386. };
  33387. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33388. this._brightPassPostProcess.onApply = brightPassCallback;
  33389. };
  33390. /**
  33391. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33392. */
  33393. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33394. var _this = this;
  33395. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33396. var luminanceOffsets = new Array(8);
  33397. var downSampleOffsets = new Array(18);
  33398. var halfDestPixelSize;
  33399. this._downSamplePostProcesses = new Array(lumSteps);
  33400. // Utils for luminance
  33401. var luminanceUpdateSourceOffsets = function (width, height) {
  33402. var sU = (1.0 / width);
  33403. var sV = (1.0 / height);
  33404. luminanceOffsets[0] = -0.5 * sU;
  33405. luminanceOffsets[1] = 0.5 * sV;
  33406. luminanceOffsets[2] = 0.5 * sU;
  33407. luminanceOffsets[3] = 0.5 * sV;
  33408. luminanceOffsets[4] = -0.5 * sU;
  33409. luminanceOffsets[5] = -0.5 * sV;
  33410. luminanceOffsets[6] = 0.5 * sU;
  33411. luminanceOffsets[7] = -0.5 * sV;
  33412. };
  33413. var luminanceUpdateDestOffsets = function (width, height) {
  33414. var id = 0;
  33415. for (var x = -1; x < 2; x++) {
  33416. for (var y = -1; y < 2; y++) {
  33417. downSampleOffsets[id] = (x) / width;
  33418. downSampleOffsets[id + 1] = (y) / height;
  33419. id += 2;
  33420. }
  33421. }
  33422. };
  33423. // Luminance callback
  33424. var luminanceCallback = function (effect) {
  33425. if (_this._needUpdate) {
  33426. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33427. }
  33428. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33429. effect.setArray2("lumOffsets", luminanceOffsets);
  33430. };
  33431. // Down sample callbacks
  33432. var downSampleCallback = function (indice) {
  33433. var i = indice;
  33434. return function (effect) {
  33435. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33436. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33437. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33438. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33439. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33440. effect.setArray2("dsOffsets", downSampleOffsets);
  33441. };
  33442. };
  33443. var downSampleAfterRenderCallback = function (effect) {
  33444. // Unpack result
  33445. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33446. 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);
  33447. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33448. };
  33449. // Create luminance post-process
  33450. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33451. 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);
  33452. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33453. // Create down sample post-processes
  33454. for (var i = lumSteps - 2; i >= 0; i--) {
  33455. var length = Math.pow(3, i);
  33456. ratio = { width: length, height: length };
  33457. var defines = "#define DOWN_SAMPLE\n";
  33458. if (i === 0) {
  33459. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33460. }
  33461. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33462. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33463. if (i === 0) {
  33464. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33465. }
  33466. }
  33467. };
  33468. /**
  33469. * Gaussian blur post-processes. Horizontal and Vertical
  33470. */
  33471. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33472. var _this = this;
  33473. var blurOffsetsW = new Array(9);
  33474. var blurOffsetsH = new Array(9);
  33475. var blurWeights = new Array(9);
  33476. var uniforms = ["blurOffsets", "blurWeights"];
  33477. // Utils for gaussian blur
  33478. var calculateBlurOffsets = function (height) {
  33479. var lastOutputDimensions = {
  33480. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33481. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33482. };
  33483. for (var i = 0; i < 9; i++) {
  33484. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33485. if (height) {
  33486. blurOffsetsH[i] = value;
  33487. }
  33488. else {
  33489. blurOffsetsW[i] = value;
  33490. }
  33491. }
  33492. };
  33493. var calculateWeights = function () {
  33494. var x = 0.0;
  33495. for (var i = 0; i < 9; i++) {
  33496. x = (i - 4.0) / 4.0;
  33497. 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));
  33498. }
  33499. };
  33500. // Callback
  33501. var gaussianBlurCallback = function (height) {
  33502. return function (effect) {
  33503. if (_this._needUpdate) {
  33504. calculateWeights();
  33505. calculateBlurOffsets(height);
  33506. }
  33507. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33508. effect.setArray("blurWeights", blurWeights);
  33509. };
  33510. };
  33511. // Create horizontal gaussian blur post-processes
  33512. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33513. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33514. // Create vertical gaussian blur post-process
  33515. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33516. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33517. };
  33518. // Luminance generator
  33519. HDRRenderingPipeline.LUM_STEPS = 6;
  33520. return HDRRenderingPipeline;
  33521. })(BABYLON.PostProcessRenderPipeline);
  33522. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33523. })(BABYLON || (BABYLON = {}));
  33524. var BABYLON;
  33525. (function (BABYLON) {
  33526. var FaceAdjacencies = (function () {
  33527. function FaceAdjacencies() {
  33528. this.edges = new Array();
  33529. this.edgesConnectedCount = 0;
  33530. }
  33531. return FaceAdjacencies;
  33532. })();
  33533. var EdgesRenderer = (function () {
  33534. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33535. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33536. if (epsilon === void 0) { epsilon = 0.95; }
  33537. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33538. this._linesPositions = new Array();
  33539. this._linesNormals = new Array();
  33540. this._linesIndices = new Array();
  33541. this._buffers = new Array();
  33542. this._checkVerticesInsteadOfIndices = false;
  33543. this._source = source;
  33544. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33545. this._epsilon = epsilon;
  33546. this._prepareRessources();
  33547. this._generateEdgesLines();
  33548. }
  33549. EdgesRenderer.prototype._prepareRessources = function () {
  33550. if (this._lineShader) {
  33551. return;
  33552. }
  33553. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33554. attributes: ["position", "normal"],
  33555. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33556. });
  33557. this._lineShader.disableDepthWrite = true;
  33558. this._lineShader.backFaceCulling = false;
  33559. };
  33560. EdgesRenderer.prototype.dispose = function () {
  33561. this._vb0.dispose();
  33562. this._vb1.dispose();
  33563. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33564. this._lineShader.dispose();
  33565. };
  33566. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33567. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33568. return 0;
  33569. }
  33570. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33571. return 1;
  33572. }
  33573. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33574. return 2;
  33575. }
  33576. return -1;
  33577. };
  33578. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33579. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33580. return 0;
  33581. }
  33582. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33583. return 1;
  33584. }
  33585. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33586. return 2;
  33587. }
  33588. return -1;
  33589. };
  33590. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33591. var needToCreateLine;
  33592. if (edge === undefined) {
  33593. needToCreateLine = true;
  33594. }
  33595. else {
  33596. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33597. needToCreateLine = dotProduct < this._epsilon;
  33598. }
  33599. if (needToCreateLine) {
  33600. var offset = this._linesPositions.length / 3;
  33601. var normal = p0.subtract(p1);
  33602. normal.normalize();
  33603. // Positions
  33604. this._linesPositions.push(p0.x);
  33605. this._linesPositions.push(p0.y);
  33606. this._linesPositions.push(p0.z);
  33607. this._linesPositions.push(p0.x);
  33608. this._linesPositions.push(p0.y);
  33609. this._linesPositions.push(p0.z);
  33610. this._linesPositions.push(p1.x);
  33611. this._linesPositions.push(p1.y);
  33612. this._linesPositions.push(p1.z);
  33613. this._linesPositions.push(p1.x);
  33614. this._linesPositions.push(p1.y);
  33615. this._linesPositions.push(p1.z);
  33616. // Normals
  33617. this._linesNormals.push(p1.x);
  33618. this._linesNormals.push(p1.y);
  33619. this._linesNormals.push(p1.z);
  33620. this._linesNormals.push(-1);
  33621. this._linesNormals.push(p1.x);
  33622. this._linesNormals.push(p1.y);
  33623. this._linesNormals.push(p1.z);
  33624. this._linesNormals.push(1);
  33625. this._linesNormals.push(p0.x);
  33626. this._linesNormals.push(p0.y);
  33627. this._linesNormals.push(p0.z);
  33628. this._linesNormals.push(-1);
  33629. this._linesNormals.push(p0.x);
  33630. this._linesNormals.push(p0.y);
  33631. this._linesNormals.push(p0.z);
  33632. this._linesNormals.push(1);
  33633. // Indices
  33634. this._linesIndices.push(offset);
  33635. this._linesIndices.push(offset + 1);
  33636. this._linesIndices.push(offset + 2);
  33637. this._linesIndices.push(offset);
  33638. this._linesIndices.push(offset + 2);
  33639. this._linesIndices.push(offset + 3);
  33640. }
  33641. };
  33642. EdgesRenderer.prototype._generateEdgesLines = function () {
  33643. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33644. var indices = this._source.getIndices();
  33645. // First let's find adjacencies
  33646. var adjacencies = new Array();
  33647. var faceNormals = new Array();
  33648. var index;
  33649. var faceAdjacencies;
  33650. // Prepare faces
  33651. for (index = 0; index < indices.length; index += 3) {
  33652. faceAdjacencies = new FaceAdjacencies();
  33653. var p0Index = indices[index];
  33654. var p1Index = indices[index + 1];
  33655. var p2Index = indices[index + 2];
  33656. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33657. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33658. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33659. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33660. faceNormal.normalize();
  33661. faceNormals.push(faceNormal);
  33662. adjacencies.push(faceAdjacencies);
  33663. }
  33664. // Scan
  33665. for (index = 0; index < adjacencies.length; index++) {
  33666. faceAdjacencies = adjacencies[index];
  33667. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33668. var otherFaceAdjacencies = adjacencies[otherIndex];
  33669. if (faceAdjacencies.edgesConnectedCount === 3) {
  33670. break;
  33671. }
  33672. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33673. continue;
  33674. }
  33675. var otherP0 = indices[otherIndex * 3];
  33676. var otherP1 = indices[otherIndex * 3 + 1];
  33677. var otherP2 = indices[otherIndex * 3 + 2];
  33678. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33679. var otherEdgeIndex;
  33680. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33681. continue;
  33682. }
  33683. switch (edgeIndex) {
  33684. case 0:
  33685. if (this._checkVerticesInsteadOfIndices) {
  33686. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33687. }
  33688. else {
  33689. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33690. }
  33691. break;
  33692. case 1:
  33693. if (this._checkVerticesInsteadOfIndices) {
  33694. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33695. }
  33696. else {
  33697. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33698. }
  33699. break;
  33700. case 2:
  33701. if (this._checkVerticesInsteadOfIndices) {
  33702. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33703. }
  33704. else {
  33705. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33706. }
  33707. break;
  33708. }
  33709. if (otherEdgeIndex === -1) {
  33710. continue;
  33711. }
  33712. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33713. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33714. faceAdjacencies.edgesConnectedCount++;
  33715. otherFaceAdjacencies.edgesConnectedCount++;
  33716. if (faceAdjacencies.edgesConnectedCount === 3) {
  33717. break;
  33718. }
  33719. }
  33720. }
  33721. }
  33722. // Create lines
  33723. for (index = 0; index < adjacencies.length; index++) {
  33724. // 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
  33725. var current = adjacencies[index];
  33726. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33727. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33728. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33729. }
  33730. // Merge into a single mesh
  33731. var engine = this._source.getScene().getEngine();
  33732. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33733. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33734. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33735. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33736. this._ib = engine.createIndexBuffer(this._linesIndices);
  33737. this._indicesCount = this._linesIndices.length;
  33738. };
  33739. EdgesRenderer.prototype.render = function () {
  33740. if (!this._lineShader.isReady()) {
  33741. return;
  33742. }
  33743. var scene = this._source.getScene();
  33744. var engine = scene.getEngine();
  33745. this._lineShader._preBind();
  33746. // VBOs
  33747. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33748. scene.resetCachedMaterial();
  33749. this._lineShader.setColor4("color", this._source.edgesColor);
  33750. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33751. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33752. this._lineShader.bind(this._source.getWorldMatrix());
  33753. // Draw order
  33754. engine.draw(true, 0, this._indicesCount);
  33755. this._lineShader.unbind();
  33756. engine.setDepthWrite(true);
  33757. };
  33758. return EdgesRenderer;
  33759. })();
  33760. BABYLON.EdgesRenderer = EdgesRenderer;
  33761. })(BABYLON || (BABYLON = {}));
  33762. var BABYLON;
  33763. (function (BABYLON) {
  33764. (function (TonemappingOperator) {
  33765. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  33766. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  33767. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  33768. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  33769. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  33770. var TonemappingOperator = BABYLON.TonemappingOperator;
  33771. ;
  33772. var TonemapPostProcess = (function (_super) {
  33773. __extends(TonemapPostProcess, _super);
  33774. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  33775. var _this = this;
  33776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33777. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33778. this._operator = operator;
  33779. this._exposureAdjustment = exposureAdjustment;
  33780. var params = ["_ExposureAdjustment"];
  33781. var defines = "#define ";
  33782. if (operator === TonemappingOperator.Hable)
  33783. defines += "HABLE_TONEMAPPING";
  33784. else if (operator === TonemappingOperator.Reinhard)
  33785. defines += "REINHARD_TONEMAPPING";
  33786. else if (operator === TonemappingOperator.HejiDawson)
  33787. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  33788. else if (operator === TonemappingOperator.Photographic)
  33789. defines += "PHOTOGRAPHIC_TONEMAPPING";
  33790. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  33791. this.onApply = function (effect) {
  33792. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  33793. };
  33794. }
  33795. return TonemapPostProcess;
  33796. })(BABYLON.PostProcess);
  33797. BABYLON.TonemapPostProcess = TonemapPostProcess;
  33798. })(BABYLON || (BABYLON = {}));
  33799. var BABYLON;
  33800. (function (BABYLON) {
  33801. var DefaultLoadingScreen = (function () {
  33802. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33803. var _this = this;
  33804. if (_loadingText === void 0) { _loadingText = ""; }
  33805. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33806. this._renderingCanvas = _renderingCanvas;
  33807. this._loadingText = _loadingText;
  33808. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33809. // Resize
  33810. this._resizeLoadingUI = function () {
  33811. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33812. _this._loadingDiv.style.position = "absolute";
  33813. _this._loadingDiv.style.left = canvasRect.left + "px";
  33814. _this._loadingDiv.style.top = canvasRect.top + "px";
  33815. _this._loadingDiv.style.width = canvasRect.width + "px";
  33816. _this._loadingDiv.style.height = canvasRect.height + "px";
  33817. };
  33818. }
  33819. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33820. var _this = this;
  33821. this._loadingDiv = document.createElement("div");
  33822. this._loadingDiv.style.opacity = "0";
  33823. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33824. // Loading text
  33825. this._loadingTextDiv = document.createElement("div");
  33826. this._loadingTextDiv.style.position = "absolute";
  33827. this._loadingTextDiv.style.left = "0";
  33828. this._loadingTextDiv.style.top = "50%";
  33829. this._loadingTextDiv.style.marginTop = "80px";
  33830. this._loadingTextDiv.style.width = "100%";
  33831. this._loadingTextDiv.style.height = "20px";
  33832. this._loadingTextDiv.style.fontFamily = "Arial";
  33833. this._loadingTextDiv.style.fontSize = "14px";
  33834. this._loadingTextDiv.style.color = "white";
  33835. this._loadingTextDiv.style.textAlign = "center";
  33836. this._loadingTextDiv.innerHTML = "Loading";
  33837. this._loadingDiv.appendChild(this._loadingTextDiv);
  33838. //set the predefined text
  33839. this._loadingTextDiv.innerHTML = this._loadingText;
  33840. // Loading img
  33841. var imgBack = new Image();
  33842. 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==";
  33843. imgBack.style.position = "absolute";
  33844. imgBack.style.left = "50%";
  33845. imgBack.style.top = "50%";
  33846. imgBack.style.marginLeft = "-50px";
  33847. imgBack.style.marginTop = "-50px";
  33848. imgBack.style.transition = "transform 1.0s ease";
  33849. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33850. var deg = 360;
  33851. var onTransitionEnd = function () {
  33852. deg += 360;
  33853. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33854. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33855. };
  33856. imgBack.addEventListener("transitionend", onTransitionEnd);
  33857. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33858. this._loadingDiv.appendChild(imgBack);
  33859. // front image
  33860. var imgFront = new Image();
  33861. 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=";
  33862. imgFront.style.position = "absolute";
  33863. imgFront.style.left = "50%";
  33864. imgFront.style.top = "50%";
  33865. imgFront.style.marginLeft = "-50px";
  33866. imgFront.style.marginTop = "-50px";
  33867. this._loadingDiv.appendChild(imgFront);
  33868. this._resizeLoadingUI();
  33869. window.addEventListener("resize", this._resizeLoadingUI);
  33870. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33871. document.body.appendChild(this._loadingDiv);
  33872. setTimeout(function () {
  33873. _this._loadingDiv.style.opacity = "1";
  33874. imgBack.style.transform = "rotateZ(360deg)";
  33875. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33876. }, 0);
  33877. };
  33878. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33879. var _this = this;
  33880. if (!this._loadingDiv) {
  33881. return;
  33882. }
  33883. var onTransitionEnd = function () {
  33884. if (!_this._loadingDiv) {
  33885. return;
  33886. }
  33887. document.body.removeChild(_this._loadingDiv);
  33888. window.removeEventListener("resize", _this._resizeLoadingUI);
  33889. _this._loadingDiv = null;
  33890. };
  33891. this._loadingDiv.style.opacity = "0";
  33892. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33893. };
  33894. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33895. set: function (text) {
  33896. this._loadingText = text;
  33897. if (this._loadingTextDiv) {
  33898. this._loadingTextDiv.innerHTML = this._loadingText;
  33899. }
  33900. },
  33901. enumerable: true,
  33902. configurable: true
  33903. });
  33904. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33905. get: function () {
  33906. return this._loadingDivBackgroundColor;
  33907. },
  33908. set: function (color) {
  33909. this._loadingDivBackgroundColor = color;
  33910. if (!this._loadingDiv) {
  33911. return;
  33912. }
  33913. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33914. },
  33915. enumerable: true,
  33916. configurable: true
  33917. });
  33918. return DefaultLoadingScreen;
  33919. })();
  33920. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33921. })(BABYLON || (BABYLON = {}));
  33922. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += vec3(lightmapIllum, lightmapIllum, lightmapIllum);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapIllum;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  33923. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r=i.Zero();return i.RotationFromAxisToRef(t,o,n,r),r},i.RotationFromAxisToRef=function(o,n,r,s){var e,a,h,u=i.Normalize(o),l=i.Normalize(r),m=f.X,x=f.Y,y=0,c=0,p=0,z=0,M=0,w=0,d=0,I=-1,D=0,S=0;t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?w=1:t.Tools.WithinEpsilon(l.x,0,t.Engine.Epsilon)?z=1:(d=l.z/l.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),a=new i(z,M,w),a.normalize(),h=i.Cross(l,a),h.normalize(),e=i.Cross(u,a),e.normalize(),i.Dot(l,e)<0&&(I=1),S=i.Dot(u,a),S=Math.min(1,Math.max(-1,S)),p=Math.acos(S)*I,i.Dot(a,m)<0&&(p=Math.PI+p,a=a.scaleInPlace(-1),h=h.scaleInPlace(-1),D++);var v,g;z=0,M=0,w=0,I=-1,t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?z=1:(d=a.z/a.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),v=new i(z,M,w),v.normalize(),g=i.Cross(v,a),g.normalize(),e=i.Cross(l,v),e.normalize(),i.Dot(a,e)<0&&(I=1),S=i.Dot(l,v),S=Math.min(1,Math.max(-1,S)),c=Math.acos(S)*I,i.Dot(g,x)<0&&(c=Math.PI+c,g=g.scaleInPlace(-1),v=v.scaleInPlace(-1),D++),I=-1,e=i.Cross(m,a),e.normalize(),i.Dot(e,x)<0&&(I=1),S=i.Dot(a,m),S=Math.min(1,Math.max(-1,S)),y=-Math.acos(S)*I,0>S&&2>D&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return i.normalize(),n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i,o){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=o||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._raw||this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  33924. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33925. module.exports = BABYLON;
  33926. };