babylon.max.js 1.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166
  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.TransformNormal = function (vector, transformation) {
  680. var result = Vector3.Zero();
  681. Vector3.TransformNormalToRef(vector, transformation, result);
  682. return result;
  683. };
  684. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  685. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  686. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  687. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  688. };
  689. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  690. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  691. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  692. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  693. };
  694. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  695. var squared = amount * amount;
  696. var cubed = amount * squared;
  697. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  698. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  699. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  700. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  701. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  702. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  703. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  704. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  705. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Clamp = function (value, min, max) {
  709. var x = value.x;
  710. x = (x > max.x) ? max.x : x;
  711. x = (x < min.x) ? min.x : x;
  712. var y = value.y;
  713. y = (y > max.y) ? max.y : y;
  714. y = (y < min.y) ? min.y : y;
  715. var z = value.z;
  716. z = (z > max.z) ? max.z : z;
  717. z = (z < min.z) ? min.z : z;
  718. return new Vector3(x, y, z);
  719. };
  720. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  721. var squared = amount * amount;
  722. var cubed = amount * squared;
  723. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  724. var part2 = (-2.0 * cubed) + (3.0 * squared);
  725. var part3 = (cubed - (2.0 * squared)) + amount;
  726. var part4 = cubed - squared;
  727. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  728. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  729. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Lerp = function (start, end, amount) {
  733. var x = start.x + ((end.x - start.x) * amount);
  734. var y = start.y + ((end.y - start.y) * amount);
  735. var z = start.z + ((end.z - start.z) * amount);
  736. return new Vector3(x, y, z);
  737. };
  738. Vector3.Dot = function (left, right) {
  739. return (left.x * right.x + left.y * right.y + left.z * right.z);
  740. };
  741. Vector3.Cross = function (left, right) {
  742. var result = Vector3.Zero();
  743. Vector3.CrossToRef(left, right, result);
  744. return result;
  745. };
  746. Vector3.CrossToRef = function (left, right, result) {
  747. result.x = left.y * right.z - left.z * right.y;
  748. result.y = left.z * right.x - left.x * right.z;
  749. result.z = left.x * right.y - left.y * right.x;
  750. };
  751. Vector3.Normalize = function (vector) {
  752. var result = Vector3.Zero();
  753. Vector3.NormalizeToRef(vector, result);
  754. return result;
  755. };
  756. Vector3.NormalizeToRef = function (vector, result) {
  757. result.copyFrom(vector);
  758. result.normalize();
  759. };
  760. Vector3.Project = function (vector, world, transform, viewport) {
  761. var cw = viewport.width;
  762. var ch = viewport.height;
  763. var cx = viewport.x;
  764. var cy = viewport.y;
  765. 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);
  766. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  767. return Vector3.TransformCoordinates(vector, finalMatrix);
  768. };
  769. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  770. var matrix = world.multiply(transform);
  771. matrix.invert();
  772. source.x = source.x / viewportWidth * 2 - 1;
  773. source.y = -(source.y / viewportHeight * 2 - 1);
  774. var vector = Vector3.TransformCoordinates(source, matrix);
  775. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  776. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  777. vector = vector.scale(1.0 / num);
  778. }
  779. return vector;
  780. };
  781. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  782. var matrix = world.multiply(view).multiply(projection);
  783. matrix.invert();
  784. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  785. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  786. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  787. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  788. vector = vector.scale(1.0 / num);
  789. }
  790. return vector;
  791. };
  792. Vector3.Minimize = function (left, right) {
  793. var min = left.clone();
  794. min.MinimizeInPlace(right);
  795. return min;
  796. };
  797. Vector3.Maximize = function (left, right) {
  798. var max = left.clone();
  799. max.MaximizeInPlace(right);
  800. return max;
  801. };
  802. Vector3.Distance = function (value1, value2) {
  803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  804. };
  805. Vector3.DistanceSquared = function (value1, value2) {
  806. var x = value1.x - value2.x;
  807. var y = value1.y - value2.y;
  808. var z = value1.z - value2.z;
  809. return (x * x) + (y * y) + (z * z);
  810. };
  811. Vector3.Center = function (value1, value2) {
  812. var center = value1.add(value2);
  813. center.scaleInPlace(0.5);
  814. return center;
  815. };
  816. /**
  817. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  819. * to something in order to rotate it from its local system to the given target system.
  820. */
  821. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  822. var rotation = Vector3.Zero();
  823. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  824. return rotation;
  825. };
  826. /**
  827. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  828. */
  829. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  830. var u = Vector3.Normalize(axis1);
  831. var w = Vector3.Normalize(axis3);
  832. // world axis
  833. var X = Axis.X;
  834. var Y = Axis.Y;
  835. // equation unknowns and vars
  836. var yaw = 0.0;
  837. var pitch = 0.0;
  838. var roll = 0.0;
  839. var x = 0.0;
  840. var y = 0.0;
  841. var z = 0.0;
  842. var t = 0.0;
  843. var sign = -1.0;
  844. var nbRevert = 0;
  845. var cross;
  846. var dot = 0.0;
  847. // step 1 : rotation around w
  848. // Rv3(u) = u1, and u1 belongs to plane xOz
  849. // Rv3(w) = w1 = w invariant
  850. var u1;
  851. var v1;
  852. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  853. z = 1.0;
  854. }
  855. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  856. x = 1.0;
  857. }
  858. else {
  859. t = w.z / w.x;
  860. x = -t * Math.sqrt(1 / (1 + t * t));
  861. z = Math.sqrt(1 / (1 + t * t));
  862. }
  863. u1 = new Vector3(x, y, z);
  864. u1.normalize();
  865. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  866. v1.normalize();
  867. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  868. cross.normalize();
  869. if (Vector3.Dot(w, cross) < 0) {
  870. sign = 1.0;
  871. }
  872. dot = Vector3.Dot(u, u1);
  873. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  874. roll = Math.acos(dot) * sign;
  875. if (Vector3.Dot(u1, X) < 0) {
  876. roll = Math.PI + roll;
  877. u1 = u1.scaleInPlace(-1);
  878. v1 = v1.scaleInPlace(-1);
  879. nbRevert++;
  880. }
  881. // step 2 : rotate around u1
  882. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  883. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  884. var w2;
  885. var v2;
  886. x = 0.0;
  887. y = 0.0;
  888. z = 0.0;
  889. sign = -1;
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. x = 1.0;
  892. }
  893. else {
  894. t = u1.z / u1.x;
  895. x = -t * Math.sqrt(1 / (1 + t * t));
  896. z = Math.sqrt(1 / (1 + t * t));
  897. }
  898. w2 = new Vector3(x, y, z);
  899. w2.normalize();
  900. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  901. v2.normalize();
  902. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  903. cross.normalize();
  904. if (Vector3.Dot(u1, cross) < 0) {
  905. sign = 1.0;
  906. }
  907. dot = Vector3.Dot(w, w2);
  908. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  909. pitch = Math.acos(dot) * sign;
  910. if (Vector3.Dot(v2, Y) < 0) {
  911. pitch = Math.PI + pitch;
  912. v2 = v2.scaleInPlace(-1);
  913. w2 = w2.scaleInPlace(-1);
  914. nbRevert++;
  915. }
  916. // step 3 : rotate around v2
  917. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  918. sign = -1;
  919. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  920. cross.normalize();
  921. if (Vector3.Dot(cross, Y) < 0) {
  922. sign = 1.0;
  923. }
  924. dot = Vector3.Dot(u1, X);
  925. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  926. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  927. if (dot < 0 && nbRevert < 2) {
  928. yaw = Math.PI + yaw;
  929. }
  930. ref.x = pitch;
  931. ref.y = yaw;
  932. ref.z = roll;
  933. };
  934. return Vector3;
  935. })();
  936. BABYLON.Vector3 = Vector3;
  937. //Vector4 class created for EulerAngle class conversion to Quaternion
  938. var Vector4 = (function () {
  939. function Vector4(x, y, z, w) {
  940. this.x = x;
  941. this.y = y;
  942. this.z = z;
  943. this.w = w;
  944. }
  945. Vector4.prototype.toString = function () {
  946. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  947. };
  948. // Operators
  949. Vector4.prototype.asArray = function () {
  950. var result = [];
  951. this.toArray(result, 0);
  952. return result;
  953. };
  954. Vector4.prototype.toArray = function (array, index) {
  955. if (index === undefined) {
  956. index = 0;
  957. }
  958. array[index] = this.x;
  959. array[index + 1] = this.y;
  960. array[index + 2] = this.z;
  961. array[index + 3] = this.w;
  962. return this;
  963. };
  964. Vector4.prototype.addInPlace = function (otherVector) {
  965. this.x += otherVector.x;
  966. this.y += otherVector.y;
  967. this.z += otherVector.z;
  968. this.w += otherVector.w;
  969. return this;
  970. };
  971. Vector4.prototype.add = function (otherVector) {
  972. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  973. };
  974. Vector4.prototype.addToRef = function (otherVector, result) {
  975. result.x = this.x + otherVector.x;
  976. result.y = this.y + otherVector.y;
  977. result.z = this.z + otherVector.z;
  978. result.w = this.w + otherVector.w;
  979. return this;
  980. };
  981. Vector4.prototype.subtractInPlace = function (otherVector) {
  982. this.x -= otherVector.x;
  983. this.y -= otherVector.y;
  984. this.z -= otherVector.z;
  985. this.w -= otherVector.w;
  986. return this;
  987. };
  988. Vector4.prototype.subtract = function (otherVector) {
  989. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  990. };
  991. Vector4.prototype.subtractToRef = function (otherVector, result) {
  992. result.x = this.x - otherVector.x;
  993. result.y = this.y - otherVector.y;
  994. result.z = this.z - otherVector.z;
  995. result.w = this.w - otherVector.w;
  996. return this;
  997. };
  998. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  999. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1000. };
  1001. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = this.x - x;
  1003. result.y = this.y - y;
  1004. result.z = this.z - z;
  1005. result.w = this.w - w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.negate = function () {
  1009. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1010. };
  1011. Vector4.prototype.scaleInPlace = function (scale) {
  1012. this.x *= scale;
  1013. this.y *= scale;
  1014. this.z *= scale;
  1015. this.w *= scale;
  1016. return this;
  1017. };
  1018. Vector4.prototype.scale = function (scale) {
  1019. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1020. };
  1021. Vector4.prototype.scaleToRef = function (scale, result) {
  1022. result.x = this.x * scale;
  1023. result.y = this.y * scale;
  1024. result.z = this.z * scale;
  1025. result.w = this.w * scale;
  1026. };
  1027. Vector4.prototype.equals = function (otherVector) {
  1028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1029. };
  1030. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1031. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1032. return otherVector
  1033. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1034. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1035. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1036. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1037. };
  1038. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1039. return this.x === x && this.y === y && this.z === z && this.w === w;
  1040. };
  1041. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1042. this.x *= otherVector.x;
  1043. this.y *= otherVector.y;
  1044. this.z *= otherVector.z;
  1045. this.w *= otherVector.w;
  1046. return this;
  1047. };
  1048. Vector4.prototype.multiply = function (otherVector) {
  1049. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1050. };
  1051. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1052. result.x = this.x * otherVector.x;
  1053. result.y = this.y * otherVector.y;
  1054. result.z = this.z * otherVector.z;
  1055. result.w = this.w * otherVector.w;
  1056. return this;
  1057. };
  1058. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1059. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1060. };
  1061. Vector4.prototype.divide = function (otherVector) {
  1062. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1063. };
  1064. Vector4.prototype.divideToRef = function (otherVector, result) {
  1065. result.x = this.x / otherVector.x;
  1066. result.y = this.y / otherVector.y;
  1067. result.z = this.z / otherVector.z;
  1068. result.w = this.w / otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.MinimizeInPlace = function (other) {
  1072. if (other.x < this.x)
  1073. this.x = other.x;
  1074. if (other.y < this.y)
  1075. this.y = other.y;
  1076. if (other.z < this.z)
  1077. this.z = other.z;
  1078. if (other.w < this.w)
  1079. this.w = other.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.MaximizeInPlace = function (other) {
  1083. if (other.x > this.x)
  1084. this.x = other.x;
  1085. if (other.y > this.y)
  1086. this.y = other.y;
  1087. if (other.z > this.z)
  1088. this.z = other.z;
  1089. if (other.w > this.w)
  1090. this.w = other.w;
  1091. return this;
  1092. };
  1093. // Properties
  1094. Vector4.prototype.length = function () {
  1095. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1096. };
  1097. Vector4.prototype.lengthSquared = function () {
  1098. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1099. };
  1100. // Methods
  1101. Vector4.prototype.normalize = function () {
  1102. var len = this.length();
  1103. if (len === 0)
  1104. return this;
  1105. var num = 1.0 / len;
  1106. this.x *= num;
  1107. this.y *= num;
  1108. this.z *= num;
  1109. this.w *= num;
  1110. return this;
  1111. };
  1112. Vector4.prototype.clone = function () {
  1113. return new Vector4(this.x, this.y, this.z, this.w);
  1114. };
  1115. Vector4.prototype.copyFrom = function (source) {
  1116. this.x = source.x;
  1117. this.y = source.y;
  1118. this.z = source.z;
  1119. this.w = source.w;
  1120. return this;
  1121. };
  1122. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1123. this.x = x;
  1124. this.y = y;
  1125. this.z = z;
  1126. this.w = w;
  1127. return this;
  1128. };
  1129. // Statics
  1130. Vector4.FromArray = function (array, offset) {
  1131. if (!offset) {
  1132. offset = 0;
  1133. }
  1134. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1135. };
  1136. Vector4.FromArrayToRef = function (array, offset, result) {
  1137. result.x = array[offset];
  1138. result.y = array[offset + 1];
  1139. result.z = array[offset + 2];
  1140. result.w = array[offset + 3];
  1141. };
  1142. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1143. result.x = array[offset];
  1144. result.y = array[offset + 1];
  1145. result.z = array[offset + 2];
  1146. result.w = array[offset + 3];
  1147. };
  1148. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1149. result.x = x;
  1150. result.y = y;
  1151. result.z = z;
  1152. result.w = w;
  1153. };
  1154. Vector4.Zero = function () {
  1155. return new Vector4(0, 0, 0, 0);
  1156. };
  1157. Vector4.Normalize = function (vector) {
  1158. var result = Vector4.Zero();
  1159. Vector4.NormalizeToRef(vector, result);
  1160. return result;
  1161. };
  1162. Vector4.NormalizeToRef = function (vector, result) {
  1163. result.copyFrom(vector);
  1164. result.normalize();
  1165. };
  1166. Vector4.Minimize = function (left, right) {
  1167. var min = left.clone();
  1168. min.MinimizeInPlace(right);
  1169. return min;
  1170. };
  1171. Vector4.Maximize = function (left, right) {
  1172. var max = left.clone();
  1173. max.MaximizeInPlace(right);
  1174. return max;
  1175. };
  1176. Vector4.Distance = function (value1, value2) {
  1177. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1178. };
  1179. Vector4.DistanceSquared = function (value1, value2) {
  1180. var x = value1.x - value2.x;
  1181. var y = value1.y - value2.y;
  1182. var z = value1.z - value2.z;
  1183. var w = value1.w - value2.w;
  1184. return (x * x) + (y * y) + (z * z) + (w * w);
  1185. };
  1186. Vector4.Center = function (value1, value2) {
  1187. var center = value1.add(value2);
  1188. center.scaleInPlace(0.5);
  1189. return center;
  1190. };
  1191. return Vector4;
  1192. })();
  1193. BABYLON.Vector4 = Vector4;
  1194. var Quaternion = (function () {
  1195. function Quaternion(x, y, z, w) {
  1196. if (x === void 0) { x = 0; }
  1197. if (y === void 0) { y = 0; }
  1198. if (z === void 0) { z = 0; }
  1199. if (w === void 0) { w = 1; }
  1200. this.x = x;
  1201. this.y = y;
  1202. this.z = z;
  1203. this.w = w;
  1204. }
  1205. Quaternion.prototype.toString = function () {
  1206. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1207. };
  1208. Quaternion.prototype.asArray = function () {
  1209. return [this.x, this.y, this.z, this.w];
  1210. };
  1211. Quaternion.prototype.equals = function (otherQuaternion) {
  1212. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1213. };
  1214. Quaternion.prototype.clone = function () {
  1215. return new Quaternion(this.x, this.y, this.z, this.w);
  1216. };
  1217. Quaternion.prototype.copyFrom = function (other) {
  1218. this.x = other.x;
  1219. this.y = other.y;
  1220. this.z = other.z;
  1221. this.w = other.w;
  1222. return this;
  1223. };
  1224. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1225. this.x = x;
  1226. this.y = y;
  1227. this.z = z;
  1228. this.w = w;
  1229. return this;
  1230. };
  1231. Quaternion.prototype.add = function (other) {
  1232. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1233. };
  1234. Quaternion.prototype.subtract = function (other) {
  1235. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1236. };
  1237. Quaternion.prototype.scale = function (value) {
  1238. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1239. };
  1240. Quaternion.prototype.multiply = function (q1) {
  1241. var result = new Quaternion(0, 0, 0, 1.0);
  1242. this.multiplyToRef(q1, result);
  1243. return result;
  1244. };
  1245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1250. result.copyFromFloats(x, y, z, w);
  1251. return this;
  1252. };
  1253. Quaternion.prototype.length = function () {
  1254. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1255. };
  1256. Quaternion.prototype.normalize = function () {
  1257. var length = 1.0 / this.length();
  1258. this.x *= length;
  1259. this.y *= length;
  1260. this.z *= length;
  1261. this.w *= length;
  1262. return this;
  1263. };
  1264. Quaternion.prototype.toEulerAngles = function () {
  1265. var result = Vector3.Zero();
  1266. this.toEulerAnglesToRef(result);
  1267. return result;
  1268. };
  1269. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1270. //result is an EulerAngles in the in the z-x-z convention
  1271. var qx = this.x;
  1272. var qy = this.y;
  1273. var qz = this.z;
  1274. var qw = this.w;
  1275. var qxy = qx * qy;
  1276. var qxz = qx * qz;
  1277. var qwy = qw * qy;
  1278. var qwz = qw * qz;
  1279. var qwx = qw * qx;
  1280. var qyz = qy * qz;
  1281. var sqx = qx * qx;
  1282. var sqy = qy * qy;
  1283. var determinant = sqx + sqy;
  1284. if (determinant !== 0.000 && determinant !== 1.000) {
  1285. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1286. result.y = Math.acos(1 - 2 * determinant);
  1287. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1288. }
  1289. else {
  1290. if (determinant === 0.0) {
  1291. result.x = 0.0;
  1292. result.y = 0.0;
  1293. 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)
  1294. }
  1295. else {
  1296. 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)
  1297. result.y = Math.PI;
  1298. result.z = 0.0;
  1299. }
  1300. }
  1301. return this;
  1302. };
  1303. Quaternion.prototype.toRotationMatrix = function (result) {
  1304. var xx = this.x * this.x;
  1305. var yy = this.y * this.y;
  1306. var zz = this.z * this.z;
  1307. var xy = this.x * this.y;
  1308. var zw = this.z * this.w;
  1309. var zx = this.z * this.x;
  1310. var yw = this.y * this.w;
  1311. var yz = this.y * this.z;
  1312. var xw = this.x * this.w;
  1313. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1314. result.m[1] = 2.0 * (xy + zw);
  1315. result.m[2] = 2.0 * (zx - yw);
  1316. result.m[3] = 0;
  1317. result.m[4] = 2.0 * (xy - zw);
  1318. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1319. result.m[6] = 2.0 * (yz + xw);
  1320. result.m[7] = 0;
  1321. result.m[8] = 2.0 * (zx + yw);
  1322. result.m[9] = 2.0 * (yz - xw);
  1323. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1324. result.m[11] = 0;
  1325. result.m[12] = 0;
  1326. result.m[13] = 0;
  1327. result.m[14] = 0;
  1328. result.m[15] = 1.0;
  1329. return this;
  1330. };
  1331. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1332. Quaternion.FromRotationMatrixToRef(matrix, this);
  1333. return this;
  1334. };
  1335. // Statics
  1336. Quaternion.FromRotationMatrix = function (matrix) {
  1337. var result = new Quaternion();
  1338. Quaternion.FromRotationMatrixToRef(matrix, result);
  1339. return result;
  1340. };
  1341. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1342. var data = matrix.m;
  1343. var m11 = data[0], m12 = data[4], m13 = data[8];
  1344. var m21 = data[1], m22 = data[5], m23 = data[9];
  1345. var m31 = data[2], m32 = data[6], m33 = data[10];
  1346. var trace = m11 + m22 + m33;
  1347. var s;
  1348. if (trace > 0) {
  1349. s = 0.5 / Math.sqrt(trace + 1.0);
  1350. result.w = 0.25 / s;
  1351. result.x = (m32 - m23) * s;
  1352. result.y = (m13 - m31) * s;
  1353. result.z = (m21 - m12) * s;
  1354. }
  1355. else if (m11 > m22 && m11 > m33) {
  1356. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1357. result.w = (m32 - m23) / s;
  1358. result.x = 0.25 * s;
  1359. result.y = (m12 + m21) / s;
  1360. result.z = (m13 + m31) / s;
  1361. }
  1362. else if (m22 > m33) {
  1363. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1364. result.w = (m13 - m31) / s;
  1365. result.x = (m12 + m21) / s;
  1366. result.y = 0.25 * s;
  1367. result.z = (m23 + m32) / s;
  1368. }
  1369. else {
  1370. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1371. result.w = (m21 - m12) / s;
  1372. result.x = (m13 + m31) / s;
  1373. result.y = (m23 + m32) / s;
  1374. result.z = 0.25 * s;
  1375. }
  1376. };
  1377. Quaternion.Inverse = function (q) {
  1378. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1379. };
  1380. Quaternion.Identity = function () {
  1381. return new Quaternion(0, 0, 0, 1);
  1382. };
  1383. Quaternion.RotationAxis = function (axis, angle) {
  1384. var result = new Quaternion();
  1385. var sin = Math.sin(angle / 2);
  1386. axis.normalize();
  1387. result.w = Math.cos(angle / 2);
  1388. result.x = axis.x * sin;
  1389. result.y = axis.y * sin;
  1390. result.z = axis.z * sin;
  1391. return result;
  1392. };
  1393. Quaternion.FromArray = function (array, offset) {
  1394. if (!offset) {
  1395. offset = 0;
  1396. }
  1397. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1398. };
  1399. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1400. var result = new Quaternion();
  1401. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1402. return result;
  1403. };
  1404. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1405. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1406. var halfRoll = roll * 0.5;
  1407. var halfPitch = pitch * 0.5;
  1408. var halfYaw = yaw * 0.5;
  1409. var sinRoll = Math.sin(halfRoll);
  1410. var cosRoll = Math.cos(halfRoll);
  1411. var sinPitch = Math.sin(halfPitch);
  1412. var cosPitch = Math.cos(halfPitch);
  1413. var sinYaw = Math.sin(halfYaw);
  1414. var cosYaw = Math.cos(halfYaw);
  1415. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1416. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1417. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1418. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1419. };
  1420. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1421. var result = new Quaternion();
  1422. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1423. return result;
  1424. };
  1425. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1426. // Produces a quaternion from Euler angles in the z-x-z orientation
  1427. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1428. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1429. var halfBeta = beta * 0.5;
  1430. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1431. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1432. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1433. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1434. };
  1435. Quaternion.Slerp = function (left, right, amount) {
  1436. var num2;
  1437. var num3;
  1438. var num = amount;
  1439. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1440. var flag = false;
  1441. if (num4 < 0) {
  1442. flag = true;
  1443. num4 = -num4;
  1444. }
  1445. if (num4 > 0.999999) {
  1446. num3 = 1 - num;
  1447. num2 = flag ? -num : num;
  1448. }
  1449. else {
  1450. var num5 = Math.acos(num4);
  1451. var num6 = (1.0 / Math.sin(num5));
  1452. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1453. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1454. }
  1455. 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));
  1456. };
  1457. return Quaternion;
  1458. })();
  1459. BABYLON.Quaternion = Quaternion;
  1460. var Matrix = (function () {
  1461. function Matrix() {
  1462. this.m = new Float32Array(16);
  1463. }
  1464. // Properties
  1465. Matrix.prototype.isIdentity = function () {
  1466. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1467. return false;
  1468. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1469. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1470. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1471. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1472. return false;
  1473. return true;
  1474. };
  1475. Matrix.prototype.determinant = function () {
  1476. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1477. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1478. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1479. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1480. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1481. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1482. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1483. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1484. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1485. };
  1486. // Methods
  1487. Matrix.prototype.toArray = function () {
  1488. return this.m;
  1489. };
  1490. Matrix.prototype.asArray = function () {
  1491. return this.toArray();
  1492. };
  1493. Matrix.prototype.invert = function () {
  1494. this.invertToRef(this);
  1495. return this;
  1496. };
  1497. Matrix.prototype.reset = function () {
  1498. for (var index = 0; index < 16; index++) {
  1499. this.m[index] = 0;
  1500. }
  1501. return this;
  1502. };
  1503. Matrix.prototype.add = function (other) {
  1504. var result = new Matrix();
  1505. this.addToRef(other, result);
  1506. return result;
  1507. };
  1508. Matrix.prototype.addToRef = function (other, result) {
  1509. for (var index = 0; index < 16; index++) {
  1510. result.m[index] = this.m[index] + other.m[index];
  1511. }
  1512. return this;
  1513. };
  1514. Matrix.prototype.addToSelf = function (other) {
  1515. for (var index = 0; index < 16; index++) {
  1516. this.m[index] += other.m[index];
  1517. }
  1518. return this;
  1519. };
  1520. Matrix.prototype.invertToRef = function (other) {
  1521. var l1 = this.m[0];
  1522. var l2 = this.m[1];
  1523. var l3 = this.m[2];
  1524. var l4 = this.m[3];
  1525. var l5 = this.m[4];
  1526. var l6 = this.m[5];
  1527. var l7 = this.m[6];
  1528. var l8 = this.m[7];
  1529. var l9 = this.m[8];
  1530. var l10 = this.m[9];
  1531. var l11 = this.m[10];
  1532. var l12 = this.m[11];
  1533. var l13 = this.m[12];
  1534. var l14 = this.m[13];
  1535. var l15 = this.m[14];
  1536. var l16 = this.m[15];
  1537. var l17 = (l11 * l16) - (l12 * l15);
  1538. var l18 = (l10 * l16) - (l12 * l14);
  1539. var l19 = (l10 * l15) - (l11 * l14);
  1540. var l20 = (l9 * l16) - (l12 * l13);
  1541. var l21 = (l9 * l15) - (l11 * l13);
  1542. var l22 = (l9 * l14) - (l10 * l13);
  1543. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1544. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1545. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1546. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1547. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1548. var l28 = (l7 * l16) - (l8 * l15);
  1549. var l29 = (l6 * l16) - (l8 * l14);
  1550. var l30 = (l6 * l15) - (l7 * l14);
  1551. var l31 = (l5 * l16) - (l8 * l13);
  1552. var l32 = (l5 * l15) - (l7 * l13);
  1553. var l33 = (l5 * l14) - (l6 * l13);
  1554. var l34 = (l7 * l12) - (l8 * l11);
  1555. var l35 = (l6 * l12) - (l8 * l10);
  1556. var l36 = (l6 * l11) - (l7 * l10);
  1557. var l37 = (l5 * l12) - (l8 * l9);
  1558. var l38 = (l5 * l11) - (l7 * l9);
  1559. var l39 = (l5 * l10) - (l6 * l9);
  1560. other.m[0] = l23 * l27;
  1561. other.m[4] = l24 * l27;
  1562. other.m[8] = l25 * l27;
  1563. other.m[12] = l26 * l27;
  1564. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1565. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1566. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1567. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1568. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1569. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1570. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1571. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1572. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1573. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1574. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1575. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1576. return this;
  1577. };
  1578. Matrix.prototype.setTranslation = function (vector3) {
  1579. this.m[12] = vector3.x;
  1580. this.m[13] = vector3.y;
  1581. this.m[14] = vector3.z;
  1582. return this;
  1583. };
  1584. Matrix.prototype.multiply = function (other) {
  1585. var result = new Matrix();
  1586. this.multiplyToRef(other, result);
  1587. return result;
  1588. };
  1589. Matrix.prototype.copyFrom = function (other) {
  1590. for (var index = 0; index < 16; index++) {
  1591. this.m[index] = other.m[index];
  1592. }
  1593. return this;
  1594. };
  1595. Matrix.prototype.copyToArray = function (array, offset) {
  1596. if (offset === void 0) { offset = 0; }
  1597. for (var index = 0; index < 16; index++) {
  1598. array[offset + index] = this.m[index];
  1599. }
  1600. return this;
  1601. };
  1602. Matrix.prototype.multiplyToRef = function (other, result) {
  1603. this.multiplyToArray(other, result.m, 0);
  1604. return this;
  1605. };
  1606. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1607. var tm0 = this.m[0];
  1608. var tm1 = this.m[1];
  1609. var tm2 = this.m[2];
  1610. var tm3 = this.m[3];
  1611. var tm4 = this.m[4];
  1612. var tm5 = this.m[5];
  1613. var tm6 = this.m[6];
  1614. var tm7 = this.m[7];
  1615. var tm8 = this.m[8];
  1616. var tm9 = this.m[9];
  1617. var tm10 = this.m[10];
  1618. var tm11 = this.m[11];
  1619. var tm12 = this.m[12];
  1620. var tm13 = this.m[13];
  1621. var tm14 = this.m[14];
  1622. var tm15 = this.m[15];
  1623. var om0 = other.m[0];
  1624. var om1 = other.m[1];
  1625. var om2 = other.m[2];
  1626. var om3 = other.m[3];
  1627. var om4 = other.m[4];
  1628. var om5 = other.m[5];
  1629. var om6 = other.m[6];
  1630. var om7 = other.m[7];
  1631. var om8 = other.m[8];
  1632. var om9 = other.m[9];
  1633. var om10 = other.m[10];
  1634. var om11 = other.m[11];
  1635. var om12 = other.m[12];
  1636. var om13 = other.m[13];
  1637. var om14 = other.m[14];
  1638. var om15 = other.m[15];
  1639. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1640. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1641. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1642. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1643. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1644. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1645. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1646. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1647. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1648. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1649. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1650. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1651. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1652. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1653. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1654. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1655. return this;
  1656. };
  1657. Matrix.prototype.equals = function (value) {
  1658. return value &&
  1659. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1660. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1661. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1662. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1663. };
  1664. Matrix.prototype.clone = function () {
  1665. 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]);
  1666. };
  1667. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1668. translation.x = this.m[12];
  1669. translation.y = this.m[13];
  1670. translation.z = this.m[14];
  1671. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1672. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1673. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1674. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1675. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1676. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1677. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1678. rotation.x = 0;
  1679. rotation.y = 0;
  1680. rotation.z = 0;
  1681. rotation.w = 1;
  1682. return false;
  1683. }
  1684. 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);
  1685. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1686. return true;
  1687. };
  1688. // Statics
  1689. Matrix.FromArray = function (array, offset) {
  1690. var result = new Matrix();
  1691. if (!offset) {
  1692. offset = 0;
  1693. }
  1694. Matrix.FromArrayToRef(array, offset, result);
  1695. return result;
  1696. };
  1697. Matrix.FromArrayToRef = function (array, offset, result) {
  1698. for (var index = 0; index < 16; index++) {
  1699. result.m[index] = array[index + offset];
  1700. }
  1701. };
  1702. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1703. for (var index = 0; index < 16; index++) {
  1704. result.m[index] = array[index + offset] * scale;
  1705. }
  1706. };
  1707. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1708. result.m[0] = initialM11;
  1709. result.m[1] = initialM12;
  1710. result.m[2] = initialM13;
  1711. result.m[3] = initialM14;
  1712. result.m[4] = initialM21;
  1713. result.m[5] = initialM22;
  1714. result.m[6] = initialM23;
  1715. result.m[7] = initialM24;
  1716. result.m[8] = initialM31;
  1717. result.m[9] = initialM32;
  1718. result.m[10] = initialM33;
  1719. result.m[11] = initialM34;
  1720. result.m[12] = initialM41;
  1721. result.m[13] = initialM42;
  1722. result.m[14] = initialM43;
  1723. result.m[15] = initialM44;
  1724. };
  1725. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1726. var result = new Matrix();
  1727. result.m[0] = initialM11;
  1728. result.m[1] = initialM12;
  1729. result.m[2] = initialM13;
  1730. result.m[3] = initialM14;
  1731. result.m[4] = initialM21;
  1732. result.m[5] = initialM22;
  1733. result.m[6] = initialM23;
  1734. result.m[7] = initialM24;
  1735. result.m[8] = initialM31;
  1736. result.m[9] = initialM32;
  1737. result.m[10] = initialM33;
  1738. result.m[11] = initialM34;
  1739. result.m[12] = initialM41;
  1740. result.m[13] = initialM42;
  1741. result.m[14] = initialM43;
  1742. result.m[15] = initialM44;
  1743. return result;
  1744. };
  1745. Matrix.Compose = function (scale, rotation, translation) {
  1746. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1747. var rotationMatrix = Matrix.Identity();
  1748. rotation.toRotationMatrix(rotationMatrix);
  1749. result = result.multiply(rotationMatrix);
  1750. result.setTranslation(translation);
  1751. return result;
  1752. };
  1753. Matrix.Identity = function () {
  1754. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1755. };
  1756. Matrix.IdentityToRef = function (result) {
  1757. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1758. };
  1759. Matrix.Zero = function () {
  1760. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1761. };
  1762. Matrix.RotationX = function (angle) {
  1763. var result = new Matrix();
  1764. Matrix.RotationXToRef(angle, result);
  1765. return result;
  1766. };
  1767. Matrix.Invert = function (source) {
  1768. var result = new Matrix();
  1769. source.invertToRef(result);
  1770. return result;
  1771. };
  1772. Matrix.RotationXToRef = function (angle, result) {
  1773. var s = Math.sin(angle);
  1774. var c = Math.cos(angle);
  1775. result.m[0] = 1.0;
  1776. result.m[15] = 1.0;
  1777. result.m[5] = c;
  1778. result.m[10] = c;
  1779. result.m[9] = -s;
  1780. result.m[6] = s;
  1781. result.m[1] = 0;
  1782. result.m[2] = 0;
  1783. result.m[3] = 0;
  1784. result.m[4] = 0;
  1785. result.m[7] = 0;
  1786. result.m[8] = 0;
  1787. result.m[11] = 0;
  1788. result.m[12] = 0;
  1789. result.m[13] = 0;
  1790. result.m[14] = 0;
  1791. };
  1792. Matrix.RotationY = function (angle) {
  1793. var result = new Matrix();
  1794. Matrix.RotationYToRef(angle, result);
  1795. return result;
  1796. };
  1797. Matrix.RotationYToRef = function (angle, result) {
  1798. var s = Math.sin(angle);
  1799. var c = Math.cos(angle);
  1800. result.m[5] = 1.0;
  1801. result.m[15] = 1.0;
  1802. result.m[0] = c;
  1803. result.m[2] = -s;
  1804. result.m[8] = s;
  1805. result.m[10] = c;
  1806. result.m[1] = 0;
  1807. result.m[3] = 0;
  1808. result.m[4] = 0;
  1809. result.m[6] = 0;
  1810. result.m[7] = 0;
  1811. result.m[9] = 0;
  1812. result.m[11] = 0;
  1813. result.m[12] = 0;
  1814. result.m[13] = 0;
  1815. result.m[14] = 0;
  1816. };
  1817. Matrix.RotationZ = function (angle) {
  1818. var result = new Matrix();
  1819. Matrix.RotationZToRef(angle, result);
  1820. return result;
  1821. };
  1822. Matrix.RotationZToRef = function (angle, result) {
  1823. var s = Math.sin(angle);
  1824. var c = Math.cos(angle);
  1825. result.m[10] = 1.0;
  1826. result.m[15] = 1.0;
  1827. result.m[0] = c;
  1828. result.m[1] = s;
  1829. result.m[4] = -s;
  1830. result.m[5] = c;
  1831. result.m[2] = 0;
  1832. result.m[3] = 0;
  1833. result.m[6] = 0;
  1834. result.m[7] = 0;
  1835. result.m[8] = 0;
  1836. result.m[9] = 0;
  1837. result.m[11] = 0;
  1838. result.m[12] = 0;
  1839. result.m[13] = 0;
  1840. result.m[14] = 0;
  1841. };
  1842. Matrix.RotationAxis = function (axis, angle) {
  1843. var result = Matrix.Zero();
  1844. Matrix.RotationAxisToRef(axis, angle, result);
  1845. return result;
  1846. };
  1847. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1848. var s = Math.sin(-angle);
  1849. var c = Math.cos(-angle);
  1850. var c1 = 1 - c;
  1851. axis.normalize();
  1852. result.m[0] = (axis.x * axis.x) * c1 + c;
  1853. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1854. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1855. result.m[3] = 0.0;
  1856. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1857. result.m[5] = (axis.y * axis.y) * c1 + c;
  1858. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1859. result.m[7] = 0.0;
  1860. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1861. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1862. result.m[10] = (axis.z * axis.z) * c1 + c;
  1863. result.m[11] = 0.0;
  1864. result.m[15] = 1.0;
  1865. };
  1866. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1867. var result = new Matrix();
  1868. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1869. return result;
  1870. };
  1871. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1872. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1873. this._tempQuaternion.toRotationMatrix(result);
  1874. };
  1875. Matrix.Scaling = function (x, y, z) {
  1876. var result = Matrix.Zero();
  1877. Matrix.ScalingToRef(x, y, z, result);
  1878. return result;
  1879. };
  1880. Matrix.ScalingToRef = function (x, y, z, result) {
  1881. result.m[0] = x;
  1882. result.m[1] = 0;
  1883. result.m[2] = 0;
  1884. result.m[3] = 0;
  1885. result.m[4] = 0;
  1886. result.m[5] = y;
  1887. result.m[6] = 0;
  1888. result.m[7] = 0;
  1889. result.m[8] = 0;
  1890. result.m[9] = 0;
  1891. result.m[10] = z;
  1892. result.m[11] = 0;
  1893. result.m[12] = 0;
  1894. result.m[13] = 0;
  1895. result.m[14] = 0;
  1896. result.m[15] = 1.0;
  1897. };
  1898. Matrix.Translation = function (x, y, z) {
  1899. var result = Matrix.Identity();
  1900. Matrix.TranslationToRef(x, y, z, result);
  1901. return result;
  1902. };
  1903. Matrix.TranslationToRef = function (x, y, z, result) {
  1904. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1905. };
  1906. Matrix.LookAtLH = function (eye, target, up) {
  1907. var result = Matrix.Zero();
  1908. Matrix.LookAtLHToRef(eye, target, up, result);
  1909. return result;
  1910. };
  1911. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1912. // Z axis
  1913. target.subtractToRef(eye, this._zAxis);
  1914. this._zAxis.normalize();
  1915. // X axis
  1916. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1917. if (this._xAxis.lengthSquared() === 0) {
  1918. this._xAxis.x = 1.0;
  1919. }
  1920. else {
  1921. this._xAxis.normalize();
  1922. }
  1923. // Y axis
  1924. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1925. this._yAxis.normalize();
  1926. // Eye angles
  1927. var ex = -Vector3.Dot(this._xAxis, eye);
  1928. var ey = -Vector3.Dot(this._yAxis, eye);
  1929. var ez = -Vector3.Dot(this._zAxis, eye);
  1930. 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);
  1931. };
  1932. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1933. var matrix = Matrix.Zero();
  1934. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1935. return matrix;
  1936. };
  1937. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1938. var hw = 2.0 / width;
  1939. var hh = 2.0 / height;
  1940. var id = 1.0 / (zfar - znear);
  1941. var nid = znear / (znear - zfar);
  1942. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1943. };
  1944. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1945. var matrix = Matrix.Zero();
  1946. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1947. return matrix;
  1948. };
  1949. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1950. result.m[0] = 2.0 / (right - left);
  1951. result.m[1] = result.m[2] = result.m[3] = 0;
  1952. result.m[5] = 2.0 / (top - bottom);
  1953. result.m[4] = result.m[6] = result.m[7] = 0;
  1954. result.m[10] = -1.0 / (znear - zfar);
  1955. result.m[8] = result.m[9] = result.m[11] = 0;
  1956. result.m[12] = (left + right) / (left - right);
  1957. result.m[13] = (top + bottom) / (bottom - top);
  1958. result.m[14] = znear / (znear - zfar);
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1962. var matrix = Matrix.Zero();
  1963. matrix.m[0] = (2.0 * znear) / width;
  1964. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1965. matrix.m[5] = (2.0 * znear) / height;
  1966. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1967. matrix.m[10] = -zfar / (znear - zfar);
  1968. matrix.m[8] = matrix.m[9] = 0.0;
  1969. matrix.m[11] = 1.0;
  1970. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1971. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1972. return matrix;
  1973. };
  1974. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1975. var matrix = Matrix.Zero();
  1976. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1977. return matrix;
  1978. };
  1979. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1980. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1981. var tan = 1.0 / (Math.tan(fov * 0.5));
  1982. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1983. if (v_fixed) {
  1984. result.m[0] = tan / aspect;
  1985. }
  1986. else {
  1987. result.m[0] = tan;
  1988. }
  1989. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1990. if (v_fixed) {
  1991. result.m[5] = tan;
  1992. }
  1993. else {
  1994. result.m[5] = tan * aspect;
  1995. }
  1996. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1997. result.m[8] = result.m[9] = 0.0;
  1998. result.m[10] = -zfar / (znear - zfar);
  1999. result.m[11] = 1.0;
  2000. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2001. result.m[14] = (znear * zfar) / (znear - zfar);
  2002. };
  2003. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2004. var cw = viewport.width;
  2005. var ch = viewport.height;
  2006. var cx = viewport.x;
  2007. var cy = viewport.y;
  2008. 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);
  2009. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2010. };
  2011. Matrix.GetAsMatrix2x2 = function (matrix) {
  2012. return new Float32Array([
  2013. matrix.m[0], matrix.m[1],
  2014. matrix.m[4], matrix.m[5]
  2015. ]);
  2016. };
  2017. Matrix.GetAsMatrix3x3 = function (matrix) {
  2018. return new Float32Array([
  2019. matrix.m[0], matrix.m[1], matrix.m[2],
  2020. matrix.m[4], matrix.m[5], matrix.m[6],
  2021. matrix.m[8], matrix.m[9], matrix.m[10]
  2022. ]);
  2023. };
  2024. Matrix.Transpose = function (matrix) {
  2025. var result = new Matrix();
  2026. result.m[0] = matrix.m[0];
  2027. result.m[1] = matrix.m[4];
  2028. result.m[2] = matrix.m[8];
  2029. result.m[3] = matrix.m[12];
  2030. result.m[4] = matrix.m[1];
  2031. result.m[5] = matrix.m[5];
  2032. result.m[6] = matrix.m[9];
  2033. result.m[7] = matrix.m[13];
  2034. result.m[8] = matrix.m[2];
  2035. result.m[9] = matrix.m[6];
  2036. result.m[10] = matrix.m[10];
  2037. result.m[11] = matrix.m[14];
  2038. result.m[12] = matrix.m[3];
  2039. result.m[13] = matrix.m[7];
  2040. result.m[14] = matrix.m[11];
  2041. result.m[15] = matrix.m[15];
  2042. return result;
  2043. };
  2044. Matrix.Reflection = function (plane) {
  2045. var matrix = new Matrix();
  2046. Matrix.ReflectionToRef(plane, matrix);
  2047. return matrix;
  2048. };
  2049. Matrix.ReflectionToRef = function (plane, result) {
  2050. plane.normalize();
  2051. var x = plane.normal.x;
  2052. var y = plane.normal.y;
  2053. var z = plane.normal.z;
  2054. var temp = -2 * x;
  2055. var temp2 = -2 * y;
  2056. var temp3 = -2 * z;
  2057. result.m[0] = (temp * x) + 1;
  2058. result.m[1] = temp2 * x;
  2059. result.m[2] = temp3 * x;
  2060. result.m[3] = 0.0;
  2061. result.m[4] = temp * y;
  2062. result.m[5] = (temp2 * y) + 1;
  2063. result.m[6] = temp3 * y;
  2064. result.m[7] = 0.0;
  2065. result.m[8] = temp * z;
  2066. result.m[9] = temp2 * z;
  2067. result.m[10] = (temp3 * z) + 1;
  2068. result.m[11] = 0.0;
  2069. result.m[12] = temp * plane.d;
  2070. result.m[13] = temp2 * plane.d;
  2071. result.m[14] = temp3 * plane.d;
  2072. result.m[15] = 1.0;
  2073. };
  2074. Matrix._tempQuaternion = new Quaternion();
  2075. Matrix._xAxis = Vector3.Zero();
  2076. Matrix._yAxis = Vector3.Zero();
  2077. Matrix._zAxis = Vector3.Zero();
  2078. return Matrix;
  2079. })();
  2080. BABYLON.Matrix = Matrix;
  2081. var Plane = (function () {
  2082. function Plane(a, b, c, d) {
  2083. this.normal = new Vector3(a, b, c);
  2084. this.d = d;
  2085. }
  2086. Plane.prototype.asArray = function () {
  2087. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2088. };
  2089. // Methods
  2090. Plane.prototype.clone = function () {
  2091. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2092. };
  2093. Plane.prototype.normalize = function () {
  2094. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2095. var magnitude = 0;
  2096. if (norm !== 0) {
  2097. magnitude = 1.0 / norm;
  2098. }
  2099. this.normal.x *= magnitude;
  2100. this.normal.y *= magnitude;
  2101. this.normal.z *= magnitude;
  2102. this.d *= magnitude;
  2103. return this;
  2104. };
  2105. Plane.prototype.transform = function (transformation) {
  2106. var transposedMatrix = Matrix.Transpose(transformation);
  2107. var x = this.normal.x;
  2108. var y = this.normal.y;
  2109. var z = this.normal.z;
  2110. var d = this.d;
  2111. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2112. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2113. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2114. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2115. return new Plane(normalX, normalY, normalZ, finalD);
  2116. };
  2117. Plane.prototype.dotCoordinate = function (point) {
  2118. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2119. };
  2120. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2121. var x1 = point2.x - point1.x;
  2122. var y1 = point2.y - point1.y;
  2123. var z1 = point2.z - point1.z;
  2124. var x2 = point3.x - point1.x;
  2125. var y2 = point3.y - point1.y;
  2126. var z2 = point3.z - point1.z;
  2127. var yz = (y1 * z2) - (z1 * y2);
  2128. var xz = (z1 * x2) - (x1 * z2);
  2129. var xy = (x1 * y2) - (y1 * x2);
  2130. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2131. var invPyth;
  2132. if (pyth !== 0) {
  2133. invPyth = 1.0 / pyth;
  2134. }
  2135. else {
  2136. invPyth = 0;
  2137. }
  2138. this.normal.x = yz * invPyth;
  2139. this.normal.y = xz * invPyth;
  2140. this.normal.z = xy * invPyth;
  2141. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2142. return this;
  2143. };
  2144. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2145. var dot = Vector3.Dot(this.normal, direction);
  2146. return (dot <= epsilon);
  2147. };
  2148. Plane.prototype.signedDistanceTo = function (point) {
  2149. return Vector3.Dot(point, this.normal) + this.d;
  2150. };
  2151. // Statics
  2152. Plane.FromArray = function (array) {
  2153. return new Plane(array[0], array[1], array[2], array[3]);
  2154. };
  2155. Plane.FromPoints = function (point1, point2, point3) {
  2156. var result = new Plane(0, 0, 0, 0);
  2157. result.copyFromPoints(point1, point2, point3);
  2158. return result;
  2159. };
  2160. Plane.FromPositionAndNormal = function (origin, normal) {
  2161. var result = new Plane(0, 0, 0, 0);
  2162. normal.normalize();
  2163. result.normal = normal;
  2164. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2165. return result;
  2166. };
  2167. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2168. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2169. return Vector3.Dot(point, normal) + d;
  2170. };
  2171. return Plane;
  2172. })();
  2173. BABYLON.Plane = Plane;
  2174. var Viewport = (function () {
  2175. function Viewport(x, y, width, height) {
  2176. this.x = x;
  2177. this.y = y;
  2178. this.width = width;
  2179. this.height = height;
  2180. }
  2181. Viewport.prototype.toGlobal = function (engine) {
  2182. var width = engine.getRenderWidth();
  2183. var height = engine.getRenderHeight();
  2184. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2185. };
  2186. return Viewport;
  2187. })();
  2188. BABYLON.Viewport = Viewport;
  2189. var Frustum = (function () {
  2190. function Frustum() {
  2191. }
  2192. Frustum.GetPlanes = function (transform) {
  2193. var frustumPlanes = [];
  2194. for (var index = 0; index < 6; index++) {
  2195. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2196. }
  2197. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2198. return frustumPlanes;
  2199. };
  2200. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2201. // Near
  2202. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2203. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2204. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2205. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2206. frustumPlanes[0].normalize();
  2207. // Far
  2208. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2209. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2210. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2211. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2212. frustumPlanes[1].normalize();
  2213. // Left
  2214. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2215. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2216. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2217. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2218. frustumPlanes[2].normalize();
  2219. // Right
  2220. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2221. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2222. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2223. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2224. frustumPlanes[3].normalize();
  2225. // Top
  2226. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2227. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2228. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2229. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2230. frustumPlanes[4].normalize();
  2231. // Bottom
  2232. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2233. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2234. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2235. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2236. frustumPlanes[5].normalize();
  2237. };
  2238. return Frustum;
  2239. })();
  2240. BABYLON.Frustum = Frustum;
  2241. var Ray = (function () {
  2242. function Ray(origin, direction, length) {
  2243. if (length === void 0) { length = Number.MAX_VALUE; }
  2244. this.origin = origin;
  2245. this.direction = direction;
  2246. this.length = length;
  2247. }
  2248. // Methods
  2249. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2250. var d = 0.0;
  2251. var maxValue = Number.MAX_VALUE;
  2252. var inv;
  2253. var min;
  2254. var max;
  2255. var temp;
  2256. if (Math.abs(this.direction.x) < 0.0000001) {
  2257. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2258. return false;
  2259. }
  2260. }
  2261. else {
  2262. inv = 1.0 / this.direction.x;
  2263. min = (minimum.x - this.origin.x) * inv;
  2264. max = (maximum.x - this.origin.x) * inv;
  2265. if (max === -Infinity) {
  2266. max = Infinity;
  2267. }
  2268. if (min > max) {
  2269. temp = min;
  2270. min = max;
  2271. max = temp;
  2272. }
  2273. d = Math.max(min, d);
  2274. maxValue = Math.min(max, maxValue);
  2275. if (d > maxValue) {
  2276. return false;
  2277. }
  2278. }
  2279. if (Math.abs(this.direction.y) < 0.0000001) {
  2280. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2281. return false;
  2282. }
  2283. }
  2284. else {
  2285. inv = 1.0 / this.direction.y;
  2286. min = (minimum.y - this.origin.y) * inv;
  2287. max = (maximum.y - this.origin.y) * inv;
  2288. if (max === -Infinity) {
  2289. max = Infinity;
  2290. }
  2291. if (min > max) {
  2292. temp = min;
  2293. min = max;
  2294. max = temp;
  2295. }
  2296. d = Math.max(min, d);
  2297. maxValue = Math.min(max, maxValue);
  2298. if (d > maxValue) {
  2299. return false;
  2300. }
  2301. }
  2302. if (Math.abs(this.direction.z) < 0.0000001) {
  2303. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2304. return false;
  2305. }
  2306. }
  2307. else {
  2308. inv = 1.0 / this.direction.z;
  2309. min = (minimum.z - this.origin.z) * inv;
  2310. max = (maximum.z - this.origin.z) * inv;
  2311. if (max === -Infinity) {
  2312. max = Infinity;
  2313. }
  2314. if (min > max) {
  2315. temp = min;
  2316. min = max;
  2317. max = temp;
  2318. }
  2319. d = Math.max(min, d);
  2320. maxValue = Math.min(max, maxValue);
  2321. if (d > maxValue) {
  2322. return false;
  2323. }
  2324. }
  2325. return true;
  2326. };
  2327. Ray.prototype.intersectsBox = function (box) {
  2328. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2329. };
  2330. Ray.prototype.intersectsSphere = function (sphere) {
  2331. var x = sphere.center.x - this.origin.x;
  2332. var y = sphere.center.y - this.origin.y;
  2333. var z = sphere.center.z - this.origin.z;
  2334. var pyth = (x * x) + (y * y) + (z * z);
  2335. var rr = sphere.radius * sphere.radius;
  2336. if (pyth <= rr) {
  2337. return true;
  2338. }
  2339. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2340. if (dot < 0.0) {
  2341. return false;
  2342. }
  2343. var temp = pyth - (dot * dot);
  2344. return temp <= rr;
  2345. };
  2346. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2347. if (!this._edge1) {
  2348. this._edge1 = Vector3.Zero();
  2349. this._edge2 = Vector3.Zero();
  2350. this._pvec = Vector3.Zero();
  2351. this._tvec = Vector3.Zero();
  2352. this._qvec = Vector3.Zero();
  2353. }
  2354. vertex1.subtractToRef(vertex0, this._edge1);
  2355. vertex2.subtractToRef(vertex0, this._edge2);
  2356. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2357. var det = Vector3.Dot(this._edge1, this._pvec);
  2358. if (det === 0) {
  2359. return null;
  2360. }
  2361. var invdet = 1 / det;
  2362. this.origin.subtractToRef(vertex0, this._tvec);
  2363. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2364. if (bu < 0 || bu > 1.0) {
  2365. return null;
  2366. }
  2367. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2368. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2369. if (bv < 0 || bu + bv > 1.0) {
  2370. return null;
  2371. }
  2372. //check if the distance is longer than the predefined length.
  2373. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2374. if (distance > this.length) {
  2375. return null;
  2376. }
  2377. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2378. };
  2379. // Statics
  2380. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2381. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2382. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2383. var direction = end.subtract(start);
  2384. direction.normalize();
  2385. return new Ray(start, direction);
  2386. };
  2387. /**
  2388. * 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
  2389. * transformed to the given world matrix.
  2390. * @param origin The origin point
  2391. * @param end The end point
  2392. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2393. */
  2394. Ray.CreateNewFromTo = function (origin, end, world) {
  2395. if (world === void 0) { world = Matrix.Identity(); }
  2396. var direction = end.subtract(origin);
  2397. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2398. direction.normalize();
  2399. return Ray.Transform(new Ray(origin, direction, length), world);
  2400. };
  2401. Ray.Transform = function (ray, matrix) {
  2402. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2403. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2404. return new Ray(newOrigin, newDirection, ray.length);
  2405. };
  2406. return Ray;
  2407. })();
  2408. BABYLON.Ray = Ray;
  2409. (function (Space) {
  2410. Space[Space["LOCAL"] = 0] = "LOCAL";
  2411. Space[Space["WORLD"] = 1] = "WORLD";
  2412. })(BABYLON.Space || (BABYLON.Space = {}));
  2413. var Space = BABYLON.Space;
  2414. var Axis = (function () {
  2415. function Axis() {
  2416. }
  2417. Axis.X = new Vector3(1, 0, 0);
  2418. Axis.Y = new Vector3(0, 1, 0);
  2419. Axis.Z = new Vector3(0, 0, 1);
  2420. return Axis;
  2421. })();
  2422. BABYLON.Axis = Axis;
  2423. ;
  2424. var BezierCurve = (function () {
  2425. function BezierCurve() {
  2426. }
  2427. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2428. // Extract X (which is equal to time here)
  2429. var f0 = 1 - 3 * x2 + 3 * x1;
  2430. var f1 = 3 * x2 - 6 * x1;
  2431. var f2 = 3 * x1;
  2432. var refinedT = t;
  2433. for (var i = 0; i < 5; i++) {
  2434. var refinedT2 = refinedT * refinedT;
  2435. var refinedT3 = refinedT2 * refinedT;
  2436. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2437. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2438. refinedT -= (x - t) * slope;
  2439. refinedT = Math.min(1, Math.max(0, refinedT));
  2440. }
  2441. // Resolve cubic bezier for the given x
  2442. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2443. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2444. Math.pow(refinedT, 3);
  2445. };
  2446. return BezierCurve;
  2447. })();
  2448. BABYLON.BezierCurve = BezierCurve;
  2449. (function (Orientation) {
  2450. Orientation[Orientation["CW"] = 0] = "CW";
  2451. Orientation[Orientation["CCW"] = 1] = "CCW";
  2452. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2453. var Orientation = BABYLON.Orientation;
  2454. var Angle = (function () {
  2455. function Angle(radians) {
  2456. var _this = this;
  2457. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2458. this.radians = function () { return _this._radians; };
  2459. this._radians = radians;
  2460. if (this._radians < 0)
  2461. this._radians += (2 * Math.PI);
  2462. }
  2463. Angle.BetweenTwoPoints = function (a, b) {
  2464. var delta = b.subtract(a);
  2465. var theta = Math.atan2(delta.y, delta.x);
  2466. return new Angle(theta);
  2467. };
  2468. Angle.FromRadians = function (radians) {
  2469. return new Angle(radians);
  2470. };
  2471. Angle.FromDegrees = function (degrees) {
  2472. return new Angle(degrees * Math.PI / 180);
  2473. };
  2474. return Angle;
  2475. })();
  2476. BABYLON.Angle = Angle;
  2477. var Arc2 = (function () {
  2478. function Arc2(startPoint, midPoint, endPoint) {
  2479. this.startPoint = startPoint;
  2480. this.midPoint = midPoint;
  2481. this.endPoint = endPoint;
  2482. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2483. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2484. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2485. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2486. 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);
  2487. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2488. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2489. var a1 = this.startAngle.degrees();
  2490. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2491. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2492. // angles correction
  2493. if (a2 - a1 > +180.0)
  2494. a2 -= 360.0;
  2495. if (a2 - a1 < -180.0)
  2496. a2 += 360.0;
  2497. if (a3 - a2 > +180.0)
  2498. a3 -= 360.0;
  2499. if (a3 - a2 < -180.0)
  2500. a3 += 360.0;
  2501. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2502. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2503. }
  2504. return Arc2;
  2505. })();
  2506. BABYLON.Arc2 = Arc2;
  2507. var PathCursor = (function () {
  2508. function PathCursor(path) {
  2509. this.path = path;
  2510. this._onchange = new Array();
  2511. this.value = 0;
  2512. this.animations = new Array();
  2513. }
  2514. PathCursor.prototype.getPoint = function () {
  2515. var point = this.path.getPointAtLengthPosition(this.value);
  2516. return new Vector3(point.x, 0, point.y);
  2517. };
  2518. PathCursor.prototype.moveAhead = function (step) {
  2519. if (step === void 0) { step = 0.002; }
  2520. this.move(step);
  2521. return this;
  2522. };
  2523. PathCursor.prototype.moveBack = function (step) {
  2524. if (step === void 0) { step = 0.002; }
  2525. this.move(-step);
  2526. return this;
  2527. };
  2528. PathCursor.prototype.move = function (step) {
  2529. if (Math.abs(step) > 1) {
  2530. throw "step size should be less than 1.";
  2531. }
  2532. this.value += step;
  2533. this.ensureLimits();
  2534. this.raiseOnChange();
  2535. return this;
  2536. };
  2537. PathCursor.prototype.ensureLimits = function () {
  2538. while (this.value > 1) {
  2539. this.value -= 1;
  2540. }
  2541. while (this.value < 0) {
  2542. this.value += 1;
  2543. }
  2544. return this;
  2545. };
  2546. // used by animation engine
  2547. PathCursor.prototype.markAsDirty = function (propertyName) {
  2548. this.ensureLimits();
  2549. this.raiseOnChange();
  2550. return this;
  2551. };
  2552. PathCursor.prototype.raiseOnChange = function () {
  2553. var _this = this;
  2554. this._onchange.forEach(function (f) { return f(_this); });
  2555. return this;
  2556. };
  2557. PathCursor.prototype.onchange = function (f) {
  2558. this._onchange.push(f);
  2559. return this;
  2560. };
  2561. return PathCursor;
  2562. })();
  2563. BABYLON.PathCursor = PathCursor;
  2564. var Path2 = (function () {
  2565. function Path2(x, y) {
  2566. this._points = new Array();
  2567. this._length = 0;
  2568. this.closed = false;
  2569. this._points.push(new Vector2(x, y));
  2570. }
  2571. Path2.prototype.addLineTo = function (x, y) {
  2572. if (closed) {
  2573. BABYLON.Tools.Error("cannot add lines to closed paths");
  2574. return this;
  2575. }
  2576. var newPoint = new Vector2(x, y);
  2577. var previousPoint = this._points[this._points.length - 1];
  2578. this._points.push(newPoint);
  2579. this._length += newPoint.subtract(previousPoint).length();
  2580. return this;
  2581. };
  2582. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2583. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2584. if (closed) {
  2585. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2586. return this;
  2587. }
  2588. var startPoint = this._points[this._points.length - 1];
  2589. var midPoint = new Vector2(midX, midY);
  2590. var endPoint = new Vector2(endX, endY);
  2591. var arc = new Arc2(startPoint, midPoint, endPoint);
  2592. var increment = arc.angle.radians() / numberOfSegments;
  2593. if (arc.orientation === Orientation.CW)
  2594. increment *= -1;
  2595. var currentAngle = arc.startAngle.radians() + increment;
  2596. for (var i = 0; i < numberOfSegments; i++) {
  2597. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2598. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2599. this.addLineTo(x, y);
  2600. currentAngle += increment;
  2601. }
  2602. return this;
  2603. };
  2604. Path2.prototype.close = function () {
  2605. this.closed = true;
  2606. return this;
  2607. };
  2608. Path2.prototype.length = function () {
  2609. var result = this._length;
  2610. if (!this.closed) {
  2611. var lastPoint = this._points[this._points.length - 1];
  2612. var firstPoint = this._points[0];
  2613. result += (firstPoint.subtract(lastPoint).length());
  2614. }
  2615. return result;
  2616. };
  2617. Path2.prototype.getPoints = function () {
  2618. return this._points;
  2619. };
  2620. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2621. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2622. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2623. return Vector2.Zero();
  2624. }
  2625. var lengthPosition = normalizedLengthPosition * this.length();
  2626. var previousOffset = 0;
  2627. for (var i = 0; i < this._points.length; i++) {
  2628. var j = (i + 1) % this._points.length;
  2629. var a = this._points[i];
  2630. var b = this._points[j];
  2631. var bToA = b.subtract(a);
  2632. var nextOffset = (bToA.length() + previousOffset);
  2633. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2634. var dir = bToA.normalize();
  2635. var localOffset = lengthPosition - previousOffset;
  2636. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2637. }
  2638. previousOffset = nextOffset;
  2639. }
  2640. BABYLON.Tools.Error("internal error");
  2641. return Vector2.Zero();
  2642. };
  2643. Path2.StartingAt = function (x, y) {
  2644. return new Path2(x, y);
  2645. };
  2646. return Path2;
  2647. })();
  2648. BABYLON.Path2 = Path2;
  2649. var Path3D = (function () {
  2650. /**
  2651. * new Path3D(path, normal, raw)
  2652. * path : an array of Vector3, the curve axis of the Path3D
  2653. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2654. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2655. */
  2656. function Path3D(path, firstNormal, raw) {
  2657. this.path = path;
  2658. this._curve = new Array();
  2659. this._distances = new Array();
  2660. this._tangents = new Array();
  2661. this._normals = new Array();
  2662. this._binormals = new Array();
  2663. for (var p = 0; p < path.length; p++) {
  2664. this._curve[p] = path[p].clone(); // hard copy
  2665. }
  2666. this._raw = raw || false;
  2667. this._compute(firstNormal);
  2668. }
  2669. Path3D.prototype.getCurve = function () {
  2670. return this._curve;
  2671. };
  2672. Path3D.prototype.getTangents = function () {
  2673. return this._tangents;
  2674. };
  2675. Path3D.prototype.getNormals = function () {
  2676. return this._normals;
  2677. };
  2678. Path3D.prototype.getBinormals = function () {
  2679. return this._binormals;
  2680. };
  2681. Path3D.prototype.getDistances = function () {
  2682. return this._distances;
  2683. };
  2684. Path3D.prototype.update = function (path, firstNormal) {
  2685. for (var p = 0; p < path.length; p++) {
  2686. this._curve[p].x = path[p].x;
  2687. this._curve[p].y = path[p].y;
  2688. this._curve[p].z = path[p].z;
  2689. }
  2690. this._compute(firstNormal);
  2691. return this;
  2692. };
  2693. // private function compute() : computes tangents, normals and binormals
  2694. Path3D.prototype._compute = function (firstNormal) {
  2695. var l = this._curve.length;
  2696. // first and last tangents
  2697. this._tangents[0] = this._getFirstNonNullVector(0);
  2698. if (!this._raw) {
  2699. this._tangents[0].normalize();
  2700. }
  2701. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2702. if (!this._raw) {
  2703. this._tangents[l - 1].normalize();
  2704. }
  2705. // normals and binormals at first point : arbitrary vector with _normalVector()
  2706. var tg0 = this._tangents[0];
  2707. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2708. this._normals[0] = pp0;
  2709. if (!this._raw) {
  2710. this._normals[0].normalize();
  2711. }
  2712. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2713. if (!this._raw) {
  2714. this._binormals[0].normalize();
  2715. }
  2716. this._distances[0] = 0;
  2717. // normals and binormals : next points
  2718. var prev; // previous vector (segment)
  2719. var cur; // current vector (segment)
  2720. var curTang; // current tangent
  2721. // previous normal
  2722. var prevBinor; // previous binormal
  2723. for (var i = 1; i < l; i++) {
  2724. // tangents
  2725. prev = this._getLastNonNullVector(i);
  2726. if (i < l - 1) {
  2727. cur = this._getFirstNonNullVector(i);
  2728. this._tangents[i] = prev.add(cur);
  2729. this._tangents[i].normalize();
  2730. }
  2731. this._distances[i] = this._distances[i - 1] + prev.length();
  2732. // normals and binormals
  2733. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2734. curTang = this._tangents[i];
  2735. prevBinor = this._binormals[i - 1];
  2736. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2737. if (!this._raw) {
  2738. this._normals[i].normalize();
  2739. }
  2740. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2741. if (!this._raw) {
  2742. this._binormals[i].normalize();
  2743. }
  2744. }
  2745. };
  2746. // private function getFirstNonNullVector(index)
  2747. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2748. Path3D.prototype._getFirstNonNullVector = function (index) {
  2749. var i = 1;
  2750. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2751. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2752. i++;
  2753. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2754. }
  2755. return nNVector;
  2756. };
  2757. // private function getLastNonNullVector(index)
  2758. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2759. Path3D.prototype._getLastNonNullVector = function (index) {
  2760. var i = 1;
  2761. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2762. while (nLVector.length() === 0 && index > i + 1) {
  2763. i++;
  2764. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2765. }
  2766. return nLVector;
  2767. };
  2768. // private function normalVector(v0, vt, va) :
  2769. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2770. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2771. Path3D.prototype._normalVector = function (v0, vt, va) {
  2772. var normal0;
  2773. if (va === undefined || va === null) {
  2774. var point;
  2775. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2776. point = new Vector3(0, -1, 0);
  2777. }
  2778. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2779. point = new Vector3(1, 0, 0);
  2780. }
  2781. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2782. point = new Vector3(0, 0, 1);
  2783. }
  2784. normal0 = Vector3.Cross(vt, point);
  2785. }
  2786. else {
  2787. normal0 = Vector3.Cross(vt, va);
  2788. Vector3.CrossToRef(normal0, vt, normal0);
  2789. }
  2790. normal0.normalize();
  2791. return normal0;
  2792. };
  2793. return Path3D;
  2794. })();
  2795. BABYLON.Path3D = Path3D;
  2796. var Curve3 = (function () {
  2797. function Curve3(points) {
  2798. this._length = 0;
  2799. this._points = points;
  2800. this._length = this._computeLength(points);
  2801. }
  2802. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2803. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2804. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2805. var bez = new Array();
  2806. var equation = function (t, val0, val1, val2) {
  2807. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2808. return res;
  2809. };
  2810. for (var i = 0; i <= nbPoints; i++) {
  2811. 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)));
  2812. }
  2813. return new Curve3(bez);
  2814. };
  2815. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2816. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2817. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2818. var bez = new Array();
  2819. var equation = function (t, val0, val1, val2, val3) {
  2820. 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;
  2821. return res;
  2822. };
  2823. for (var i = 0; i <= nbPoints; i++) {
  2824. 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)));
  2825. }
  2826. return new Curve3(bez);
  2827. };
  2828. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2829. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2830. var hermite = new Array();
  2831. var step = 1 / nbPoints;
  2832. for (var i = 0; i <= nbPoints; i++) {
  2833. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2834. }
  2835. return new Curve3(hermite);
  2836. };
  2837. Curve3.prototype.getPoints = function () {
  2838. return this._points;
  2839. };
  2840. Curve3.prototype.length = function () {
  2841. return this._length;
  2842. };
  2843. Curve3.prototype.continue = function (curve) {
  2844. var lastPoint = this._points[this._points.length - 1];
  2845. var continuedPoints = this._points.slice();
  2846. var curvePoints = curve.getPoints();
  2847. for (var i = 1; i < curvePoints.length; i++) {
  2848. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2849. }
  2850. var continuedCurve = new Curve3(continuedPoints);
  2851. return continuedCurve;
  2852. };
  2853. Curve3.prototype._computeLength = function (path) {
  2854. var l = 0;
  2855. for (var i = 1; i < path.length; i++) {
  2856. l += (path[i].subtract(path[i - 1])).length();
  2857. }
  2858. return l;
  2859. };
  2860. return Curve3;
  2861. })();
  2862. BABYLON.Curve3 = Curve3;
  2863. // Vertex formats
  2864. var PositionNormalVertex = (function () {
  2865. function PositionNormalVertex(position, normal) {
  2866. if (position === void 0) { position = Vector3.Zero(); }
  2867. if (normal === void 0) { normal = Vector3.Up(); }
  2868. this.position = position;
  2869. this.normal = normal;
  2870. }
  2871. PositionNormalVertex.prototype.clone = function () {
  2872. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2873. };
  2874. return PositionNormalVertex;
  2875. })();
  2876. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2877. var PositionNormalTextureVertex = (function () {
  2878. function PositionNormalTextureVertex(position, normal, uv) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. if (uv === void 0) { uv = Vector2.Zero(); }
  2882. this.position = position;
  2883. this.normal = normal;
  2884. this.uv = uv;
  2885. }
  2886. PositionNormalTextureVertex.prototype.clone = function () {
  2887. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2888. };
  2889. return PositionNormalTextureVertex;
  2890. })();
  2891. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2892. })(BABYLON || (BABYLON = {}));
  2893. var BABYLON;
  2894. (function (BABYLON) {
  2895. var Database = (function () {
  2896. function Database(urlToScene, callbackManifestChecked) {
  2897. // Handling various flavors of prefixed version of IndexedDB
  2898. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2899. this.callbackManifestChecked = callbackManifestChecked;
  2900. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2901. this.db = null;
  2902. this.enableSceneOffline = false;
  2903. this.enableTexturesOffline = false;
  2904. this.manifestVersionFound = 0;
  2905. this.mustUpdateRessources = false;
  2906. this.hasReachedQuota = false;
  2907. if (!Database.IDBStorageEnabled) {
  2908. this.callbackManifestChecked(true);
  2909. }
  2910. else {
  2911. this.checkManifestFile();
  2912. }
  2913. }
  2914. Database.prototype.checkManifestFile = function () {
  2915. var _this = this;
  2916. function noManifestFile() {
  2917. that.enableSceneOffline = false;
  2918. that.enableTexturesOffline = false;
  2919. that.callbackManifestChecked(false);
  2920. }
  2921. var that = this;
  2922. var manifestURL = this.currentSceneUrl + ".manifest";
  2923. var xhr = new XMLHttpRequest();
  2924. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2925. xhr.open("GET", manifestURLTimeStamped, true);
  2926. xhr.addEventListener("load", function () {
  2927. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2928. try {
  2929. var manifestFile = JSON.parse(xhr.response);
  2930. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2931. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2932. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2933. _this.manifestVersionFound = manifestFile.version;
  2934. }
  2935. if (_this.callbackManifestChecked) {
  2936. _this.callbackManifestChecked(true);
  2937. }
  2938. }
  2939. catch (ex) {
  2940. noManifestFile();
  2941. }
  2942. }
  2943. else {
  2944. noManifestFile();
  2945. }
  2946. }, false);
  2947. xhr.addEventListener("error", function (event) {
  2948. noManifestFile();
  2949. }, false);
  2950. try {
  2951. xhr.send();
  2952. }
  2953. catch (ex) {
  2954. BABYLON.Tools.Error("Error on XHR send request.");
  2955. that.callbackManifestChecked(false);
  2956. }
  2957. };
  2958. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2959. var _this = this;
  2960. function handleError() {
  2961. that.isSupported = false;
  2962. if (errorCallback)
  2963. errorCallback();
  2964. }
  2965. var that = this;
  2966. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2967. // Your browser doesn't support IndexedDB
  2968. this.isSupported = false;
  2969. if (errorCallback)
  2970. errorCallback();
  2971. }
  2972. else {
  2973. // If the DB hasn't been opened or created yet
  2974. if (!this.db) {
  2975. this.hasReachedQuota = false;
  2976. this.isSupported = true;
  2977. var request = this.idbFactory.open("babylonjs", 1);
  2978. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2979. request.onerror = function (event) {
  2980. handleError();
  2981. };
  2982. // executes when a version change transaction cannot complete due to other active transactions
  2983. request.onblocked = function (event) {
  2984. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2985. handleError();
  2986. };
  2987. // DB has been opened successfully
  2988. request.onsuccess = function (event) {
  2989. _this.db = request.result;
  2990. successCallback();
  2991. };
  2992. // Initialization of the DB. Creating Scenes & Textures stores
  2993. request.onupgradeneeded = function (event) {
  2994. _this.db = (event.target).result;
  2995. try {
  2996. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  2997. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  2998. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  2999. }
  3000. catch (ex) {
  3001. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3002. handleError();
  3003. }
  3004. };
  3005. }
  3006. else {
  3007. if (successCallback)
  3008. successCallback();
  3009. }
  3010. }
  3011. };
  3012. Database.prototype.loadImageFromDB = function (url, image) {
  3013. var _this = this;
  3014. var completeURL = Database.ReturnFullUrlLocation(url);
  3015. var saveAndLoadImage = function () {
  3016. if (!_this.hasReachedQuota && _this.db !== null) {
  3017. // the texture is not yet in the DB, let's try to save it
  3018. _this._saveImageIntoDBAsync(completeURL, image);
  3019. }
  3020. else {
  3021. image.src = url;
  3022. }
  3023. };
  3024. if (!this.mustUpdateRessources) {
  3025. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3026. }
  3027. else {
  3028. saveAndLoadImage();
  3029. }
  3030. };
  3031. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3032. if (this.isSupported && this.db !== null) {
  3033. var texture;
  3034. var transaction = this.db.transaction(["textures"]);
  3035. transaction.onabort = function (event) {
  3036. image.src = url;
  3037. };
  3038. transaction.oncomplete = function (event) {
  3039. var blobTextureURL;
  3040. if (texture) {
  3041. var URL = window.URL || window.webkitURL;
  3042. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3043. image.onerror = function () {
  3044. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3045. image.src = url;
  3046. };
  3047. image.src = blobTextureURL;
  3048. }
  3049. else {
  3050. notInDBCallback();
  3051. }
  3052. };
  3053. var getRequest = transaction.objectStore("textures").get(url);
  3054. getRequest.onsuccess = function (event) {
  3055. texture = (event.target).result;
  3056. };
  3057. getRequest.onerror = function (event) {
  3058. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3059. image.src = url;
  3060. };
  3061. }
  3062. else {
  3063. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3064. image.src = url;
  3065. }
  3066. };
  3067. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3068. var _this = this;
  3069. if (this.isSupported) {
  3070. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3071. var generateBlobUrl = function () {
  3072. var blobTextureURL;
  3073. if (blob) {
  3074. var URL = window.URL || window.webkitURL;
  3075. try {
  3076. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3077. }
  3078. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3079. catch (ex) {
  3080. blobTextureURL = URL.createObjectURL(blob);
  3081. }
  3082. }
  3083. image.src = blobTextureURL;
  3084. };
  3085. if (Database.IsUASupportingBlobStorage) {
  3086. var xhr = new XMLHttpRequest(), blob;
  3087. xhr.open("GET", url, true);
  3088. xhr.responseType = "blob";
  3089. xhr.addEventListener("load", function () {
  3090. if (xhr.status === 200) {
  3091. // Blob as response (XHR2)
  3092. blob = xhr.response;
  3093. var transaction = _this.db.transaction(["textures"], "readwrite");
  3094. // the transaction could abort because of a QuotaExceededError error
  3095. transaction.onabort = function (event) {
  3096. try {
  3097. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3098. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3099. this.hasReachedQuota = true;
  3100. }
  3101. }
  3102. catch (ex) { }
  3103. generateBlobUrl();
  3104. };
  3105. transaction.oncomplete = function (event) {
  3106. generateBlobUrl();
  3107. };
  3108. var newTexture = { textureUrl: url, data: blob };
  3109. try {
  3110. // Put the blob into the dabase
  3111. var addRequest = transaction.objectStore("textures").put(newTexture);
  3112. addRequest.onsuccess = function (event) {
  3113. };
  3114. addRequest.onerror = function (event) {
  3115. generateBlobUrl();
  3116. };
  3117. }
  3118. catch (ex) {
  3119. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3120. if (ex.code === 25) {
  3121. Database.IsUASupportingBlobStorage = false;
  3122. }
  3123. image.src = url;
  3124. }
  3125. }
  3126. else {
  3127. image.src = url;
  3128. }
  3129. }, false);
  3130. xhr.addEventListener("error", function (event) {
  3131. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3132. image.src = url;
  3133. }, false);
  3134. xhr.send();
  3135. }
  3136. else {
  3137. image.src = url;
  3138. }
  3139. }
  3140. else {
  3141. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3142. image.src = url;
  3143. }
  3144. };
  3145. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3146. var _this = this;
  3147. var updateVersion = function (event) {
  3148. // the version is not yet in the DB or we need to update it
  3149. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3150. };
  3151. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3152. };
  3153. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3154. var _this = this;
  3155. if (this.isSupported) {
  3156. var version;
  3157. try {
  3158. var transaction = this.db.transaction(["versions"]);
  3159. transaction.oncomplete = function (event) {
  3160. if (version) {
  3161. // If the version in the JSON file is > than the version in DB
  3162. if (_this.manifestVersionFound > version.data) {
  3163. _this.mustUpdateRessources = true;
  3164. updateInDBCallback();
  3165. }
  3166. else {
  3167. callback(version.data);
  3168. }
  3169. }
  3170. else {
  3171. _this.mustUpdateRessources = true;
  3172. updateInDBCallback();
  3173. }
  3174. };
  3175. transaction.onabort = function (event) {
  3176. callback(-1);
  3177. };
  3178. var getRequest = transaction.objectStore("versions").get(url);
  3179. getRequest.onsuccess = function (event) {
  3180. version = (event.target).result;
  3181. };
  3182. getRequest.onerror = function (event) {
  3183. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3184. callback(-1);
  3185. };
  3186. }
  3187. catch (ex) {
  3188. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3189. callback(-1);
  3190. }
  3191. }
  3192. else {
  3193. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3194. callback(-1);
  3195. }
  3196. };
  3197. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3198. var _this = this;
  3199. if (this.isSupported && !this.hasReachedQuota) {
  3200. try {
  3201. // Open a transaction to the database
  3202. var transaction = this.db.transaction(["versions"], "readwrite");
  3203. // the transaction could abort because of a QuotaExceededError error
  3204. transaction.onabort = function (event) {
  3205. try {
  3206. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3207. _this.hasReachedQuota = true;
  3208. }
  3209. }
  3210. catch (ex) { }
  3211. callback(-1);
  3212. };
  3213. transaction.oncomplete = function (event) {
  3214. callback(_this.manifestVersionFound);
  3215. };
  3216. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3217. // Put the scene into the database
  3218. var addRequest = transaction.objectStore("versions").put(newVersion);
  3219. addRequest.onsuccess = function (event) {
  3220. };
  3221. addRequest.onerror = function (event) {
  3222. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3223. };
  3224. }
  3225. catch (ex) {
  3226. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3227. callback(-1);
  3228. }
  3229. }
  3230. else {
  3231. callback(-1);
  3232. }
  3233. };
  3234. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3235. var _this = this;
  3236. var completeUrl = Database.ReturnFullUrlLocation(url);
  3237. var saveAndLoadFile = function (event) {
  3238. // the scene is not yet in the DB, let's try to save it
  3239. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3240. };
  3241. this._checkVersionFromDB(completeUrl, function (version) {
  3242. if (version !== -1) {
  3243. if (!_this.mustUpdateRessources) {
  3244. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3245. }
  3246. else {
  3247. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3248. }
  3249. }
  3250. else {
  3251. errorCallback();
  3252. }
  3253. });
  3254. };
  3255. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3256. if (this.isSupported) {
  3257. var targetStore;
  3258. if (url.indexOf(".babylon") !== -1) {
  3259. targetStore = "scenes";
  3260. }
  3261. else {
  3262. targetStore = "textures";
  3263. }
  3264. var file;
  3265. var transaction = this.db.transaction([targetStore]);
  3266. transaction.oncomplete = function (event) {
  3267. if (file) {
  3268. callback(file.data);
  3269. }
  3270. else {
  3271. notInDBCallback();
  3272. }
  3273. };
  3274. transaction.onabort = function (event) {
  3275. notInDBCallback();
  3276. };
  3277. var getRequest = transaction.objectStore(targetStore).get(url);
  3278. getRequest.onsuccess = function (event) {
  3279. file = (event.target).result;
  3280. };
  3281. getRequest.onerror = function (event) {
  3282. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3283. notInDBCallback();
  3284. };
  3285. }
  3286. else {
  3287. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3288. callback();
  3289. }
  3290. };
  3291. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3292. var _this = this;
  3293. if (this.isSupported) {
  3294. var targetStore;
  3295. if (url.indexOf(".babylon") !== -1) {
  3296. targetStore = "scenes";
  3297. }
  3298. else {
  3299. targetStore = "textures";
  3300. }
  3301. // Create XHR
  3302. var xhr = new XMLHttpRequest(), fileData;
  3303. xhr.open("GET", url, true);
  3304. if (useArrayBuffer) {
  3305. xhr.responseType = "arraybuffer";
  3306. }
  3307. xhr.onprogress = progressCallback;
  3308. xhr.addEventListener("load", function () {
  3309. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3310. // Blob as response (XHR2)
  3311. //fileData = xhr.responseText;
  3312. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3313. if (!_this.hasReachedQuota) {
  3314. // Open a transaction to the database
  3315. var transaction = _this.db.transaction([targetStore], "readwrite");
  3316. // the transaction could abort because of a QuotaExceededError error
  3317. transaction.onabort = function (event) {
  3318. try {
  3319. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3320. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3321. this.hasReachedQuota = true;
  3322. }
  3323. }
  3324. catch (ex) { }
  3325. callback(fileData);
  3326. };
  3327. transaction.oncomplete = function (event) {
  3328. callback(fileData);
  3329. };
  3330. var newFile;
  3331. if (targetStore === "scenes") {
  3332. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3333. }
  3334. else {
  3335. newFile = { textureUrl: url, data: fileData };
  3336. }
  3337. try {
  3338. // Put the scene into the database
  3339. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3340. addRequest.onsuccess = function (event) {
  3341. };
  3342. addRequest.onerror = function (event) {
  3343. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3344. };
  3345. }
  3346. catch (ex) {
  3347. callback(fileData);
  3348. }
  3349. }
  3350. else {
  3351. callback(fileData);
  3352. }
  3353. }
  3354. else {
  3355. callback();
  3356. }
  3357. }, false);
  3358. xhr.addEventListener("error", function (event) {
  3359. BABYLON.Tools.Error("error on XHR request.");
  3360. callback();
  3361. }, false);
  3362. xhr.send();
  3363. }
  3364. else {
  3365. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3366. callback();
  3367. }
  3368. };
  3369. Database.IsUASupportingBlobStorage = true;
  3370. Database.IDBStorageEnabled = true;
  3371. Database.parseURL = function (url) {
  3372. var a = document.createElement('a');
  3373. a.href = url;
  3374. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3375. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3376. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3377. return absLocation;
  3378. };
  3379. Database.ReturnFullUrlLocation = function (url) {
  3380. if (url.indexOf("http:/") === -1) {
  3381. return (Database.parseURL(window.location.href) + url);
  3382. }
  3383. else {
  3384. return url;
  3385. }
  3386. };
  3387. return Database;
  3388. })();
  3389. BABYLON.Database = Database;
  3390. })(BABYLON || (BABYLON = {}));
  3391. var BABYLON;
  3392. (function (BABYLON) {
  3393. var Internals;
  3394. (function (Internals) {
  3395. /*
  3396. * Based on jsTGALoader - Javascript loader for TGA file
  3397. * By Vincent Thibault
  3398. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3399. */
  3400. var TGATools = (function () {
  3401. function TGATools() {
  3402. }
  3403. TGATools.GetTGAHeader = function (data) {
  3404. var offset = 0;
  3405. var header = {
  3406. id_length: data[offset++],
  3407. colormap_type: data[offset++],
  3408. image_type: data[offset++],
  3409. colormap_index: data[offset++] | data[offset++] << 8,
  3410. colormap_length: data[offset++] | data[offset++] << 8,
  3411. colormap_size: data[offset++],
  3412. origin: [
  3413. data[offset++] | data[offset++] << 8,
  3414. data[offset++] | data[offset++] << 8
  3415. ],
  3416. width: data[offset++] | data[offset++] << 8,
  3417. height: data[offset++] | data[offset++] << 8,
  3418. pixel_size: data[offset++],
  3419. flags: data[offset++]
  3420. };
  3421. return header;
  3422. };
  3423. TGATools.UploadContent = function (gl, data) {
  3424. // Not enough data to contain header ?
  3425. if (data.length < 19) {
  3426. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3427. return;
  3428. }
  3429. // Read Header
  3430. var offset = 18;
  3431. var header = TGATools.GetTGAHeader(data);
  3432. // Assume it's a valid Targa file.
  3433. if (header.id_length + offset > data.length) {
  3434. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3435. return;
  3436. }
  3437. // Skip not needed data
  3438. offset += header.id_length;
  3439. var use_rle = false;
  3440. var use_pal = false;
  3441. var use_rgb = false;
  3442. var use_grey = false;
  3443. // Get some informations.
  3444. switch (header.image_type) {
  3445. case TGATools._TYPE_RLE_INDEXED:
  3446. use_rle = true;
  3447. case TGATools._TYPE_INDEXED:
  3448. use_pal = true;
  3449. break;
  3450. case TGATools._TYPE_RLE_RGB:
  3451. use_rle = true;
  3452. case TGATools._TYPE_RGB:
  3453. use_rgb = true;
  3454. break;
  3455. case TGATools._TYPE_RLE_GREY:
  3456. use_rle = true;
  3457. case TGATools._TYPE_GREY:
  3458. use_grey = true;
  3459. break;
  3460. }
  3461. var pixel_data;
  3462. var numAlphaBits = header.flags & 0xf;
  3463. var pixel_size = header.pixel_size >> 3;
  3464. var pixel_total = header.width * header.height * pixel_size;
  3465. // Read palettes
  3466. var palettes;
  3467. if (use_pal) {
  3468. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3469. }
  3470. // Read LRE
  3471. if (use_rle) {
  3472. pixel_data = new Uint8Array(pixel_total);
  3473. var c, count, i;
  3474. var localOffset = 0;
  3475. var pixels = new Uint8Array(pixel_size);
  3476. while (offset < pixel_total && localOffset < pixel_total) {
  3477. c = data[offset++];
  3478. count = (c & 0x7f) + 1;
  3479. // RLE pixels
  3480. if (c & 0x80) {
  3481. // Bind pixel tmp array
  3482. for (i = 0; i < pixel_size; ++i) {
  3483. pixels[i] = data[offset++];
  3484. }
  3485. // Copy pixel array
  3486. for (i = 0; i < count; ++i) {
  3487. pixel_data.set(pixels, localOffset + i * pixel_size);
  3488. }
  3489. localOffset += pixel_size * count;
  3490. }
  3491. else {
  3492. count *= pixel_size;
  3493. for (i = 0; i < count; ++i) {
  3494. pixel_data[localOffset + i] = data[offset++];
  3495. }
  3496. localOffset += count;
  3497. }
  3498. }
  3499. }
  3500. else {
  3501. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3502. }
  3503. // Load to texture
  3504. var x_start, y_start, x_step, y_step, y_end, x_end;
  3505. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3506. default:
  3507. case TGATools._ORIGIN_UL:
  3508. x_start = 0;
  3509. x_step = 1;
  3510. x_end = header.width;
  3511. y_start = 0;
  3512. y_step = 1;
  3513. y_end = header.height;
  3514. break;
  3515. case TGATools._ORIGIN_BL:
  3516. x_start = 0;
  3517. x_step = 1;
  3518. x_end = header.width;
  3519. y_start = header.height - 1;
  3520. y_step = -1;
  3521. y_end = -1;
  3522. break;
  3523. case TGATools._ORIGIN_UR:
  3524. x_start = header.width - 1;
  3525. x_step = -1;
  3526. x_end = -1;
  3527. y_start = 0;
  3528. y_step = 1;
  3529. y_end = header.height;
  3530. break;
  3531. case TGATools._ORIGIN_BR:
  3532. x_start = header.width - 1;
  3533. x_step = -1;
  3534. x_end = -1;
  3535. y_start = header.height - 1;
  3536. y_step = -1;
  3537. y_end = -1;
  3538. break;
  3539. }
  3540. // Load the specify method
  3541. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3542. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3543. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3544. };
  3545. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3546. var image = pixel_data, colormap = palettes;
  3547. var width = header.width, height = header.height;
  3548. var color, i = 0, x, y;
  3549. var imageData = new Uint8Array(width * height * 4);
  3550. for (y = y_start; y !== y_end; y += y_step) {
  3551. for (x = x_start; x !== x_end; x += x_step, i++) {
  3552. color = image[i];
  3553. imageData[(x + width * y) * 4 + 3] = 255;
  3554. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3555. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3556. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3557. }
  3558. }
  3559. return imageData;
  3560. };
  3561. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3562. var image = pixel_data;
  3563. var width = header.width, height = header.height;
  3564. var color, i = 0, x, y;
  3565. var imageData = new Uint8Array(width * height * 4);
  3566. for (y = y_start; y !== y_end; y += y_step) {
  3567. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3568. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3569. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3570. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3571. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3572. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3573. }
  3574. }
  3575. return imageData;
  3576. };
  3577. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3578. var image = pixel_data;
  3579. var width = header.width, height = header.height;
  3580. var i = 0, x, y;
  3581. var imageData = new Uint8Array(width * height * 4);
  3582. for (y = y_start; y !== y_end; y += y_step) {
  3583. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3584. imageData[(x + width * y) * 4 + 3] = 255;
  3585. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3586. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3587. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3588. }
  3589. }
  3590. return imageData;
  3591. };
  3592. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3593. var image = pixel_data;
  3594. var width = header.width, height = header.height;
  3595. var i = 0, x, y;
  3596. var imageData = new Uint8Array(width * height * 4);
  3597. for (y = y_start; y !== y_end; y += y_step) {
  3598. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3599. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3600. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3601. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3602. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3603. }
  3604. }
  3605. return imageData;
  3606. };
  3607. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3608. var image = pixel_data;
  3609. var width = header.width, height = header.height;
  3610. var color, i = 0, x, y;
  3611. var imageData = new Uint8Array(width * height * 4);
  3612. for (y = y_start; y !== y_end; y += y_step) {
  3613. for (x = x_start; x !== x_end; x += x_step, i++) {
  3614. color = image[i];
  3615. imageData[(x + width * y) * 4 + 0] = color;
  3616. imageData[(x + width * y) * 4 + 1] = color;
  3617. imageData[(x + width * y) * 4 + 2] = color;
  3618. imageData[(x + width * y) * 4 + 3] = 255;
  3619. }
  3620. }
  3621. return imageData;
  3622. };
  3623. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3624. var image = pixel_data;
  3625. var width = header.width, height = header.height;
  3626. var i = 0, x, y;
  3627. var imageData = new Uint8Array(width * height * 4);
  3628. for (y = y_start; y !== y_end; y += y_step) {
  3629. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3630. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3631. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3632. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3633. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3634. }
  3635. }
  3636. return imageData;
  3637. };
  3638. TGATools._TYPE_NO_DATA = 0;
  3639. TGATools._TYPE_INDEXED = 1;
  3640. TGATools._TYPE_RGB = 2;
  3641. TGATools._TYPE_GREY = 3;
  3642. TGATools._TYPE_RLE_INDEXED = 9;
  3643. TGATools._TYPE_RLE_RGB = 10;
  3644. TGATools._TYPE_RLE_GREY = 11;
  3645. TGATools._ORIGIN_MASK = 0x30;
  3646. TGATools._ORIGIN_SHIFT = 0x04;
  3647. TGATools._ORIGIN_BL = 0x00;
  3648. TGATools._ORIGIN_BR = 0x01;
  3649. TGATools._ORIGIN_UL = 0x02;
  3650. TGATools._ORIGIN_UR = 0x03;
  3651. return TGATools;
  3652. })();
  3653. Internals.TGATools = TGATools;
  3654. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3655. })(BABYLON || (BABYLON = {}));
  3656. var BABYLON;
  3657. (function (BABYLON) {
  3658. var SmartArray = (function () {
  3659. function SmartArray(capacity) {
  3660. this.length = 0;
  3661. this._duplicateId = 0;
  3662. this.data = new Array(capacity);
  3663. this._id = SmartArray._GlobalId++;
  3664. }
  3665. SmartArray.prototype.push = function (value) {
  3666. this.data[this.length++] = value;
  3667. if (this.length > this.data.length) {
  3668. this.data.length *= 2;
  3669. }
  3670. if (!value.__smartArrayFlags) {
  3671. value.__smartArrayFlags = {};
  3672. }
  3673. value.__smartArrayFlags[this._id] = this._duplicateId;
  3674. };
  3675. SmartArray.prototype.pushNoDuplicate = function (value) {
  3676. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3677. return;
  3678. }
  3679. this.push(value);
  3680. };
  3681. SmartArray.prototype.sort = function (compareFn) {
  3682. this.data.sort(compareFn);
  3683. };
  3684. SmartArray.prototype.reset = function () {
  3685. this.length = 0;
  3686. this._duplicateId++;
  3687. };
  3688. SmartArray.prototype.concat = function (array) {
  3689. if (array.length === 0) {
  3690. return;
  3691. }
  3692. if (this.length + array.length > this.data.length) {
  3693. this.data.length = (this.length + array.length) * 2;
  3694. }
  3695. for (var index = 0; index < array.length; index++) {
  3696. this.data[this.length++] = (array.data || array)[index];
  3697. }
  3698. };
  3699. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3700. if (array.length === 0) {
  3701. return;
  3702. }
  3703. if (this.length + array.length > this.data.length) {
  3704. this.data.length = (this.length + array.length) * 2;
  3705. }
  3706. for (var index = 0; index < array.length; index++) {
  3707. var item = (array.data || array)[index];
  3708. this.pushNoDuplicate(item);
  3709. }
  3710. };
  3711. SmartArray.prototype.indexOf = function (value) {
  3712. var position = this.data.indexOf(value);
  3713. if (position >= this.length) {
  3714. return -1;
  3715. }
  3716. return position;
  3717. };
  3718. // Statics
  3719. SmartArray._GlobalId = 0;
  3720. return SmartArray;
  3721. })();
  3722. BABYLON.SmartArray = SmartArray;
  3723. })(BABYLON || (BABYLON = {}));
  3724. var BABYLON;
  3725. (function (BABYLON) {
  3726. var SmartCollection = (function () {
  3727. function SmartCollection(capacity) {
  3728. if (capacity === void 0) { capacity = 10; }
  3729. this.count = 0;
  3730. this._initialCapacity = capacity;
  3731. this.items = {};
  3732. this._keys = new Array(this._initialCapacity);
  3733. }
  3734. SmartCollection.prototype.add = function (key, item) {
  3735. if (this.items[key] != undefined) {
  3736. return -1;
  3737. }
  3738. this.items[key] = item;
  3739. //literal keys are always strings, but we keep source type of key in _keys array
  3740. this._keys[this.count++] = key;
  3741. if (this.count > this._keys.length) {
  3742. this._keys.length *= 2;
  3743. }
  3744. return this.count;
  3745. };
  3746. SmartCollection.prototype.remove = function (key) {
  3747. if (this.items[key] == undefined) {
  3748. return -1;
  3749. }
  3750. return this.removeItemOfIndex(this.indexOf(key));
  3751. };
  3752. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3753. if (index < this.count && index > -1) {
  3754. delete this.items[this._keys[index]];
  3755. //here, shifting by hand is better optimised than .splice
  3756. while (index < this.count) {
  3757. this._keys[index] = this._keys[index + 1];
  3758. index++;
  3759. }
  3760. }
  3761. else {
  3762. return -1;
  3763. }
  3764. return --this.count;
  3765. };
  3766. SmartCollection.prototype.indexOf = function (key) {
  3767. for (var i = 0; i !== this.count; i++) {
  3768. if (this._keys[i] === key) {
  3769. return i;
  3770. }
  3771. }
  3772. return -1;
  3773. };
  3774. SmartCollection.prototype.item = function (key) {
  3775. return this.items[key];
  3776. };
  3777. SmartCollection.prototype.getAllKeys = function () {
  3778. if (this.count > 0) {
  3779. var keys = new Array(this.count);
  3780. for (var i = 0; i < this.count; i++) {
  3781. keys[i] = this._keys[i];
  3782. }
  3783. return keys;
  3784. }
  3785. else {
  3786. return undefined;
  3787. }
  3788. };
  3789. SmartCollection.prototype.getKeyByIndex = function (index) {
  3790. if (index < this.count && index > -1) {
  3791. return this._keys[index];
  3792. }
  3793. else {
  3794. return undefined;
  3795. }
  3796. };
  3797. SmartCollection.prototype.getItemByIndex = function (index) {
  3798. if (index < this.count && index > -1) {
  3799. return this.items[this._keys[index]];
  3800. }
  3801. else {
  3802. return undefined;
  3803. }
  3804. };
  3805. SmartCollection.prototype.empty = function () {
  3806. if (this.count > 0) {
  3807. this.count = 0;
  3808. this.items = {};
  3809. this._keys = new Array(this._initialCapacity);
  3810. }
  3811. };
  3812. SmartCollection.prototype.forEach = function (block) {
  3813. var key;
  3814. for (key in this.items) {
  3815. if (this.items.hasOwnProperty(key)) {
  3816. block(this.items[key]);
  3817. }
  3818. }
  3819. };
  3820. return SmartCollection;
  3821. })();
  3822. BABYLON.SmartCollection = SmartCollection;
  3823. })(BABYLON || (BABYLON = {}));
  3824. var BABYLON;
  3825. (function (BABYLON) {
  3826. // Screenshots
  3827. var screenshotCanvas;
  3828. var cloneValue = function (source, destinationObject) {
  3829. if (!source)
  3830. return null;
  3831. if (source instanceof BABYLON.Mesh) {
  3832. return null;
  3833. }
  3834. if (source instanceof BABYLON.SubMesh) {
  3835. return source.clone(destinationObject);
  3836. }
  3837. else if (source.clone) {
  3838. return source.clone();
  3839. }
  3840. return null;
  3841. };
  3842. var Tools = (function () {
  3843. function Tools() {
  3844. }
  3845. Tools.ToHex = function (i) {
  3846. var str = i.toString(16);
  3847. if (i <= 15) {
  3848. return ("0" + str).toUpperCase();
  3849. }
  3850. return str.toUpperCase();
  3851. };
  3852. Tools.SetImmediate = function (action) {
  3853. if (window.setImmediate) {
  3854. window.setImmediate(action);
  3855. }
  3856. else {
  3857. setTimeout(action, 1);
  3858. }
  3859. };
  3860. Tools.IsExponentOfTwo = function (value) {
  3861. var count = 1;
  3862. do {
  3863. count *= 2;
  3864. } while (count < value);
  3865. return count === value;
  3866. };
  3867. Tools.GetExponentOfTwo = function (value, max) {
  3868. var count = 1;
  3869. do {
  3870. count *= 2;
  3871. } while (count < value);
  3872. if (count > max)
  3873. count = max;
  3874. return count;
  3875. };
  3876. Tools.GetFilename = function (path) {
  3877. var index = path.lastIndexOf("/");
  3878. if (index < 0)
  3879. return path;
  3880. return path.substring(index + 1);
  3881. };
  3882. Tools.GetDOMTextContent = function (element) {
  3883. var result = "";
  3884. var child = element.firstChild;
  3885. while (child) {
  3886. if (child.nodeType === 3) {
  3887. result += child.textContent;
  3888. }
  3889. child = child.nextSibling;
  3890. }
  3891. return result;
  3892. };
  3893. Tools.ToDegrees = function (angle) {
  3894. return angle * 180 / Math.PI;
  3895. };
  3896. Tools.ToRadians = function (angle) {
  3897. return angle * Math.PI / 180;
  3898. };
  3899. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3900. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3901. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3902. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3903. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3904. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3905. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3906. }
  3907. return {
  3908. minimum: minimum,
  3909. maximum: maximum
  3910. };
  3911. };
  3912. Tools.ExtractMinAndMax = function (positions, start, count) {
  3913. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3914. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3915. for (var index = start; index < start + count; index++) {
  3916. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3917. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3918. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3919. }
  3920. return {
  3921. minimum: minimum,
  3922. maximum: maximum
  3923. };
  3924. };
  3925. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3926. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3927. return undefined;
  3928. return Array.isArray(obj) ? obj : [obj];
  3929. };
  3930. // Misc.
  3931. Tools.GetPointerPrefix = function () {
  3932. var eventPrefix = "pointer";
  3933. // Check if hand.js is referenced or if the browser natively supports pointer events
  3934. if (!navigator.pointerEnabled) {
  3935. eventPrefix = "mouse";
  3936. }
  3937. return eventPrefix;
  3938. };
  3939. Tools.QueueNewFrame = function (func) {
  3940. if (window.requestAnimationFrame)
  3941. window.requestAnimationFrame(func);
  3942. else if (window.msRequestAnimationFrame)
  3943. window.msRequestAnimationFrame(func);
  3944. else if (window.webkitRequestAnimationFrame)
  3945. window.webkitRequestAnimationFrame(func);
  3946. else if (window.mozRequestAnimationFrame)
  3947. window.mozRequestAnimationFrame(func);
  3948. else if (window.oRequestAnimationFrame)
  3949. window.oRequestAnimationFrame(func);
  3950. else {
  3951. window.setTimeout(func, 16);
  3952. }
  3953. };
  3954. Tools.RequestFullscreen = function (element) {
  3955. if (element.requestFullscreen)
  3956. element.requestFullscreen();
  3957. else if (element.msRequestFullscreen)
  3958. element.msRequestFullscreen();
  3959. else if (element.webkitRequestFullscreen)
  3960. element.webkitRequestFullscreen();
  3961. else if (element.mozRequestFullScreen)
  3962. element.mozRequestFullScreen();
  3963. };
  3964. Tools.ExitFullscreen = function () {
  3965. if (document.exitFullscreen) {
  3966. document.exitFullscreen();
  3967. }
  3968. else if (document.mozCancelFullScreen) {
  3969. document.mozCancelFullScreen();
  3970. }
  3971. else if (document.webkitCancelFullScreen) {
  3972. document.webkitCancelFullScreen();
  3973. }
  3974. else if (document.msCancelFullScreen) {
  3975. document.msCancelFullScreen();
  3976. }
  3977. };
  3978. // External files
  3979. Tools.CleanUrl = function (url) {
  3980. url = url.replace(/#/mg, "%23");
  3981. return url;
  3982. };
  3983. Tools.LoadImage = function (url, onload, onerror, database) {
  3984. url = Tools.CleanUrl(url);
  3985. var img = new Image();
  3986. if (url.substr(0, 5) !== "data:")
  3987. img.crossOrigin = 'anonymous';
  3988. img.onload = function () {
  3989. onload(img);
  3990. };
  3991. img.onerror = function (err) {
  3992. Tools.Error("Error while trying to load texture: " + url);
  3993. 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";
  3994. onload(img);
  3995. };
  3996. var noIndexedDB = function () {
  3997. img.src = url;
  3998. };
  3999. var loadFromIndexedDB = function () {
  4000. database.loadImageFromDB(url, img);
  4001. };
  4002. //ANY database to do!
  4003. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4004. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4005. }
  4006. else {
  4007. if (url.indexOf("file:") === -1) {
  4008. noIndexedDB();
  4009. }
  4010. else {
  4011. try {
  4012. var textureName = url.substring(5);
  4013. var blobURL;
  4014. try {
  4015. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4016. }
  4017. catch (ex) {
  4018. // Chrome doesn't support oneTimeOnly parameter
  4019. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4020. }
  4021. img.src = blobURL;
  4022. }
  4023. catch (e) {
  4024. img.src = null;
  4025. }
  4026. }
  4027. }
  4028. return img;
  4029. };
  4030. //ANY
  4031. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4032. url = Tools.CleanUrl(url);
  4033. var noIndexedDB = function () {
  4034. var request = new XMLHttpRequest();
  4035. var loadUrl = Tools.BaseUrl + url;
  4036. request.open('GET', loadUrl, true);
  4037. if (useArrayBuffer) {
  4038. request.responseType = "arraybuffer";
  4039. }
  4040. request.onprogress = progressCallBack;
  4041. request.onreadystatechange = function () {
  4042. if (request.readyState === 4) {
  4043. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4044. callback(!useArrayBuffer ? request.responseText : request.response);
  4045. }
  4046. else {
  4047. if (onError) {
  4048. onError();
  4049. }
  4050. else {
  4051. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4052. }
  4053. }
  4054. }
  4055. };
  4056. request.send(null);
  4057. };
  4058. var loadFromIndexedDB = function () {
  4059. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4060. };
  4061. if (url.indexOf("file:") !== -1) {
  4062. var fileName = url.substring(5);
  4063. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4064. }
  4065. else {
  4066. // Caching all files
  4067. if (database && database.enableSceneOffline) {
  4068. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4069. }
  4070. else {
  4071. noIndexedDB();
  4072. }
  4073. }
  4074. };
  4075. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4076. var reader = new FileReader();
  4077. reader.onload = function (e) {
  4078. //target doesn't have result from ts 1.3
  4079. callback(e.target['result']);
  4080. };
  4081. reader.onprogress = progressCallback;
  4082. reader.readAsDataURL(fileToLoad);
  4083. };
  4084. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4085. var reader = new FileReader();
  4086. reader.onerror = function (e) {
  4087. Tools.Log("Error while reading file: " + fileToLoad.name);
  4088. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4089. };
  4090. reader.onload = function (e) {
  4091. //target doesn't have result from ts 1.3
  4092. callback(e.target['result']);
  4093. };
  4094. reader.onprogress = progressCallBack;
  4095. if (!useArrayBuffer) {
  4096. // Asynchronous read
  4097. reader.readAsText(fileToLoad);
  4098. }
  4099. else {
  4100. reader.readAsArrayBuffer(fileToLoad);
  4101. }
  4102. };
  4103. //returns a downloadable url to a file content.
  4104. Tools.FileAsURL = function (content) {
  4105. var fileBlob = new Blob([content]);
  4106. var url = window.URL || window.webkitURL;
  4107. var link = url.createObjectURL(fileBlob);
  4108. return link;
  4109. };
  4110. // Misc.
  4111. Tools.Clamp = function (value, min, max) {
  4112. if (min === void 0) { min = 0; }
  4113. if (max === void 0) { max = 1; }
  4114. return Math.min(max, Math.max(min, value));
  4115. };
  4116. // Returns -1 when value is a negative number and
  4117. // +1 when value is a positive number.
  4118. Tools.Sign = function (value) {
  4119. value = +value; // convert to a number
  4120. if (value === 0 || isNaN(value))
  4121. return value;
  4122. return value > 0 ? 1 : -1;
  4123. };
  4124. Tools.Format = function (value, decimals) {
  4125. if (decimals === void 0) { decimals = 2; }
  4126. return value.toFixed(decimals);
  4127. };
  4128. Tools.CheckExtends = function (v, min, max) {
  4129. if (v.x < min.x)
  4130. min.x = v.x;
  4131. if (v.y < min.y)
  4132. min.y = v.y;
  4133. if (v.z < min.z)
  4134. min.z = v.z;
  4135. if (v.x > max.x)
  4136. max.x = v.x;
  4137. if (v.y > max.y)
  4138. max.y = v.y;
  4139. if (v.z > max.z)
  4140. max.z = v.z;
  4141. };
  4142. Tools.WithinEpsilon = function (a, b, epsilon) {
  4143. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4144. var num = a - b;
  4145. return -epsilon <= num && num <= epsilon;
  4146. };
  4147. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4148. for (var prop in source) {
  4149. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4150. continue;
  4151. }
  4152. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4153. continue;
  4154. }
  4155. var sourceValue = source[prop];
  4156. var typeOfSourceValue = typeof sourceValue;
  4157. if (typeOfSourceValue === "function") {
  4158. continue;
  4159. }
  4160. if (typeOfSourceValue === "object") {
  4161. if (sourceValue instanceof Array) {
  4162. destination[prop] = [];
  4163. if (sourceValue.length > 0) {
  4164. if (typeof sourceValue[0] == "object") {
  4165. for (var index = 0; index < sourceValue.length; index++) {
  4166. var clonedValue = cloneValue(sourceValue[index], destination);
  4167. if (destination[prop].indexOf(clonedValue) === -1) {
  4168. destination[prop].push(clonedValue);
  4169. }
  4170. }
  4171. }
  4172. else {
  4173. destination[prop] = sourceValue.slice(0);
  4174. }
  4175. }
  4176. }
  4177. else {
  4178. destination[prop] = cloneValue(sourceValue, destination);
  4179. }
  4180. }
  4181. else {
  4182. destination[prop] = sourceValue;
  4183. }
  4184. }
  4185. };
  4186. Tools.IsEmpty = function (obj) {
  4187. for (var i in obj) {
  4188. return false;
  4189. }
  4190. return true;
  4191. };
  4192. Tools.RegisterTopRootEvents = function (events) {
  4193. for (var index = 0; index < events.length; index++) {
  4194. var event = events[index];
  4195. window.addEventListener(event.name, event.handler, false);
  4196. try {
  4197. if (window.parent) {
  4198. window.parent.addEventListener(event.name, event.handler, false);
  4199. }
  4200. }
  4201. catch (e) {
  4202. }
  4203. }
  4204. };
  4205. Tools.UnregisterTopRootEvents = function (events) {
  4206. for (var index = 0; index < events.length; index++) {
  4207. var event = events[index];
  4208. window.removeEventListener(event.name, event.handler);
  4209. try {
  4210. if (window.parent) {
  4211. window.parent.removeEventListener(event.name, event.handler);
  4212. }
  4213. }
  4214. catch (e) {
  4215. }
  4216. }
  4217. };
  4218. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4219. // Read the contents of the framebuffer
  4220. var numberOfChannelsByLine = width * 4;
  4221. var halfHeight = height / 2;
  4222. //Reading datas from WebGL
  4223. var data = engine.readPixels(0, 0, width, height);
  4224. //To flip image on Y axis.
  4225. for (var i = 0; i < halfHeight; i++) {
  4226. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4227. var currentCell = j + i * numberOfChannelsByLine;
  4228. var targetLine = height - i - 1;
  4229. var targetCell = j + targetLine * numberOfChannelsByLine;
  4230. var temp = data[currentCell];
  4231. data[currentCell] = data[targetCell];
  4232. data[targetCell] = temp;
  4233. }
  4234. }
  4235. // Create a 2D canvas to store the result
  4236. if (!screenshotCanvas) {
  4237. screenshotCanvas = document.createElement('canvas');
  4238. }
  4239. screenshotCanvas.width = width;
  4240. screenshotCanvas.height = height;
  4241. var context = screenshotCanvas.getContext('2d');
  4242. // Copy the pixels to a 2D canvas
  4243. var imageData = context.createImageData(width, height);
  4244. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4245. var castData = imageData.data;
  4246. castData.set(data);
  4247. context.putImageData(imageData, 0, 0);
  4248. var base64Image = screenshotCanvas.toDataURL();
  4249. if (successCallback) {
  4250. successCallback(base64Image);
  4251. }
  4252. else {
  4253. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4254. if (("download" in document.createElement("a"))) {
  4255. var a = window.document.createElement("a");
  4256. a.href = base64Image;
  4257. var date = new Date();
  4258. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4259. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4260. window.document.body.appendChild(a);
  4261. a.addEventListener("click", function () {
  4262. a.parentElement.removeChild(a);
  4263. });
  4264. a.click();
  4265. }
  4266. else {
  4267. var newWindow = window.open("");
  4268. var img = newWindow.document.createElement("img");
  4269. img.src = base64Image;
  4270. newWindow.document.body.appendChild(img);
  4271. }
  4272. }
  4273. };
  4274. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4275. var width;
  4276. var height;
  4277. //If a precision value is specified
  4278. if (size.precision) {
  4279. width = Math.round(engine.getRenderWidth() * size.precision);
  4280. height = Math.round(width / engine.getAspectRatio(camera));
  4281. size = { width: width, height: height };
  4282. }
  4283. else if (size.width && size.height) {
  4284. width = size.width;
  4285. height = size.height;
  4286. }
  4287. else if (size.width && !size.height) {
  4288. width = size.width;
  4289. height = Math.round(width / engine.getAspectRatio(camera));
  4290. size = { width: width, height: height };
  4291. }
  4292. else if (size.height && !size.width) {
  4293. height = size.height;
  4294. width = Math.round(height * engine.getAspectRatio(camera));
  4295. size = { width: width, height: height };
  4296. }
  4297. else if (!isNaN(size)) {
  4298. height = size;
  4299. width = size;
  4300. }
  4301. else {
  4302. Tools.Error("Invalid 'size' parameter !");
  4303. return;
  4304. }
  4305. var scene = camera.getScene();
  4306. var previousCamera = null;
  4307. if (scene.activeCamera !== camera) {
  4308. previousCamera = scene.activeCamera;
  4309. scene.activeCamera = camera;
  4310. }
  4311. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4312. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4313. texture.renderList = scene.meshes;
  4314. texture.onAfterRender = function () {
  4315. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4316. };
  4317. scene.incrementRenderId();
  4318. texture.render(true);
  4319. texture.dispose();
  4320. if (previousCamera) {
  4321. scene.activeCamera = previousCamera;
  4322. }
  4323. };
  4324. // XHR response validator for local file scenario
  4325. Tools.ValidateXHRData = function (xhr, dataType) {
  4326. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4327. if (dataType === void 0) { dataType = 7; }
  4328. try {
  4329. if (dataType & 1) {
  4330. if (xhr.responseText && xhr.responseText.length > 0) {
  4331. return true;
  4332. }
  4333. else if (dataType === 1) {
  4334. return false;
  4335. }
  4336. }
  4337. if (dataType & 2) {
  4338. // Check header width and height since there is no "TGA" magic number
  4339. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4340. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4341. return true;
  4342. }
  4343. else if (dataType === 2) {
  4344. return false;
  4345. }
  4346. }
  4347. if (dataType & 4) {
  4348. // Check for the "DDS" magic number
  4349. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4350. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4351. return true;
  4352. }
  4353. else {
  4354. return false;
  4355. }
  4356. }
  4357. }
  4358. catch (e) {
  4359. }
  4360. return false;
  4361. };
  4362. Object.defineProperty(Tools, "NoneLogLevel", {
  4363. get: function () {
  4364. return Tools._NoneLogLevel;
  4365. },
  4366. enumerable: true,
  4367. configurable: true
  4368. });
  4369. Object.defineProperty(Tools, "MessageLogLevel", {
  4370. get: function () {
  4371. return Tools._MessageLogLevel;
  4372. },
  4373. enumerable: true,
  4374. configurable: true
  4375. });
  4376. Object.defineProperty(Tools, "WarningLogLevel", {
  4377. get: function () {
  4378. return Tools._WarningLogLevel;
  4379. },
  4380. enumerable: true,
  4381. configurable: true
  4382. });
  4383. Object.defineProperty(Tools, "ErrorLogLevel", {
  4384. get: function () {
  4385. return Tools._ErrorLogLevel;
  4386. },
  4387. enumerable: true,
  4388. configurable: true
  4389. });
  4390. Object.defineProperty(Tools, "AllLogLevel", {
  4391. get: function () {
  4392. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4393. },
  4394. enumerable: true,
  4395. configurable: true
  4396. });
  4397. Tools._AddLogEntry = function (entry) {
  4398. Tools._LogCache = entry + Tools._LogCache;
  4399. if (Tools.OnNewCacheEntry) {
  4400. Tools.OnNewCacheEntry(entry);
  4401. }
  4402. };
  4403. Tools._FormatMessage = function (message) {
  4404. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4405. var date = new Date();
  4406. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4407. };
  4408. Tools._LogDisabled = function (message) {
  4409. // nothing to do
  4410. };
  4411. Tools._LogEnabled = function (message) {
  4412. var formattedMessage = Tools._FormatMessage(message);
  4413. console.log("BJS - " + formattedMessage);
  4414. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4415. Tools._AddLogEntry(entry);
  4416. };
  4417. Tools._WarnDisabled = function (message) {
  4418. // nothing to do
  4419. };
  4420. Tools._WarnEnabled = function (message) {
  4421. var formattedMessage = Tools._FormatMessage(message);
  4422. console.warn("BJS - " + formattedMessage);
  4423. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4424. Tools._AddLogEntry(entry);
  4425. };
  4426. Tools._ErrorDisabled = function (message) {
  4427. // nothing to do
  4428. };
  4429. Tools._ErrorEnabled = function (message) {
  4430. Tools.errorsCount++;
  4431. var formattedMessage = Tools._FormatMessage(message);
  4432. console.error("BJS - " + formattedMessage);
  4433. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4434. Tools._AddLogEntry(entry);
  4435. };
  4436. Object.defineProperty(Tools, "LogCache", {
  4437. get: function () {
  4438. return Tools._LogCache;
  4439. },
  4440. enumerable: true,
  4441. configurable: true
  4442. });
  4443. Tools.ClearLogCache = function () {
  4444. Tools._LogCache = "";
  4445. Tools.errorsCount = 0;
  4446. };
  4447. Object.defineProperty(Tools, "LogLevels", {
  4448. set: function (level) {
  4449. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4450. Tools.Log = Tools._LogEnabled;
  4451. }
  4452. else {
  4453. Tools.Log = Tools._LogDisabled;
  4454. }
  4455. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4456. Tools.Warn = Tools._WarnEnabled;
  4457. }
  4458. else {
  4459. Tools.Warn = Tools._WarnDisabled;
  4460. }
  4461. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4462. Tools.Error = Tools._ErrorEnabled;
  4463. }
  4464. else {
  4465. Tools.Error = Tools._ErrorDisabled;
  4466. }
  4467. },
  4468. enumerable: true,
  4469. configurable: true
  4470. });
  4471. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4472. get: function () {
  4473. return Tools._PerformanceNoneLogLevel;
  4474. },
  4475. enumerable: true,
  4476. configurable: true
  4477. });
  4478. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4479. get: function () {
  4480. return Tools._PerformanceUserMarkLogLevel;
  4481. },
  4482. enumerable: true,
  4483. configurable: true
  4484. });
  4485. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4486. get: function () {
  4487. return Tools._PerformanceConsoleLogLevel;
  4488. },
  4489. enumerable: true,
  4490. configurable: true
  4491. });
  4492. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4493. set: function (level) {
  4494. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4495. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4496. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4497. return;
  4498. }
  4499. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4500. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4501. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4502. return;
  4503. }
  4504. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4505. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4506. },
  4507. enumerable: true,
  4508. configurable: true
  4509. });
  4510. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4511. };
  4512. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4513. };
  4514. Tools._StartUserMark = function (counterName, condition) {
  4515. if (condition === void 0) { condition = true; }
  4516. if (!condition || !Tools._performance.mark) {
  4517. return;
  4518. }
  4519. Tools._performance.mark(counterName + "-Begin");
  4520. };
  4521. Tools._EndUserMark = function (counterName, condition) {
  4522. if (condition === void 0) { condition = true; }
  4523. if (!condition || !Tools._performance.mark) {
  4524. return;
  4525. }
  4526. Tools._performance.mark(counterName + "-End");
  4527. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4528. };
  4529. Tools._StartPerformanceConsole = function (counterName, condition) {
  4530. if (condition === void 0) { condition = true; }
  4531. if (!condition) {
  4532. return;
  4533. }
  4534. Tools._StartUserMark(counterName, condition);
  4535. if (console.time) {
  4536. console.time(counterName);
  4537. }
  4538. };
  4539. Tools._EndPerformanceConsole = function (counterName, condition) {
  4540. if (condition === void 0) { condition = true; }
  4541. if (!condition) {
  4542. return;
  4543. }
  4544. Tools._EndUserMark(counterName, condition);
  4545. if (console.time) {
  4546. console.timeEnd(counterName);
  4547. }
  4548. };
  4549. Object.defineProperty(Tools, "Now", {
  4550. get: function () {
  4551. if (window.performance && window.performance.now) {
  4552. return window.performance.now();
  4553. }
  4554. return new Date().getTime();
  4555. },
  4556. enumerable: true,
  4557. configurable: true
  4558. });
  4559. Tools.BaseUrl = "";
  4560. // Logs
  4561. Tools._NoneLogLevel = 0;
  4562. Tools._MessageLogLevel = 1;
  4563. Tools._WarningLogLevel = 2;
  4564. Tools._ErrorLogLevel = 4;
  4565. Tools._LogCache = "";
  4566. Tools.errorsCount = 0;
  4567. Tools.Log = Tools._LogEnabled;
  4568. Tools.Warn = Tools._WarnEnabled;
  4569. Tools.Error = Tools._ErrorEnabled;
  4570. // Performances
  4571. Tools._PerformanceNoneLogLevel = 0;
  4572. Tools._PerformanceUserMarkLogLevel = 1;
  4573. Tools._PerformanceConsoleLogLevel = 2;
  4574. Tools._performance = window.performance;
  4575. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4576. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4577. return Tools;
  4578. })();
  4579. BABYLON.Tools = Tools;
  4580. /**
  4581. * An implementation of a loop for asynchronous functions.
  4582. */
  4583. var AsyncLoop = (function () {
  4584. /**
  4585. * Constroctor.
  4586. * @param iterations the number of iterations.
  4587. * @param _fn the function to run each iteration
  4588. * @param _successCallback the callback that will be called upon succesful execution
  4589. * @param offset starting offset.
  4590. */
  4591. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4592. if (offset === void 0) { offset = 0; }
  4593. this.iterations = iterations;
  4594. this._fn = _fn;
  4595. this._successCallback = _successCallback;
  4596. this.index = offset - 1;
  4597. this._done = false;
  4598. }
  4599. /**
  4600. * Execute the next iteration. Must be called after the last iteration was finished.
  4601. */
  4602. AsyncLoop.prototype.executeNext = function () {
  4603. if (!this._done) {
  4604. if (this.index + 1 < this.iterations) {
  4605. ++this.index;
  4606. this._fn(this);
  4607. }
  4608. else {
  4609. this.breakLoop();
  4610. }
  4611. }
  4612. };
  4613. /**
  4614. * Break the loop and run the success callback.
  4615. */
  4616. AsyncLoop.prototype.breakLoop = function () {
  4617. this._done = true;
  4618. this._successCallback();
  4619. };
  4620. /**
  4621. * Helper function
  4622. */
  4623. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4624. if (offset === void 0) { offset = 0; }
  4625. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4626. loop.executeNext();
  4627. return loop;
  4628. };
  4629. /**
  4630. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4631. * @param iterations total number of iterations
  4632. * @param syncedIterations number of synchronous iterations in each async iteration.
  4633. * @param fn the function to call each iteration.
  4634. * @param callback a success call back that will be called when iterating stops.
  4635. * @param breakFunction a break condition (optional)
  4636. * @param timeout timeout settings for the setTimeout function. default - 0.
  4637. * @constructor
  4638. */
  4639. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4640. if (timeout === void 0) { timeout = 0; }
  4641. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4642. if (breakFunction && breakFunction())
  4643. loop.breakLoop();
  4644. else {
  4645. setTimeout(function () {
  4646. for (var i = 0; i < syncedIterations; ++i) {
  4647. var iteration = (loop.index * syncedIterations) + i;
  4648. if (iteration >= iterations)
  4649. break;
  4650. fn(iteration);
  4651. if (breakFunction && breakFunction()) {
  4652. loop.breakLoop();
  4653. break;
  4654. }
  4655. }
  4656. loop.executeNext();
  4657. }, timeout);
  4658. }
  4659. }, callback);
  4660. };
  4661. return AsyncLoop;
  4662. })();
  4663. BABYLON.AsyncLoop = AsyncLoop;
  4664. })(BABYLON || (BABYLON = {}));
  4665. var BABYLON;
  4666. (function (BABYLON) {
  4667. var _DepthCullingState = (function () {
  4668. function _DepthCullingState() {
  4669. this._isDepthTestDirty = false;
  4670. this._isDepthMaskDirty = false;
  4671. this._isDepthFuncDirty = false;
  4672. this._isCullFaceDirty = false;
  4673. this._isCullDirty = false;
  4674. this._isZOffsetDirty = false;
  4675. }
  4676. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4677. get: function () {
  4678. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4679. },
  4680. enumerable: true,
  4681. configurable: true
  4682. });
  4683. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4684. get: function () {
  4685. return this._zOffset;
  4686. },
  4687. set: function (value) {
  4688. if (this._zOffset === value) {
  4689. return;
  4690. }
  4691. this._zOffset = value;
  4692. this._isZOffsetDirty = true;
  4693. },
  4694. enumerable: true,
  4695. configurable: true
  4696. });
  4697. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4698. get: function () {
  4699. return this._cullFace;
  4700. },
  4701. set: function (value) {
  4702. if (this._cullFace === value) {
  4703. return;
  4704. }
  4705. this._cullFace = value;
  4706. this._isCullFaceDirty = true;
  4707. },
  4708. enumerable: true,
  4709. configurable: true
  4710. });
  4711. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4712. get: function () {
  4713. return this._cull;
  4714. },
  4715. set: function (value) {
  4716. if (this._cull === value) {
  4717. return;
  4718. }
  4719. this._cull = value;
  4720. this._isCullDirty = true;
  4721. },
  4722. enumerable: true,
  4723. configurable: true
  4724. });
  4725. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4726. get: function () {
  4727. return this._depthFunc;
  4728. },
  4729. set: function (value) {
  4730. if (this._depthFunc === value) {
  4731. return;
  4732. }
  4733. this._depthFunc = value;
  4734. this._isDepthFuncDirty = true;
  4735. },
  4736. enumerable: true,
  4737. configurable: true
  4738. });
  4739. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4740. get: function () {
  4741. return this._depthMask;
  4742. },
  4743. set: function (value) {
  4744. if (this._depthMask === value) {
  4745. return;
  4746. }
  4747. this._depthMask = value;
  4748. this._isDepthMaskDirty = true;
  4749. },
  4750. enumerable: true,
  4751. configurable: true
  4752. });
  4753. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4754. get: function () {
  4755. return this._depthTest;
  4756. },
  4757. set: function (value) {
  4758. if (this._depthTest === value) {
  4759. return;
  4760. }
  4761. this._depthTest = value;
  4762. this._isDepthTestDirty = true;
  4763. },
  4764. enumerable: true,
  4765. configurable: true
  4766. });
  4767. _DepthCullingState.prototype.reset = function () {
  4768. this._depthMask = true;
  4769. this._depthTest = true;
  4770. this._depthFunc = null;
  4771. this._cull = null;
  4772. this._cullFace = null;
  4773. this._zOffset = 0;
  4774. this._isDepthTestDirty = true;
  4775. this._isDepthMaskDirty = true;
  4776. this._isDepthFuncDirty = false;
  4777. this._isCullFaceDirty = false;
  4778. this._isCullDirty = false;
  4779. this._isZOffsetDirty = false;
  4780. };
  4781. _DepthCullingState.prototype.apply = function (gl) {
  4782. if (!this.isDirty) {
  4783. return;
  4784. }
  4785. // Cull
  4786. if (this._isCullDirty) {
  4787. if (this.cull) {
  4788. gl.enable(gl.CULL_FACE);
  4789. }
  4790. else {
  4791. gl.disable(gl.CULL_FACE);
  4792. }
  4793. this._isCullDirty = false;
  4794. }
  4795. // Cull face
  4796. if (this._isCullFaceDirty) {
  4797. gl.cullFace(this.cullFace);
  4798. this._isCullFaceDirty = false;
  4799. }
  4800. // Depth mask
  4801. if (this._isDepthMaskDirty) {
  4802. gl.depthMask(this.depthMask);
  4803. this._isDepthMaskDirty = false;
  4804. }
  4805. // Depth test
  4806. if (this._isDepthTestDirty) {
  4807. if (this.depthTest) {
  4808. gl.enable(gl.DEPTH_TEST);
  4809. }
  4810. else {
  4811. gl.disable(gl.DEPTH_TEST);
  4812. }
  4813. this._isDepthTestDirty = false;
  4814. }
  4815. // Depth func
  4816. if (this._isDepthFuncDirty) {
  4817. gl.depthFunc(this.depthFunc);
  4818. this._isDepthFuncDirty = false;
  4819. }
  4820. // zOffset
  4821. if (this._isZOffsetDirty) {
  4822. if (this.zOffset) {
  4823. gl.enable(gl.POLYGON_OFFSET_FILL);
  4824. gl.polygonOffset(this.zOffset, 0);
  4825. }
  4826. else {
  4827. gl.disable(gl.POLYGON_OFFSET_FILL);
  4828. }
  4829. this._isZOffsetDirty = false;
  4830. }
  4831. };
  4832. return _DepthCullingState;
  4833. })();
  4834. BABYLON._DepthCullingState = _DepthCullingState;
  4835. var _AlphaState = (function () {
  4836. function _AlphaState() {
  4837. this._isAlphaBlendDirty = false;
  4838. this._isBlendFunctionParametersDirty = false;
  4839. this._alphaBlend = false;
  4840. this._blendFunctionParameters = new Array(4);
  4841. }
  4842. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4843. get: function () {
  4844. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4845. },
  4846. enumerable: true,
  4847. configurable: true
  4848. });
  4849. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4850. get: function () {
  4851. return this._alphaBlend;
  4852. },
  4853. set: function (value) {
  4854. if (this._alphaBlend === value) {
  4855. return;
  4856. }
  4857. this._alphaBlend = value;
  4858. this._isAlphaBlendDirty = true;
  4859. },
  4860. enumerable: true,
  4861. configurable: true
  4862. });
  4863. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4864. if (this._blendFunctionParameters[0] === value0 &&
  4865. this._blendFunctionParameters[1] === value1 &&
  4866. this._blendFunctionParameters[2] === value2 &&
  4867. this._blendFunctionParameters[3] === value3) {
  4868. return;
  4869. }
  4870. this._blendFunctionParameters[0] = value0;
  4871. this._blendFunctionParameters[1] = value1;
  4872. this._blendFunctionParameters[2] = value2;
  4873. this._blendFunctionParameters[3] = value3;
  4874. this._isBlendFunctionParametersDirty = true;
  4875. };
  4876. _AlphaState.prototype.reset = function () {
  4877. this._alphaBlend = false;
  4878. this._blendFunctionParameters[0] = null;
  4879. this._blendFunctionParameters[1] = null;
  4880. this._blendFunctionParameters[2] = null;
  4881. this._blendFunctionParameters[3] = null;
  4882. this._isAlphaBlendDirty = true;
  4883. this._isBlendFunctionParametersDirty = false;
  4884. };
  4885. _AlphaState.prototype.apply = function (gl) {
  4886. if (!this.isDirty) {
  4887. return;
  4888. }
  4889. // Alpha blend
  4890. if (this._isAlphaBlendDirty) {
  4891. if (this._alphaBlend) {
  4892. gl.enable(gl.BLEND);
  4893. }
  4894. else {
  4895. gl.disable(gl.BLEND);
  4896. }
  4897. this._isAlphaBlendDirty = false;
  4898. }
  4899. // Alpha function
  4900. if (this._isBlendFunctionParametersDirty) {
  4901. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4902. this._isBlendFunctionParametersDirty = false;
  4903. }
  4904. };
  4905. return _AlphaState;
  4906. })();
  4907. BABYLON._AlphaState = _AlphaState;
  4908. var compileShader = function (gl, source, type, defines) {
  4909. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4910. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4911. gl.compileShader(shader);
  4912. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4913. throw new Error(gl.getShaderInfoLog(shader));
  4914. }
  4915. return shader;
  4916. };
  4917. var getWebGLTextureType = function (gl, type) {
  4918. var textureType = gl.UNSIGNED_BYTE;
  4919. if (type === Engine.TEXTURETYPE_FLOAT)
  4920. textureType = gl.FLOAT;
  4921. return textureType;
  4922. };
  4923. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4924. var magFilter = gl.NEAREST;
  4925. var minFilter = gl.NEAREST;
  4926. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4927. magFilter = gl.LINEAR;
  4928. if (generateMipMaps) {
  4929. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  4930. }
  4931. else {
  4932. minFilter = gl.LINEAR;
  4933. }
  4934. }
  4935. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4936. magFilter = gl.LINEAR;
  4937. if (generateMipMaps) {
  4938. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4939. }
  4940. else {
  4941. minFilter = gl.LINEAR;
  4942. }
  4943. }
  4944. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4945. magFilter = gl.NEAREST;
  4946. if (generateMipMaps) {
  4947. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  4948. }
  4949. else {
  4950. minFilter = gl.NEAREST;
  4951. }
  4952. }
  4953. return {
  4954. min: minFilter,
  4955. mag: magFilter
  4956. };
  4957. };
  4958. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  4959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4960. var engine = scene.getEngine();
  4961. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  4962. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  4963. gl.bindTexture(gl.TEXTURE_2D, texture);
  4964. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4965. texture._baseWidth = width;
  4966. texture._baseHeight = height;
  4967. texture._width = potWidth;
  4968. texture._height = potHeight;
  4969. texture.isReady = true;
  4970. processFunction(potWidth, potHeight);
  4971. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  4972. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4973. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4974. if (!noMipmap && !isCompressed) {
  4975. gl.generateMipmap(gl.TEXTURE_2D);
  4976. }
  4977. gl.bindTexture(gl.TEXTURE_2D, null);
  4978. engine.resetTextureCache();
  4979. scene._removePendingData(texture);
  4980. };
  4981. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  4982. var onload = function () {
  4983. loadedImages[index] = img;
  4984. loadedImages._internalCount++;
  4985. scene._removePendingData(img);
  4986. if (loadedImages._internalCount === 6) {
  4987. onfinish(loadedImages);
  4988. }
  4989. };
  4990. var onerror = function () {
  4991. scene._removePendingData(img);
  4992. };
  4993. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4994. scene._addPendingData(img);
  4995. };
  4996. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  4997. var loadedImages = [];
  4998. loadedImages._internalCount = 0;
  4999. for (var index = 0; index < 6; index++) {
  5000. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5001. }
  5002. };
  5003. var EngineCapabilities = (function () {
  5004. function EngineCapabilities() {
  5005. }
  5006. return EngineCapabilities;
  5007. })();
  5008. BABYLON.EngineCapabilities = EngineCapabilities;
  5009. /**
  5010. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5011. */
  5012. var Engine = (function () {
  5013. /**
  5014. * @constructor
  5015. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5016. * @param {boolean} [antialias] - enable antialias
  5017. * @param options - further options to be sent to the getContext function
  5018. */
  5019. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5020. var _this = this;
  5021. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5022. // Public members
  5023. this.isFullscreen = false;
  5024. this.isPointerLock = false;
  5025. this.cullBackFaces = true;
  5026. this.renderEvenInBackground = true;
  5027. // To enable/disable IDB support and avoid XHR on .manifest
  5028. this.enableOfflineSupport = true;
  5029. this.scenes = new Array();
  5030. this._windowIsBackground = false;
  5031. this._drawCalls = 0;
  5032. this._renderingQueueLaunched = false;
  5033. this._activeRenderLoops = [];
  5034. // FPS
  5035. this.fpsRange = 60;
  5036. this.previousFramesDuration = [];
  5037. this.fps = 60;
  5038. this.deltaTime = 0;
  5039. // States
  5040. this._depthCullingState = new _DepthCullingState();
  5041. this._alphaState = new _AlphaState();
  5042. this._alphaMode = Engine.ALPHA_DISABLE;
  5043. // Cache
  5044. this._loadedTexturesCache = new Array();
  5045. this._maxTextureChannels = 16;
  5046. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5047. this._compiledEffects = {};
  5048. this._uintIndicesCurrentlySet = false;
  5049. this._renderingCanvas = canvas;
  5050. options = options || {};
  5051. options.antialias = antialias;
  5052. if (options.preserveDrawingBuffer === undefined) {
  5053. options.preserveDrawingBuffer = false;
  5054. }
  5055. // GL
  5056. try {
  5057. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5058. }
  5059. catch (e) {
  5060. throw new Error("WebGL not supported");
  5061. }
  5062. if (!this._gl) {
  5063. throw new Error("WebGL not supported");
  5064. }
  5065. this._onBlur = function () {
  5066. _this._windowIsBackground = true;
  5067. };
  5068. this._onFocus = function () {
  5069. _this._windowIsBackground = false;
  5070. };
  5071. window.addEventListener("blur", this._onBlur);
  5072. window.addEventListener("focus", this._onFocus);
  5073. // Viewport
  5074. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5075. this.resize();
  5076. // Caps
  5077. this._caps = new EngineCapabilities();
  5078. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5079. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5080. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5081. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5082. // Infos
  5083. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5084. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5085. if (rendererInfo != null) {
  5086. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5087. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5088. }
  5089. if (!this._glVendor) {
  5090. this._glVendor = "Unknown vendor";
  5091. }
  5092. if (!this._glRenderer) {
  5093. this._glRenderer = "Unknown renderer";
  5094. }
  5095. // Extensions
  5096. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5097. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5098. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5099. 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');
  5100. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5101. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5102. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5103. this._caps.highPrecisionShaderSupported = true;
  5104. if (this._gl.getShaderPrecisionFormat) {
  5105. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5106. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5107. }
  5108. // Depth buffer
  5109. this.setDepthBuffer(true);
  5110. this.setDepthFunctionToLessOrEqual();
  5111. this.setDepthWrite(true);
  5112. // Fullscreen
  5113. this._onFullscreenChange = function () {
  5114. if (document.fullscreen !== undefined) {
  5115. _this.isFullscreen = document.fullscreen;
  5116. }
  5117. else if (document.mozFullScreen !== undefined) {
  5118. _this.isFullscreen = document.mozFullScreen;
  5119. }
  5120. else if (document.webkitIsFullScreen !== undefined) {
  5121. _this.isFullscreen = document.webkitIsFullScreen;
  5122. }
  5123. else if (document.msIsFullScreen !== undefined) {
  5124. _this.isFullscreen = document.msIsFullScreen;
  5125. }
  5126. // Pointer lock
  5127. if (_this.isFullscreen && _this._pointerLockRequested) {
  5128. canvas.requestPointerLock = canvas.requestPointerLock ||
  5129. canvas.msRequestPointerLock ||
  5130. canvas.mozRequestPointerLock ||
  5131. canvas.webkitRequestPointerLock;
  5132. if (canvas.requestPointerLock) {
  5133. canvas.requestPointerLock();
  5134. }
  5135. }
  5136. };
  5137. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5138. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5139. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5140. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5141. // Pointer lock
  5142. this._onPointerLockChange = function () {
  5143. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5144. document.webkitPointerLockElement === canvas ||
  5145. document.msPointerLockElement === canvas ||
  5146. document.pointerLockElement === canvas);
  5147. };
  5148. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5149. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5150. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5151. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5152. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5153. Engine.audioEngine = new BABYLON.AudioEngine();
  5154. }
  5155. //default loading screen
  5156. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5157. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5158. }
  5159. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5160. get: function () {
  5161. return Engine._ALPHA_DISABLE;
  5162. },
  5163. enumerable: true,
  5164. configurable: true
  5165. });
  5166. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5167. get: function () {
  5168. return Engine._ALPHA_ONEONE;
  5169. },
  5170. enumerable: true,
  5171. configurable: true
  5172. });
  5173. Object.defineProperty(Engine, "ALPHA_ADD", {
  5174. get: function () {
  5175. return Engine._ALPHA_ADD;
  5176. },
  5177. enumerable: true,
  5178. configurable: true
  5179. });
  5180. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5181. get: function () {
  5182. return Engine._ALPHA_COMBINE;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5188. get: function () {
  5189. return Engine._ALPHA_SUBTRACT;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5195. get: function () {
  5196. return Engine._ALPHA_MULTIPLY;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5202. get: function () {
  5203. return Engine._ALPHA_MAXIMIZED;
  5204. },
  5205. enumerable: true,
  5206. configurable: true
  5207. });
  5208. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5209. get: function () {
  5210. return Engine._DELAYLOADSTATE_NONE;
  5211. },
  5212. enumerable: true,
  5213. configurable: true
  5214. });
  5215. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5216. get: function () {
  5217. return Engine._DELAYLOADSTATE_LOADED;
  5218. },
  5219. enumerable: true,
  5220. configurable: true
  5221. });
  5222. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5223. get: function () {
  5224. return Engine._DELAYLOADSTATE_LOADING;
  5225. },
  5226. enumerable: true,
  5227. configurable: true
  5228. });
  5229. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5230. get: function () {
  5231. return Engine._DELAYLOADSTATE_NOTLOADED;
  5232. },
  5233. enumerable: true,
  5234. configurable: true
  5235. });
  5236. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5237. get: function () {
  5238. return Engine._TEXTUREFORMAT_ALPHA;
  5239. },
  5240. enumerable: true,
  5241. configurable: true
  5242. });
  5243. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5244. get: function () {
  5245. return Engine._TEXTUREFORMAT_LUMINANCE;
  5246. },
  5247. enumerable: true,
  5248. configurable: true
  5249. });
  5250. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5251. get: function () {
  5252. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5253. },
  5254. enumerable: true,
  5255. configurable: true
  5256. });
  5257. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5258. get: function () {
  5259. return Engine._TEXTUREFORMAT_RGB;
  5260. },
  5261. enumerable: true,
  5262. configurable: true
  5263. });
  5264. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5265. get: function () {
  5266. return Engine._TEXTUREFORMAT_RGBA;
  5267. },
  5268. enumerable: true,
  5269. configurable: true
  5270. });
  5271. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5272. get: function () {
  5273. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5274. },
  5275. enumerable: true,
  5276. configurable: true
  5277. });
  5278. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5279. get: function () {
  5280. return Engine._TEXTURETYPE_FLOAT;
  5281. },
  5282. enumerable: true,
  5283. configurable: true
  5284. });
  5285. Object.defineProperty(Engine, "Version", {
  5286. get: function () {
  5287. return "2.3.0-alpha";
  5288. },
  5289. enumerable: true,
  5290. configurable: true
  5291. });
  5292. Engine.prototype._prepareWorkingCanvas = function () {
  5293. if (this._workingCanvas) {
  5294. return;
  5295. }
  5296. this._workingCanvas = document.createElement("canvas");
  5297. this._workingContext = this._workingCanvas.getContext("2d");
  5298. };
  5299. Engine.prototype.resetTextureCache = function () {
  5300. for (var index = 0; index < this._maxTextureChannels; index++) {
  5301. this._activeTexturesCache[index] = null;
  5302. }
  5303. };
  5304. Engine.prototype.getGlInfo = function () {
  5305. return {
  5306. vendor: this._glVendor,
  5307. renderer: this._glRenderer,
  5308. version: this._glVersion
  5309. };
  5310. };
  5311. Engine.prototype.getAspectRatio = function (camera) {
  5312. var viewport = camera.viewport;
  5313. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5314. };
  5315. Engine.prototype.getRenderWidth = function () {
  5316. if (this._currentRenderTarget) {
  5317. return this._currentRenderTarget._width;
  5318. }
  5319. return this._renderingCanvas.width;
  5320. };
  5321. Engine.prototype.getRenderHeight = function () {
  5322. if (this._currentRenderTarget) {
  5323. return this._currentRenderTarget._height;
  5324. }
  5325. return this._renderingCanvas.height;
  5326. };
  5327. Engine.prototype.getRenderingCanvas = function () {
  5328. return this._renderingCanvas;
  5329. };
  5330. Engine.prototype.getRenderingCanvasClientRect = function () {
  5331. return this._renderingCanvas.getBoundingClientRect();
  5332. };
  5333. Engine.prototype.setHardwareScalingLevel = function (level) {
  5334. this._hardwareScalingLevel = level;
  5335. this.resize();
  5336. };
  5337. Engine.prototype.getHardwareScalingLevel = function () {
  5338. return this._hardwareScalingLevel;
  5339. };
  5340. Engine.prototype.getLoadedTexturesCache = function () {
  5341. return this._loadedTexturesCache;
  5342. };
  5343. Engine.prototype.getCaps = function () {
  5344. return this._caps;
  5345. };
  5346. Object.defineProperty(Engine.prototype, "drawCalls", {
  5347. get: function () {
  5348. return this._drawCalls;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. // Methods
  5354. Engine.prototype.resetDrawCalls = function () {
  5355. this._drawCalls = 0;
  5356. };
  5357. Engine.prototype.setDepthFunctionToGreater = function () {
  5358. this._depthCullingState.depthFunc = this._gl.GREATER;
  5359. };
  5360. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5361. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5362. };
  5363. Engine.prototype.setDepthFunctionToLess = function () {
  5364. this._depthCullingState.depthFunc = this._gl.LESS;
  5365. };
  5366. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5367. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5368. };
  5369. /**
  5370. * stop executing a render loop function and remove it from the execution array
  5371. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5372. */
  5373. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5374. if (!renderFunction) {
  5375. this._activeRenderLoops = [];
  5376. return;
  5377. }
  5378. var index = this._activeRenderLoops.indexOf(renderFunction);
  5379. if (index >= 0) {
  5380. this._activeRenderLoops.splice(index, 1);
  5381. }
  5382. };
  5383. Engine.prototype._renderLoop = function () {
  5384. var shouldRender = true;
  5385. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5386. shouldRender = false;
  5387. }
  5388. if (shouldRender) {
  5389. // Start new frame
  5390. this.beginFrame();
  5391. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5392. var renderFunction = this._activeRenderLoops[index];
  5393. renderFunction();
  5394. }
  5395. // Present
  5396. this.endFrame();
  5397. }
  5398. if (this._activeRenderLoops.length > 0) {
  5399. // Register new frame
  5400. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5401. }
  5402. else {
  5403. this._renderingQueueLaunched = false;
  5404. }
  5405. };
  5406. /**
  5407. * Register and execute a render loop. The engine can have more than one render function.
  5408. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5409. * @example
  5410. * engine.runRenderLoop(function () {
  5411. * scene.render()
  5412. * })
  5413. */
  5414. Engine.prototype.runRenderLoop = function (renderFunction) {
  5415. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5416. return;
  5417. }
  5418. this._activeRenderLoops.push(renderFunction);
  5419. if (!this._renderingQueueLaunched) {
  5420. this._renderingQueueLaunched = true;
  5421. this._bindedRenderFunction = this._renderLoop.bind(this);
  5422. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5423. }
  5424. };
  5425. /**
  5426. * Toggle full screen mode.
  5427. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5428. */
  5429. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5430. if (this.isFullscreen) {
  5431. BABYLON.Tools.ExitFullscreen();
  5432. }
  5433. else {
  5434. this._pointerLockRequested = requestPointerLock;
  5435. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5436. }
  5437. };
  5438. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5439. this.applyStates();
  5440. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5441. if (this._depthCullingState.depthMask) {
  5442. this._gl.clearDepth(1.0);
  5443. }
  5444. var mode = 0;
  5445. if (backBuffer)
  5446. mode |= this._gl.COLOR_BUFFER_BIT;
  5447. if (depthStencil && this._depthCullingState.depthMask)
  5448. mode |= this._gl.DEPTH_BUFFER_BIT;
  5449. this._gl.clear(mode);
  5450. };
  5451. /**
  5452. * Set the WebGL's viewport
  5453. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5454. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5455. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5456. */
  5457. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5458. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5459. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5460. var x = viewport.x || 0;
  5461. var y = viewport.y || 0;
  5462. this._cachedViewport = viewport;
  5463. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5464. };
  5465. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5466. this._cachedViewport = null;
  5467. this._gl.viewport(x, y, width, height);
  5468. };
  5469. Engine.prototype.beginFrame = function () {
  5470. this._measureFps();
  5471. };
  5472. Engine.prototype.endFrame = function () {
  5473. //this.flushFramebuffer();
  5474. };
  5475. /**
  5476. * resize the view according to the canvas' size.
  5477. * @example
  5478. * window.addEventListener("resize", function () {
  5479. * engine.resize();
  5480. * });
  5481. */
  5482. Engine.prototype.resize = function () {
  5483. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5484. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5485. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5486. };
  5487. /**
  5488. * force a specific size of the canvas
  5489. * @param {number} width - the new canvas' width
  5490. * @param {number} height - the new canvas' height
  5491. */
  5492. Engine.prototype.setSize = function (width, height) {
  5493. this._renderingCanvas.width = width;
  5494. this._renderingCanvas.height = height;
  5495. for (var index = 0; index < this.scenes.length; index++) {
  5496. var scene = this.scenes[index];
  5497. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5498. var cam = scene.cameras[camIndex];
  5499. cam._currentRenderId = 0;
  5500. }
  5501. }
  5502. };
  5503. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5504. this._currentRenderTarget = texture;
  5505. var gl = this._gl;
  5506. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5507. if (texture.isCube) {
  5508. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5509. }
  5510. else {
  5511. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5512. }
  5513. this._gl.viewport(0, 0, texture._width, texture._height);
  5514. this.wipeCaches();
  5515. };
  5516. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5517. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5518. this._currentRenderTarget = null;
  5519. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5520. var gl = this._gl;
  5521. gl.bindTexture(gl.TEXTURE_2D, texture);
  5522. gl.generateMipmap(gl.TEXTURE_2D);
  5523. gl.bindTexture(gl.TEXTURE_2D, null);
  5524. }
  5525. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5526. };
  5527. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5528. if (texture.generateMipMaps) {
  5529. var gl = this._gl;
  5530. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5531. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5532. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5533. }
  5534. };
  5535. Engine.prototype.flushFramebuffer = function () {
  5536. this._gl.flush();
  5537. };
  5538. Engine.prototype.restoreDefaultFramebuffer = function () {
  5539. this._currentRenderTarget = null;
  5540. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5541. this.setViewport(this._cachedViewport);
  5542. this.wipeCaches();
  5543. };
  5544. // VBOs
  5545. Engine.prototype._resetVertexBufferBinding = function () {
  5546. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5547. this._cachedVertexBuffers = null;
  5548. };
  5549. Engine.prototype.createVertexBuffer = function (vertices) {
  5550. var vbo = this._gl.createBuffer();
  5551. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5552. if (vertices instanceof Float32Array) {
  5553. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5554. }
  5555. else {
  5556. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5557. }
  5558. this._resetVertexBufferBinding();
  5559. vbo.references = 1;
  5560. return vbo;
  5561. };
  5562. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5563. var vbo = this._gl.createBuffer();
  5564. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5565. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5566. this._resetVertexBufferBinding();
  5567. vbo.references = 1;
  5568. return vbo;
  5569. };
  5570. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5571. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5572. if (offset === undefined) {
  5573. offset = 0;
  5574. }
  5575. if (vertices instanceof Float32Array) {
  5576. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5577. }
  5578. else {
  5579. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5580. }
  5581. this._resetVertexBufferBinding();
  5582. };
  5583. Engine.prototype._resetIndexBufferBinding = function () {
  5584. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5585. this._cachedIndexBuffer = null;
  5586. };
  5587. Engine.prototype.createIndexBuffer = function (indices) {
  5588. var vbo = this._gl.createBuffer();
  5589. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5590. // Check for 32 bits indices
  5591. var arrayBuffer;
  5592. var need32Bits = false;
  5593. if (this._caps.uintIndices) {
  5594. for (var index = 0; index < indices.length; index++) {
  5595. if (indices[index] > 65535) {
  5596. need32Bits = true;
  5597. break;
  5598. }
  5599. }
  5600. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5601. }
  5602. else {
  5603. arrayBuffer = new Uint16Array(indices);
  5604. }
  5605. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5606. this._resetIndexBufferBinding();
  5607. vbo.references = 1;
  5608. vbo.is32Bits = need32Bits;
  5609. return vbo;
  5610. };
  5611. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5612. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5613. this._cachedVertexBuffers = vertexBuffer;
  5614. this._cachedEffectForVertexBuffers = effect;
  5615. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5616. var offset = 0;
  5617. for (var index = 0; index < vertexDeclaration.length; index++) {
  5618. var order = effect.getAttributeLocation(index);
  5619. if (order >= 0) {
  5620. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5621. }
  5622. offset += vertexDeclaration[index] * 4;
  5623. }
  5624. }
  5625. if (this._cachedIndexBuffer !== indexBuffer) {
  5626. this._cachedIndexBuffer = indexBuffer;
  5627. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5628. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5629. }
  5630. };
  5631. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5632. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5633. this._cachedVertexBuffers = vertexBuffers;
  5634. this._cachedEffectForVertexBuffers = effect;
  5635. var attributes = effect.getAttributesNames();
  5636. for (var index = 0; index < attributes.length; index++) {
  5637. var order = effect.getAttributeLocation(index);
  5638. if (order >= 0) {
  5639. var vertexBuffer = vertexBuffers[attributes[index]];
  5640. if (!vertexBuffer) {
  5641. continue;
  5642. }
  5643. var stride = vertexBuffer.getStrideSize();
  5644. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5645. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5646. }
  5647. }
  5648. }
  5649. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5650. this._cachedIndexBuffer = indexBuffer;
  5651. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5652. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5653. }
  5654. };
  5655. Engine.prototype._releaseBuffer = function (buffer) {
  5656. buffer.references--;
  5657. if (buffer.references === 0) {
  5658. this._gl.deleteBuffer(buffer);
  5659. return true;
  5660. }
  5661. return false;
  5662. };
  5663. Engine.prototype.createInstancesBuffer = function (capacity) {
  5664. var buffer = this._gl.createBuffer();
  5665. buffer.capacity = capacity;
  5666. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5667. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5668. return buffer;
  5669. };
  5670. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5671. this._gl.deleteBuffer(buffer);
  5672. };
  5673. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5674. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5675. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5676. for (var index = 0; index < 4; index++) {
  5677. var offsetLocation = offsetLocations[index];
  5678. this._gl.enableVertexAttribArray(offsetLocation);
  5679. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5680. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5681. }
  5682. };
  5683. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5684. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5685. for (var index = 0; index < 4; index++) {
  5686. var offsetLocation = offsetLocations[index];
  5687. this._gl.disableVertexAttribArray(offsetLocation);
  5688. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5689. }
  5690. };
  5691. Engine.prototype.applyStates = function () {
  5692. this._depthCullingState.apply(this._gl);
  5693. this._alphaState.apply(this._gl);
  5694. };
  5695. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5696. // Apply states
  5697. this.applyStates();
  5698. this._drawCalls++;
  5699. // Render
  5700. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5701. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5702. if (instancesCount) {
  5703. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5704. return;
  5705. }
  5706. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5707. };
  5708. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5709. // Apply states
  5710. this.applyStates();
  5711. this._drawCalls++;
  5712. if (instancesCount) {
  5713. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5714. return;
  5715. }
  5716. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5717. };
  5718. // Shaders
  5719. Engine.prototype._releaseEffect = function (effect) {
  5720. if (this._compiledEffects[effect._key]) {
  5721. delete this._compiledEffects[effect._key];
  5722. if (effect.getProgram()) {
  5723. this._gl.deleteProgram(effect.getProgram());
  5724. }
  5725. }
  5726. };
  5727. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5728. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5729. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5730. var name = vertex + "+" + fragment + "@" + defines;
  5731. if (this._compiledEffects[name]) {
  5732. return this._compiledEffects[name];
  5733. }
  5734. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5735. effect._key = name;
  5736. this._compiledEffects[name] = effect;
  5737. return effect;
  5738. };
  5739. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5740. if (uniformsNames === void 0) { uniformsNames = []; }
  5741. if (samplers === void 0) { samplers = []; }
  5742. if (defines === void 0) { defines = ""; }
  5743. return this.createEffect({
  5744. vertex: "particles",
  5745. fragmentElement: fragmentName
  5746. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5747. };
  5748. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5749. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5750. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5751. var shaderProgram = this._gl.createProgram();
  5752. this._gl.attachShader(shaderProgram, vertexShader);
  5753. this._gl.attachShader(shaderProgram, fragmentShader);
  5754. this._gl.linkProgram(shaderProgram);
  5755. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5756. if (!linked) {
  5757. var error = this._gl.getProgramInfoLog(shaderProgram);
  5758. if (error) {
  5759. throw new Error(error);
  5760. }
  5761. }
  5762. this._gl.deleteShader(vertexShader);
  5763. this._gl.deleteShader(fragmentShader);
  5764. return shaderProgram;
  5765. };
  5766. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5767. var results = [];
  5768. for (var index = 0; index < uniformsNames.length; index++) {
  5769. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5770. }
  5771. return results;
  5772. };
  5773. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5774. var results = [];
  5775. for (var index = 0; index < attributesNames.length; index++) {
  5776. try {
  5777. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5778. }
  5779. catch (e) {
  5780. results.push(-1);
  5781. }
  5782. }
  5783. return results;
  5784. };
  5785. Engine.prototype.enableEffect = function (effect) {
  5786. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5787. if (effect && effect.onBind) {
  5788. effect.onBind(effect);
  5789. }
  5790. return;
  5791. }
  5792. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5793. // Use program
  5794. this._gl.useProgram(effect.getProgram());
  5795. for (var i in this._vertexAttribArrays) {
  5796. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5797. continue;
  5798. }
  5799. this._vertexAttribArrays[i] = false;
  5800. this._gl.disableVertexAttribArray(i);
  5801. }
  5802. var attributesCount = effect.getAttributesCount();
  5803. for (var index = 0; index < attributesCount; index++) {
  5804. // Attributes
  5805. var order = effect.getAttributeLocation(index);
  5806. if (order >= 0) {
  5807. this._vertexAttribArrays[order] = true;
  5808. this._gl.enableVertexAttribArray(order);
  5809. }
  5810. }
  5811. this._currentEffect = effect;
  5812. if (effect.onBind) {
  5813. effect.onBind(effect);
  5814. }
  5815. };
  5816. Engine.prototype.setArray = function (uniform, array) {
  5817. if (!uniform)
  5818. return;
  5819. this._gl.uniform1fv(uniform, array);
  5820. };
  5821. Engine.prototype.setArray2 = function (uniform, array) {
  5822. if (!uniform || array.length % 2 !== 0)
  5823. return;
  5824. this._gl.uniform2fv(uniform, array);
  5825. };
  5826. Engine.prototype.setArray3 = function (uniform, array) {
  5827. if (!uniform || array.length % 3 !== 0)
  5828. return;
  5829. this._gl.uniform3fv(uniform, array);
  5830. };
  5831. Engine.prototype.setArray4 = function (uniform, array) {
  5832. if (!uniform || array.length % 4 !== 0)
  5833. return;
  5834. this._gl.uniform4fv(uniform, array);
  5835. };
  5836. Engine.prototype.setMatrices = function (uniform, matrices) {
  5837. if (!uniform)
  5838. return;
  5839. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5840. };
  5841. Engine.prototype.setMatrix = function (uniform, matrix) {
  5842. if (!uniform)
  5843. return;
  5844. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5845. };
  5846. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5847. if (!uniform)
  5848. return;
  5849. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5850. };
  5851. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5852. if (!uniform)
  5853. return;
  5854. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5855. };
  5856. Engine.prototype.setFloat = function (uniform, value) {
  5857. if (!uniform)
  5858. return;
  5859. this._gl.uniform1f(uniform, value);
  5860. };
  5861. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5862. if (!uniform)
  5863. return;
  5864. this._gl.uniform2f(uniform, x, y);
  5865. };
  5866. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5867. if (!uniform)
  5868. return;
  5869. this._gl.uniform3f(uniform, x, y, z);
  5870. };
  5871. Engine.prototype.setBool = function (uniform, bool) {
  5872. if (!uniform)
  5873. return;
  5874. this._gl.uniform1i(uniform, bool);
  5875. };
  5876. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5877. if (!uniform)
  5878. return;
  5879. this._gl.uniform4f(uniform, x, y, z, w);
  5880. };
  5881. Engine.prototype.setColor3 = function (uniform, color3) {
  5882. if (!uniform)
  5883. return;
  5884. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5885. };
  5886. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5887. if (!uniform)
  5888. return;
  5889. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5890. };
  5891. // States
  5892. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5893. if (zOffset === void 0) { zOffset = 0; }
  5894. if (reverseSide === void 0) { reverseSide = false; }
  5895. // Culling
  5896. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5897. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5898. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5899. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5900. if (culling) {
  5901. this._depthCullingState.cullFace = cullFace;
  5902. this._depthCullingState.cull = true;
  5903. }
  5904. else {
  5905. this._depthCullingState.cull = false;
  5906. }
  5907. }
  5908. // Z offset
  5909. this._depthCullingState.zOffset = zOffset;
  5910. };
  5911. Engine.prototype.setDepthBuffer = function (enable) {
  5912. this._depthCullingState.depthTest = enable;
  5913. };
  5914. Engine.prototype.getDepthWrite = function () {
  5915. return this._depthCullingState.depthMask;
  5916. };
  5917. Engine.prototype.setDepthWrite = function (enable) {
  5918. this._depthCullingState.depthMask = enable;
  5919. };
  5920. Engine.prototype.setColorWrite = function (enable) {
  5921. this._gl.colorMask(enable, enable, enable, enable);
  5922. };
  5923. Engine.prototype.setAlphaMode = function (mode) {
  5924. if (this._alphaMode === mode) {
  5925. return;
  5926. }
  5927. switch (mode) {
  5928. case Engine.ALPHA_DISABLE:
  5929. this.setDepthWrite(true);
  5930. this._alphaState.alphaBlend = false;
  5931. break;
  5932. case Engine.ALPHA_COMBINE:
  5933. this.setDepthWrite(false);
  5934. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  5935. this._alphaState.alphaBlend = true;
  5936. break;
  5937. case Engine.ALPHA_ONEONE:
  5938. this.setDepthWrite(false);
  5939. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5940. this._alphaState.alphaBlend = true;
  5941. break;
  5942. case Engine.ALPHA_ADD:
  5943. this.setDepthWrite(false);
  5944. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5945. this._alphaState.alphaBlend = true;
  5946. break;
  5947. case Engine.ALPHA_SUBTRACT:
  5948. this.setDepthWrite(false);
  5949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  5950. this._alphaState.alphaBlend = true;
  5951. break;
  5952. case Engine.ALPHA_MULTIPLY:
  5953. this.setDepthWrite(false);
  5954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  5955. this._alphaState.alphaBlend = true;
  5956. break;
  5957. case Engine.ALPHA_MAXIMIZED:
  5958. this.setDepthWrite(false);
  5959. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  5960. this._alphaState.alphaBlend = true;
  5961. break;
  5962. }
  5963. this._alphaMode = mode;
  5964. };
  5965. Engine.prototype.getAlphaMode = function () {
  5966. return this._alphaMode;
  5967. };
  5968. Engine.prototype.setAlphaTesting = function (enable) {
  5969. this._alphaTest = enable;
  5970. };
  5971. Engine.prototype.getAlphaTesting = function () {
  5972. return this._alphaTest;
  5973. };
  5974. // Textures
  5975. Engine.prototype.wipeCaches = function () {
  5976. this.resetTextureCache();
  5977. this._currentEffect = null;
  5978. this._depthCullingState.reset();
  5979. this._alphaState.reset();
  5980. this._cachedVertexBuffers = null;
  5981. this._cachedIndexBuffer = null;
  5982. this._cachedEffectForVertexBuffers = null;
  5983. };
  5984. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  5985. var gl = this._gl;
  5986. gl.bindTexture(gl.TEXTURE_2D, texture);
  5987. var magFilter = gl.NEAREST;
  5988. var minFilter = gl.NEAREST;
  5989. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5990. magFilter = gl.LINEAR;
  5991. minFilter = gl.LINEAR;
  5992. }
  5993. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5994. magFilter = gl.LINEAR;
  5995. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5996. }
  5997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  5998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  5999. gl.bindTexture(gl.TEXTURE_2D, null);
  6000. texture.samplingMode = samplingMode;
  6001. };
  6002. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6003. var _this = this;
  6004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6005. if (onLoad === void 0) { onLoad = null; }
  6006. if (onError === void 0) { onError = null; }
  6007. if (buffer === void 0) { buffer = null; }
  6008. var texture = this._gl.createTexture();
  6009. var extension;
  6010. var fromData = false;
  6011. if (url.substr(0, 5) === "data:") {
  6012. fromData = true;
  6013. }
  6014. if (!fromData)
  6015. extension = url.substr(url.length - 4, 4).toLowerCase();
  6016. else {
  6017. var oldUrl = url;
  6018. fromData = oldUrl.split(':');
  6019. url = oldUrl;
  6020. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6021. }
  6022. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6023. var isTGA = (extension === ".tga");
  6024. scene._addPendingData(texture);
  6025. texture.url = url;
  6026. texture.noMipmap = noMipmap;
  6027. texture.references = 1;
  6028. texture.samplingMode = samplingMode;
  6029. this._loadedTexturesCache.push(texture);
  6030. var onerror = function () {
  6031. scene._removePendingData(texture);
  6032. if (onError) {
  6033. onError();
  6034. }
  6035. };
  6036. var callback;
  6037. if (isTGA) {
  6038. callback = function (arrayBuffer) {
  6039. var data = new Uint8Array(arrayBuffer);
  6040. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6041. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6042. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6043. if (onLoad) {
  6044. onLoad();
  6045. }
  6046. }, samplingMode);
  6047. };
  6048. if (!(fromData instanceof Array))
  6049. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6050. callback(arrayBuffer);
  6051. }, onerror, scene.database, true);
  6052. else
  6053. callback(buffer);
  6054. }
  6055. else if (isDDS) {
  6056. callback = function (data) {
  6057. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6058. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6059. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6060. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6061. if (onLoad) {
  6062. onLoad();
  6063. }
  6064. }, samplingMode);
  6065. };
  6066. if (!(fromData instanceof Array))
  6067. BABYLON.Tools.LoadFile(url, function (data) {
  6068. callback(data);
  6069. }, onerror, scene.database, true);
  6070. else
  6071. callback(buffer);
  6072. }
  6073. else {
  6074. var onload = function (img) {
  6075. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6076. var isPot = (img.width === potWidth && img.height === potHeight);
  6077. if (!isPot) {
  6078. _this._prepareWorkingCanvas();
  6079. _this._workingCanvas.width = potWidth;
  6080. _this._workingCanvas.height = potHeight;
  6081. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6082. _this._workingContext.imageSmoothingEnabled = false;
  6083. _this._workingContext.mozImageSmoothingEnabled = false;
  6084. _this._workingContext.oImageSmoothingEnabled = false;
  6085. _this._workingContext.webkitImageSmoothingEnabled = false;
  6086. _this._workingContext.msImageSmoothingEnabled = false;
  6087. }
  6088. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6089. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6090. _this._workingContext.imageSmoothingEnabled = true;
  6091. _this._workingContext.mozImageSmoothingEnabled = true;
  6092. _this._workingContext.oImageSmoothingEnabled = true;
  6093. _this._workingContext.webkitImageSmoothingEnabled = true;
  6094. _this._workingContext.msImageSmoothingEnabled = true;
  6095. }
  6096. }
  6097. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6098. if (onLoad) {
  6099. onLoad();
  6100. }
  6101. }, samplingMode);
  6102. };
  6103. if (!(fromData instanceof Array))
  6104. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6105. else
  6106. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6107. }
  6108. return texture;
  6109. };
  6110. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6111. if (compression === void 0) { compression = null; }
  6112. var internalFormat = this._gl.RGBA;
  6113. switch (format) {
  6114. case Engine.TEXTUREFORMAT_ALPHA:
  6115. internalFormat = this._gl.ALPHA;
  6116. break;
  6117. case Engine.TEXTUREFORMAT_LUMINANCE:
  6118. internalFormat = this._gl.LUMINANCE;
  6119. break;
  6120. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6121. internalFormat = this._gl.LUMINANCE_ALPHA;
  6122. break;
  6123. case Engine.TEXTUREFORMAT_RGB:
  6124. internalFormat = this._gl.RGB;
  6125. break;
  6126. case Engine.TEXTUREFORMAT_RGBA:
  6127. internalFormat = this._gl.RGBA;
  6128. break;
  6129. }
  6130. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6131. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6132. if (compression) {
  6133. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6134. }
  6135. else {
  6136. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6137. }
  6138. if (texture.generateMipMaps) {
  6139. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6140. }
  6141. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6142. this.resetTextureCache();
  6143. texture.isReady = true;
  6144. };
  6145. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6146. if (compression === void 0) { compression = null; }
  6147. var texture = this._gl.createTexture();
  6148. texture._baseWidth = width;
  6149. texture._baseHeight = height;
  6150. texture._width = width;
  6151. texture._height = height;
  6152. texture.references = 1;
  6153. this.updateRawTexture(texture, data, format, invertY, compression);
  6154. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6155. // Filters
  6156. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6157. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6158. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6159. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6160. texture.samplingMode = samplingMode;
  6161. this._loadedTexturesCache.push(texture);
  6162. return texture;
  6163. };
  6164. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6165. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6166. var texture = this._gl.createTexture();
  6167. texture._baseWidth = width;
  6168. texture._baseHeight = height;
  6169. if (forceExponantOfTwo) {
  6170. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6171. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6172. }
  6173. this.resetTextureCache();
  6174. texture._width = width;
  6175. texture._height = height;
  6176. texture.isReady = false;
  6177. texture.generateMipMaps = generateMipMaps;
  6178. texture.references = 1;
  6179. texture.samplingMode = samplingMode;
  6180. this.updateTextureSamplingMode(samplingMode, texture);
  6181. this._loadedTexturesCache.push(texture);
  6182. return texture;
  6183. };
  6184. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6185. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6186. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6187. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6188. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6189. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6190. };
  6191. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6192. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6193. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6194. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6195. if (texture.generateMipMaps) {
  6196. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6197. }
  6198. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6199. this.resetTextureCache();
  6200. texture.isReady = true;
  6201. };
  6202. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6203. if (texture._isDisabled) {
  6204. return;
  6205. }
  6206. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6207. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6208. try {
  6209. // Testing video texture support
  6210. if (this._videoTextureSupported === undefined) {
  6211. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6212. if (this._gl.getError() !== 0) {
  6213. this._videoTextureSupported = false;
  6214. }
  6215. else {
  6216. this._videoTextureSupported = true;
  6217. }
  6218. }
  6219. // Copy video through the current working canvas if video texture is not supported
  6220. if (!this._videoTextureSupported) {
  6221. if (!texture._workingCanvas) {
  6222. texture._workingCanvas = document.createElement("canvas");
  6223. texture._workingContext = texture._workingCanvas.getContext("2d");
  6224. texture._workingCanvas.width = texture._width;
  6225. texture._workingCanvas.height = texture._height;
  6226. }
  6227. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6228. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6229. }
  6230. else {
  6231. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6232. }
  6233. if (texture.generateMipMaps) {
  6234. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6235. }
  6236. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6237. this.resetTextureCache();
  6238. texture.isReady = true;
  6239. }
  6240. catch (ex) {
  6241. // Something unexpected
  6242. // Let's disable the texture
  6243. texture._isDisabled = true;
  6244. }
  6245. };
  6246. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6247. // old version had a "generateMipMaps" arg instead of options.
  6248. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6249. // in the same way, generateDepthBuffer is defaulted to true
  6250. var generateMipMaps = false;
  6251. var generateDepthBuffer = true;
  6252. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6253. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6254. if (options !== undefined) {
  6255. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6256. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6257. type = options.type === undefined ? type : options.type;
  6258. if (options.samplingMode !== undefined) {
  6259. samplingMode = options.samplingMode;
  6260. }
  6261. if (type === Engine.TEXTURETYPE_FLOAT) {
  6262. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6263. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6264. }
  6265. }
  6266. var gl = this._gl;
  6267. var texture = gl.createTexture();
  6268. gl.bindTexture(gl.TEXTURE_2D, texture);
  6269. var width = size.width || size;
  6270. var height = size.height || size;
  6271. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6272. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6273. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6274. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6275. }
  6276. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6277. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6278. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6280. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6281. var depthBuffer;
  6282. // Create the depth buffer
  6283. if (generateDepthBuffer) {
  6284. depthBuffer = gl.createRenderbuffer();
  6285. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6286. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6287. }
  6288. // Create the framebuffer
  6289. var framebuffer = gl.createFramebuffer();
  6290. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6291. if (generateDepthBuffer) {
  6292. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6293. }
  6294. if (generateMipMaps) {
  6295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6296. }
  6297. // Unbind
  6298. gl.bindTexture(gl.TEXTURE_2D, null);
  6299. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6300. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6301. texture._framebuffer = framebuffer;
  6302. if (generateDepthBuffer) {
  6303. texture._depthBuffer = depthBuffer;
  6304. }
  6305. texture._width = width;
  6306. texture._height = height;
  6307. texture.isReady = true;
  6308. texture.generateMipMaps = generateMipMaps;
  6309. texture.references = 1;
  6310. texture.samplingMode = samplingMode;
  6311. this.resetTextureCache();
  6312. this._loadedTexturesCache.push(texture);
  6313. return texture;
  6314. };
  6315. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6316. var gl = this._gl;
  6317. var texture = gl.createTexture();
  6318. var generateMipMaps = true;
  6319. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6320. if (options !== undefined) {
  6321. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6322. if (options.samplingMode !== undefined) {
  6323. samplingMode = options.samplingMode;
  6324. }
  6325. }
  6326. texture.isCube = true;
  6327. texture.references = 1;
  6328. texture.generateMipMaps = generateMipMaps;
  6329. texture.references = 1;
  6330. texture.samplingMode = samplingMode;
  6331. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6332. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6333. for (var face = 0; face < 6; face++) {
  6334. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6335. }
  6336. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6339. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6340. // Create the depth buffer
  6341. var depthBuffer = gl.createRenderbuffer();
  6342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6343. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6344. // Create the framebuffer
  6345. var framebuffer = gl.createFramebuffer();
  6346. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6347. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6348. // Unbind
  6349. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6350. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6351. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6352. texture._framebuffer = framebuffer;
  6353. texture._depthBuffer = depthBuffer;
  6354. this.resetTextureCache();
  6355. texture._width = size;
  6356. texture._height = size;
  6357. texture.isReady = true;
  6358. return texture;
  6359. };
  6360. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6361. var _this = this;
  6362. var gl = this._gl;
  6363. var texture = gl.createTexture();
  6364. texture.isCube = true;
  6365. texture.url = rootUrl;
  6366. texture.references = 1;
  6367. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6368. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6369. if (isDDS) {
  6370. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6371. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6372. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6373. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6374. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6375. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6376. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6377. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6378. }
  6379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6383. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6384. _this.resetTextureCache();
  6385. texture._width = info.width;
  6386. texture._height = info.height;
  6387. texture.isReady = true;
  6388. }, null, null, true);
  6389. }
  6390. else {
  6391. cascadeLoad(rootUrl, scene, function (imgs) {
  6392. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6393. var height = width;
  6394. _this._prepareWorkingCanvas();
  6395. _this._workingCanvas.width = width;
  6396. _this._workingCanvas.height = height;
  6397. var faces = [
  6398. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6399. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6400. ];
  6401. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6402. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6403. for (var index = 0; index < faces.length; index++) {
  6404. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6405. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6406. }
  6407. if (!noMipmap) {
  6408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6409. }
  6410. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6411. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6414. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6415. _this.resetTextureCache();
  6416. texture._width = width;
  6417. texture._height = height;
  6418. texture.isReady = true;
  6419. }, extensions);
  6420. }
  6421. return texture;
  6422. };
  6423. Engine.prototype._releaseTexture = function (texture) {
  6424. var gl = this._gl;
  6425. if (texture._framebuffer) {
  6426. gl.deleteFramebuffer(texture._framebuffer);
  6427. }
  6428. if (texture._depthBuffer) {
  6429. gl.deleteRenderbuffer(texture._depthBuffer);
  6430. }
  6431. gl.deleteTexture(texture);
  6432. // Unbind channels
  6433. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6434. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6435. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6436. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6437. this._activeTexturesCache[channel] = null;
  6438. }
  6439. var index = this._loadedTexturesCache.indexOf(texture);
  6440. if (index !== -1) {
  6441. this._loadedTexturesCache.splice(index, 1);
  6442. }
  6443. };
  6444. Engine.prototype.bindSamplers = function (effect) {
  6445. this._gl.useProgram(effect.getProgram());
  6446. var samplers = effect.getSamplers();
  6447. for (var index = 0; index < samplers.length; index++) {
  6448. var uniform = effect.getUniform(samplers[index]);
  6449. this._gl.uniform1i(uniform, index);
  6450. }
  6451. this._currentEffect = null;
  6452. };
  6453. Engine.prototype._bindTexture = function (channel, texture) {
  6454. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6455. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6456. this._activeTexturesCache[channel] = null;
  6457. };
  6458. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6459. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6460. };
  6461. Engine.prototype.setTexture = function (channel, texture) {
  6462. if (channel < 0) {
  6463. return;
  6464. }
  6465. // Not ready?
  6466. if (!texture || !texture.isReady()) {
  6467. if (this._activeTexturesCache[channel] != null) {
  6468. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6469. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6470. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6471. this._activeTexturesCache[channel] = null;
  6472. }
  6473. return;
  6474. }
  6475. // Video
  6476. if (texture instanceof BABYLON.VideoTexture) {
  6477. if (texture.update()) {
  6478. this._activeTexturesCache[channel] = null;
  6479. }
  6480. }
  6481. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6482. texture.delayLoad();
  6483. return;
  6484. }
  6485. if (this._activeTexturesCache[channel] === texture) {
  6486. return;
  6487. }
  6488. this._activeTexturesCache[channel] = texture;
  6489. var internalTexture = texture.getInternalTexture();
  6490. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6491. if (internalTexture.isCube) {
  6492. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6493. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6494. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6495. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6496. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6497. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6498. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6499. }
  6500. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6501. }
  6502. else {
  6503. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6504. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6505. internalTexture._cachedWrapU = texture.wrapU;
  6506. switch (texture.wrapU) {
  6507. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6508. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6509. break;
  6510. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6511. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6512. break;
  6513. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6514. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6515. break;
  6516. }
  6517. }
  6518. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6519. internalTexture._cachedWrapV = texture.wrapV;
  6520. switch (texture.wrapV) {
  6521. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6523. break;
  6524. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6525. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6526. break;
  6527. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6528. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6529. break;
  6530. }
  6531. }
  6532. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6533. }
  6534. };
  6535. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6536. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6537. var value = texture.anisotropicFilteringLevel;
  6538. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6539. value = 1;
  6540. }
  6541. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6542. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6543. texture._cachedAnisotropicFilteringLevel = value;
  6544. }
  6545. };
  6546. Engine.prototype.readPixels = function (x, y, width, height) {
  6547. var data = new Uint8Array(height * width * 4);
  6548. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6549. return data;
  6550. };
  6551. Engine.prototype.releaseInternalTexture = function (texture) {
  6552. if (!texture) {
  6553. return;
  6554. }
  6555. texture.references--;
  6556. // Final reference ?
  6557. if (texture.references === 0) {
  6558. var texturesCache = this.getLoadedTexturesCache();
  6559. var index = texturesCache.indexOf(texture);
  6560. if (index > -1) {
  6561. texturesCache.splice(index, 1);
  6562. }
  6563. this._releaseTexture(texture);
  6564. }
  6565. };
  6566. // Dispose
  6567. Engine.prototype.dispose = function () {
  6568. this.hideLoadingUI();
  6569. this.stopRenderLoop();
  6570. // Release scenes
  6571. while (this.scenes.length) {
  6572. this.scenes[0].dispose();
  6573. }
  6574. // Release audio engine
  6575. Engine.audioEngine.dispose();
  6576. // Release effects
  6577. for (var name in this._compiledEffects) {
  6578. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6579. }
  6580. // Unbind
  6581. for (var i in this._vertexAttribArrays) {
  6582. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6583. continue;
  6584. }
  6585. this._gl.disableVertexAttribArray(i);
  6586. }
  6587. this._gl = null;
  6588. // Events
  6589. window.removeEventListener("blur", this._onBlur);
  6590. window.removeEventListener("focus", this._onFocus);
  6591. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6592. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6593. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6594. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6595. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6596. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6597. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6598. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6599. };
  6600. // Loading screen
  6601. Engine.prototype.displayLoadingUI = function () {
  6602. this._loadingScreen.displayLoadingUI();
  6603. };
  6604. Engine.prototype.hideLoadingUI = function () {
  6605. this._loadingScreen.hideLoadingUI();
  6606. };
  6607. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6608. get: function () {
  6609. return this._loadingScreen;
  6610. },
  6611. set: function (loadingScreen) {
  6612. this._loadingScreen = loadingScreen;
  6613. },
  6614. enumerable: true,
  6615. configurable: true
  6616. });
  6617. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6618. set: function (text) {
  6619. this._loadingScreen.loadingUIText = text;
  6620. },
  6621. enumerable: true,
  6622. configurable: true
  6623. });
  6624. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6625. set: function (color) {
  6626. this._loadingScreen.loadingUIBackgroundColor = color;
  6627. },
  6628. enumerable: true,
  6629. configurable: true
  6630. });
  6631. // FPS
  6632. Engine.prototype.getFps = function () {
  6633. return this.fps;
  6634. };
  6635. Engine.prototype.getDeltaTime = function () {
  6636. return this.deltaTime;
  6637. };
  6638. Engine.prototype._measureFps = function () {
  6639. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6640. var length = this.previousFramesDuration.length;
  6641. if (length >= 2) {
  6642. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6643. }
  6644. if (length >= this.fpsRange) {
  6645. if (length > this.fpsRange) {
  6646. this.previousFramesDuration.splice(0, 1);
  6647. length = this.previousFramesDuration.length;
  6648. }
  6649. var sum = 0;
  6650. for (var id = 0; id < length - 1; id++) {
  6651. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6652. }
  6653. this.fps = 1000.0 / (sum / (length - 1));
  6654. }
  6655. };
  6656. // Statics
  6657. Engine.isSupported = function () {
  6658. try {
  6659. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6660. if (navigator.isCocoonJS) {
  6661. return true;
  6662. }
  6663. var tempcanvas = document.createElement("canvas");
  6664. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6665. return gl != null && !!window.WebGLRenderingContext;
  6666. }
  6667. catch (e) {
  6668. return false;
  6669. }
  6670. };
  6671. // Const statics
  6672. Engine._ALPHA_DISABLE = 0;
  6673. Engine._ALPHA_ADD = 1;
  6674. Engine._ALPHA_COMBINE = 2;
  6675. Engine._ALPHA_SUBTRACT = 3;
  6676. Engine._ALPHA_MULTIPLY = 4;
  6677. Engine._ALPHA_MAXIMIZED = 5;
  6678. Engine._ALPHA_ONEONE = 6;
  6679. Engine._DELAYLOADSTATE_NONE = 0;
  6680. Engine._DELAYLOADSTATE_LOADED = 1;
  6681. Engine._DELAYLOADSTATE_LOADING = 2;
  6682. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6683. Engine._TEXTUREFORMAT_ALPHA = 0;
  6684. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6685. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6686. Engine._TEXTUREFORMAT_RGB = 4;
  6687. Engine._TEXTUREFORMAT_RGBA = 5;
  6688. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6689. Engine._TEXTURETYPE_FLOAT = 1;
  6690. // Updatable statics so stick with vars here
  6691. Engine.Epsilon = 0.001;
  6692. Engine.CollisionsEpsilon = 0.001;
  6693. Engine.CodeRepository = "src/";
  6694. Engine.ShadersRepository = "src/Shaders/";
  6695. return Engine;
  6696. })();
  6697. BABYLON.Engine = Engine;
  6698. })(BABYLON || (BABYLON = {}));
  6699. var BABYLON;
  6700. (function (BABYLON) {
  6701. /**
  6702. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6703. */
  6704. var Node = (function () {
  6705. /**
  6706. * @constructor
  6707. * @param {string} name - the name and id to be given to this node
  6708. * @param {BABYLON.Scene} the scene this node will be added to
  6709. */
  6710. function Node(name, scene) {
  6711. this.state = "";
  6712. this.animations = new Array();
  6713. this._childrenFlag = -1;
  6714. this._isEnabled = true;
  6715. this._isReady = true;
  6716. this._currentRenderId = -1;
  6717. this._parentRenderId = -1;
  6718. this.name = name;
  6719. this.id = name;
  6720. this._scene = scene;
  6721. this._initCache();
  6722. }
  6723. Node.prototype.getScene = function () {
  6724. return this._scene;
  6725. };
  6726. Node.prototype.getEngine = function () {
  6727. return this._scene.getEngine();
  6728. };
  6729. // override it in derived class
  6730. Node.prototype.getWorldMatrix = function () {
  6731. return BABYLON.Matrix.Identity();
  6732. };
  6733. // override it in derived class if you add new variables to the cache
  6734. // and call the parent class method
  6735. Node.prototype._initCache = function () {
  6736. this._cache = {};
  6737. this._cache.parent = undefined;
  6738. };
  6739. Node.prototype.updateCache = function (force) {
  6740. if (!force && this.isSynchronized())
  6741. return;
  6742. this._cache.parent = this.parent;
  6743. this._updateCache();
  6744. };
  6745. // override it in derived class if you add new variables to the cache
  6746. // and call the parent class method if !ignoreParentClass
  6747. Node.prototype._updateCache = function (ignoreParentClass) {
  6748. };
  6749. // override it in derived class if you add new variables to the cache
  6750. Node.prototype._isSynchronized = function () {
  6751. return true;
  6752. };
  6753. Node.prototype._markSyncedWithParent = function () {
  6754. this._parentRenderId = this.parent._currentRenderId;
  6755. };
  6756. Node.prototype.isSynchronizedWithParent = function () {
  6757. if (!this.parent) {
  6758. return true;
  6759. }
  6760. if (this._parentRenderId !== this.parent._currentRenderId) {
  6761. return false;
  6762. }
  6763. return this.parent.isSynchronized();
  6764. };
  6765. Node.prototype.isSynchronized = function (updateCache) {
  6766. var check = this.hasNewParent();
  6767. check = check || !this.isSynchronizedWithParent();
  6768. check = check || !this._isSynchronized();
  6769. if (updateCache)
  6770. this.updateCache(true);
  6771. return !check;
  6772. };
  6773. Node.prototype.hasNewParent = function (update) {
  6774. if (this._cache.parent === this.parent)
  6775. return false;
  6776. if (update)
  6777. this._cache.parent = this.parent;
  6778. return true;
  6779. };
  6780. /**
  6781. * Is this node ready to be used/rendered
  6782. * @return {boolean} is it ready
  6783. */
  6784. Node.prototype.isReady = function () {
  6785. return this._isReady;
  6786. };
  6787. /**
  6788. * Is this node enabled.
  6789. * If the node has a parent and is enabled, the parent will be inspected as well.
  6790. * @return {boolean} whether this node (and its parent) is enabled.
  6791. * @see setEnabled
  6792. */
  6793. Node.prototype.isEnabled = function () {
  6794. if (!this._isEnabled) {
  6795. return false;
  6796. }
  6797. if (this.parent) {
  6798. return this.parent.isEnabled();
  6799. }
  6800. return true;
  6801. };
  6802. /**
  6803. * Set the enabled state of this node.
  6804. * @param {boolean} value - the new enabled state
  6805. * @see isEnabled
  6806. */
  6807. Node.prototype.setEnabled = function (value) {
  6808. this._isEnabled = value;
  6809. };
  6810. /**
  6811. * Is this node a descendant of the given node.
  6812. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6813. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6814. * @see parent
  6815. */
  6816. Node.prototype.isDescendantOf = function (ancestor) {
  6817. if (this.parent) {
  6818. if (this.parent === ancestor) {
  6819. return true;
  6820. }
  6821. return this.parent.isDescendantOf(ancestor);
  6822. }
  6823. return false;
  6824. };
  6825. Node.prototype._getDescendants = function (list, results) {
  6826. for (var index = 0; index < list.length; index++) {
  6827. var item = list[index];
  6828. if (item.isDescendantOf(this)) {
  6829. results.push(item);
  6830. }
  6831. }
  6832. };
  6833. /**
  6834. * Will return all nodes that have this node as parent.
  6835. * @return {BABYLON.Node[]} all children nodes of all types.
  6836. */
  6837. Node.prototype.getDescendants = function () {
  6838. var results = [];
  6839. this._getDescendants(this._scene.meshes, results);
  6840. this._getDescendants(this._scene.lights, results);
  6841. this._getDescendants(this._scene.cameras, results);
  6842. return results;
  6843. };
  6844. Node.prototype._setReady = function (state) {
  6845. if (state == this._isReady) {
  6846. return;
  6847. }
  6848. if (!state) {
  6849. this._isReady = false;
  6850. return;
  6851. }
  6852. this._isReady = true;
  6853. if (this.onReady) {
  6854. this.onReady(this);
  6855. }
  6856. };
  6857. return Node;
  6858. })();
  6859. BABYLON.Node = Node;
  6860. })(BABYLON || (BABYLON = {}));
  6861. var BABYLON;
  6862. (function (BABYLON) {
  6863. var FilesInput = (function () {
  6864. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6865. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6866. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6867. this._engine = p_engine;
  6868. this._canvas = p_canvas;
  6869. this._currentScene = p_scene;
  6870. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6871. this._progressCallback = p_progressCallback;
  6872. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6873. this._textureLoadingCallback = p_textureLoadingCallback;
  6874. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6875. }
  6876. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6877. var _this = this;
  6878. if (p_elementToMonitor) {
  6879. this._elementToMonitor = p_elementToMonitor;
  6880. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6881. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6882. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6883. }
  6884. };
  6885. FilesInput.prototype.renderFunction = function () {
  6886. if (this._additionnalRenderLoopLogicCallback) {
  6887. this._additionnalRenderLoopLogicCallback();
  6888. }
  6889. if (this._currentScene) {
  6890. if (this._textureLoadingCallback) {
  6891. var remaining = this._currentScene.getWaitingItemsCount();
  6892. if (remaining > 0) {
  6893. this._textureLoadingCallback(remaining);
  6894. }
  6895. }
  6896. this._currentScene.render();
  6897. }
  6898. };
  6899. FilesInput.prototype.drag = function (e) {
  6900. e.stopPropagation();
  6901. e.preventDefault();
  6902. };
  6903. FilesInput.prototype.drop = function (eventDrop) {
  6904. eventDrop.stopPropagation();
  6905. eventDrop.preventDefault();
  6906. this.loadFiles(eventDrop);
  6907. };
  6908. FilesInput.prototype.loadFiles = function (event) {
  6909. if (this._startingProcessingFilesCallback)
  6910. this._startingProcessingFilesCallback();
  6911. // Handling data transfer via drag'n'drop
  6912. if (event && event.dataTransfer && event.dataTransfer.files) {
  6913. this._filesToLoad = event.dataTransfer.files;
  6914. }
  6915. // Handling files from input files
  6916. if (event && event.target && event.target.files) {
  6917. this._filesToLoad = event.target.files;
  6918. }
  6919. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6920. for (var i = 0; i < this._filesToLoad.length; i++) {
  6921. switch (this._filesToLoad[i].type) {
  6922. case "image/jpeg":
  6923. case "image/png":
  6924. case "image/bmp":
  6925. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6926. break;
  6927. case "image/targa":
  6928. case "image/vnd.ms-dds":
  6929. case "audio/wav":
  6930. case "audio/x-wav":
  6931. case "audio/mp3":
  6932. case "audio/mpeg":
  6933. case "audio/mpeg3":
  6934. case "audio/x-mpeg-3":
  6935. case "audio/ogg":
  6936. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6937. break;
  6938. default:
  6939. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  6940. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  6941. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  6942. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  6943. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  6944. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  6945. this._sceneFileToLoad = this._filesToLoad[i];
  6946. }
  6947. break;
  6948. }
  6949. }
  6950. this.reload();
  6951. }
  6952. };
  6953. FilesInput.prototype.reload = function () {
  6954. var _this = this;
  6955. var that = this;
  6956. // If a ".babylon" file has been provided
  6957. if (this._sceneFileToLoad) {
  6958. if (this._currentScene) {
  6959. if (BABYLON.Tools.errorsCount > 0) {
  6960. BABYLON.Tools.ClearLogCache();
  6961. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  6962. }
  6963. this._engine.stopRenderLoop();
  6964. this._currentScene.dispose();
  6965. }
  6966. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  6967. that._currentScene = newScene;
  6968. // Wait for textures and shaders to be ready
  6969. that._currentScene.executeWhenReady(function () {
  6970. // Attach camera to canvas inputs
  6971. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  6972. that._currentScene.createDefaultCameraOrLight();
  6973. }
  6974. that._currentScene.activeCamera.attachControl(that._canvas);
  6975. if (that._sceneLoadedCallback) {
  6976. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  6977. }
  6978. that._engine.runRenderLoop(function () { that.renderFunction(); });
  6979. });
  6980. }, function (progress) {
  6981. if (_this._progressCallback) {
  6982. _this._progressCallback(progress);
  6983. }
  6984. });
  6985. }
  6986. else {
  6987. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  6988. }
  6989. };
  6990. FilesInput.FilesTextures = new Array();
  6991. FilesInput.FilesToLoad = new Array();
  6992. return FilesInput;
  6993. })();
  6994. BABYLON.FilesInput = FilesInput;
  6995. })(BABYLON || (BABYLON = {}));
  6996. var BABYLON;
  6997. (function (BABYLON) {
  6998. var IntersectionInfo = (function () {
  6999. function IntersectionInfo(bu, bv, distance) {
  7000. this.bu = bu;
  7001. this.bv = bv;
  7002. this.distance = distance;
  7003. this.faceId = 0;
  7004. this.subMeshId = 0;
  7005. }
  7006. return IntersectionInfo;
  7007. })();
  7008. BABYLON.IntersectionInfo = IntersectionInfo;
  7009. var PickingInfo = (function () {
  7010. function PickingInfo() {
  7011. this.hit = false;
  7012. this.distance = 0;
  7013. this.pickedPoint = null;
  7014. this.pickedMesh = null;
  7015. this.bu = 0;
  7016. this.bv = 0;
  7017. this.faceId = -1;
  7018. this.subMeshId = 0;
  7019. this.pickedSprite = null;
  7020. }
  7021. // Methods
  7022. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7023. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7024. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7025. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7026. return null;
  7027. }
  7028. var indices = this.pickedMesh.getIndices();
  7029. var result;
  7030. if (useVerticesNormals) {
  7031. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7032. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7033. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7034. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7035. normal0 = normal0.scale(this.bu);
  7036. normal1 = normal1.scale(this.bv);
  7037. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7038. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7039. }
  7040. else {
  7041. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7042. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7043. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7044. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7045. var p1p2 = vertex1.subtract(vertex2);
  7046. var p3p2 = vertex3.subtract(vertex2);
  7047. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7048. }
  7049. if (useWorldCoordinates) {
  7050. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7051. }
  7052. return BABYLON.Vector3.Normalize(result);
  7053. };
  7054. PickingInfo.prototype.getTextureCoordinates = function () {
  7055. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7056. return null;
  7057. }
  7058. var indices = this.pickedMesh.getIndices();
  7059. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7060. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7061. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7062. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7063. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7064. uv1 = uv1.scale(this.bu);
  7065. uv2 = uv2.scale(this.bv);
  7066. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7067. };
  7068. return PickingInfo;
  7069. })();
  7070. BABYLON.PickingInfo = PickingInfo;
  7071. })(BABYLON || (BABYLON = {}));
  7072. var BABYLON;
  7073. (function (BABYLON) {
  7074. var BoundingSphere = (function () {
  7075. function BoundingSphere(minimum, maximum) {
  7076. this.minimum = minimum;
  7077. this.maximum = maximum;
  7078. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7079. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7080. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7081. this.radius = distance * 0.5;
  7082. this.centerWorld = BABYLON.Vector3.Zero();
  7083. this._update(BABYLON.Matrix.Identity());
  7084. }
  7085. // Methods
  7086. BoundingSphere.prototype._update = function (world) {
  7087. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7088. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7089. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7090. };
  7091. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7092. for (var i = 0; i < 6; i++) {
  7093. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7094. return false;
  7095. }
  7096. return true;
  7097. };
  7098. BoundingSphere.prototype.intersectsPoint = function (point) {
  7099. var x = this.centerWorld.x - point.x;
  7100. var y = this.centerWorld.y - point.y;
  7101. var z = this.centerWorld.z - point.z;
  7102. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7103. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7104. return false;
  7105. return true;
  7106. };
  7107. // Statics
  7108. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7109. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7110. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7111. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7112. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7113. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7114. return false;
  7115. return true;
  7116. };
  7117. return BoundingSphere;
  7118. })();
  7119. BABYLON.BoundingSphere = BoundingSphere;
  7120. })(BABYLON || (BABYLON = {}));
  7121. var BABYLON;
  7122. (function (BABYLON) {
  7123. var BoundingBox = (function () {
  7124. function BoundingBox(minimum, maximum) {
  7125. this.minimum = minimum;
  7126. this.maximum = maximum;
  7127. this.vectors = new Array();
  7128. this.vectorsWorld = new Array();
  7129. // Bounding vectors
  7130. this.vectors.push(this.minimum.clone());
  7131. this.vectors.push(this.maximum.clone());
  7132. this.vectors.push(this.minimum.clone());
  7133. this.vectors[2].x = this.maximum.x;
  7134. this.vectors.push(this.minimum.clone());
  7135. this.vectors[3].y = this.maximum.y;
  7136. this.vectors.push(this.minimum.clone());
  7137. this.vectors[4].z = this.maximum.z;
  7138. this.vectors.push(this.maximum.clone());
  7139. this.vectors[5].z = this.minimum.z;
  7140. this.vectors.push(this.maximum.clone());
  7141. this.vectors[6].x = this.minimum.x;
  7142. this.vectors.push(this.maximum.clone());
  7143. this.vectors[7].y = this.minimum.y;
  7144. // OBB
  7145. this.center = this.maximum.add(this.minimum).scale(0.5);
  7146. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7147. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7148. // World
  7149. for (var index = 0; index < this.vectors.length; index++) {
  7150. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7151. }
  7152. this.minimumWorld = BABYLON.Vector3.Zero();
  7153. this.maximumWorld = BABYLON.Vector3.Zero();
  7154. this._update(BABYLON.Matrix.Identity());
  7155. }
  7156. // Methods
  7157. BoundingBox.prototype.getWorldMatrix = function () {
  7158. return this._worldMatrix;
  7159. };
  7160. BoundingBox.prototype._update = function (world) {
  7161. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7162. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7163. for (var index = 0; index < this.vectors.length; index++) {
  7164. var v = this.vectorsWorld[index];
  7165. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7166. if (v.x < this.minimumWorld.x)
  7167. this.minimumWorld.x = v.x;
  7168. if (v.y < this.minimumWorld.y)
  7169. this.minimumWorld.y = v.y;
  7170. if (v.z < this.minimumWorld.z)
  7171. this.minimumWorld.z = v.z;
  7172. if (v.x > this.maximumWorld.x)
  7173. this.maximumWorld.x = v.x;
  7174. if (v.y > this.maximumWorld.y)
  7175. this.maximumWorld.y = v.y;
  7176. if (v.z > this.maximumWorld.z)
  7177. this.maximumWorld.z = v.z;
  7178. }
  7179. // OBB
  7180. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7181. this.center.scaleInPlace(0.5);
  7182. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7183. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7184. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7185. this._worldMatrix = world;
  7186. };
  7187. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7188. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7189. };
  7190. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7191. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7192. };
  7193. BoundingBox.prototype.intersectsPoint = function (point) {
  7194. var delta = -BABYLON.Engine.Epsilon;
  7195. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7196. return false;
  7197. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7198. return false;
  7199. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7200. return false;
  7201. return true;
  7202. };
  7203. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7204. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7205. };
  7206. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7207. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7208. return false;
  7209. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7210. return false;
  7211. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7212. return false;
  7213. return true;
  7214. };
  7215. // Statics
  7216. BoundingBox.Intersects = function (box0, box1) {
  7217. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7218. return false;
  7219. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7220. return false;
  7221. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7222. return false;
  7223. return true;
  7224. };
  7225. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7226. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7227. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7228. return (num <= (sphereRadius * sphereRadius));
  7229. };
  7230. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7231. for (var p = 0; p < 6; p++) {
  7232. for (var i = 0; i < 8; i++) {
  7233. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7234. return false;
  7235. }
  7236. }
  7237. }
  7238. return true;
  7239. };
  7240. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7241. for (var p = 0; p < 6; p++) {
  7242. var inCount = 8;
  7243. for (var i = 0; i < 8; i++) {
  7244. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7245. --inCount;
  7246. }
  7247. else {
  7248. break;
  7249. }
  7250. }
  7251. if (inCount === 0)
  7252. return false;
  7253. }
  7254. return true;
  7255. };
  7256. return BoundingBox;
  7257. })();
  7258. BABYLON.BoundingBox = BoundingBox;
  7259. })(BABYLON || (BABYLON = {}));
  7260. var BABYLON;
  7261. (function (BABYLON) {
  7262. var computeBoxExtents = function (axis, box) {
  7263. var p = BABYLON.Vector3.Dot(box.center, axis);
  7264. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7265. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7266. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7267. var r = r0 + r1 + r2;
  7268. return {
  7269. min: p - r,
  7270. max: p + r
  7271. };
  7272. };
  7273. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7274. var axisOverlap = function (axis, box0, box1) {
  7275. var result0 = computeBoxExtents(axis, box0);
  7276. var result1 = computeBoxExtents(axis, box1);
  7277. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7278. };
  7279. var BoundingInfo = (function () {
  7280. function BoundingInfo(minimum, maximum) {
  7281. this.minimum = minimum;
  7282. this.maximum = maximum;
  7283. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7284. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7285. }
  7286. // Methods
  7287. BoundingInfo.prototype._update = function (world) {
  7288. this.boundingBox._update(world);
  7289. this.boundingSphere._update(world);
  7290. };
  7291. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7292. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7293. return false;
  7294. return this.boundingBox.isInFrustum(frustumPlanes);
  7295. };
  7296. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7297. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7298. };
  7299. BoundingInfo.prototype._checkCollision = function (collider) {
  7300. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7301. };
  7302. BoundingInfo.prototype.intersectsPoint = function (point) {
  7303. if (!this.boundingSphere.centerWorld) {
  7304. return false;
  7305. }
  7306. if (!this.boundingSphere.intersectsPoint(point)) {
  7307. return false;
  7308. }
  7309. if (!this.boundingBox.intersectsPoint(point)) {
  7310. return false;
  7311. }
  7312. return true;
  7313. };
  7314. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7315. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7316. return false;
  7317. }
  7318. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7319. return false;
  7320. }
  7321. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7322. return false;
  7323. }
  7324. if (!precise) {
  7325. return true;
  7326. }
  7327. var box0 = this.boundingBox;
  7328. var box1 = boundingInfo.boundingBox;
  7329. if (!axisOverlap(box0.directions[0], box0, box1))
  7330. return false;
  7331. if (!axisOverlap(box0.directions[1], box0, box1))
  7332. return false;
  7333. if (!axisOverlap(box0.directions[2], box0, box1))
  7334. return false;
  7335. if (!axisOverlap(box1.directions[0], box0, box1))
  7336. return false;
  7337. if (!axisOverlap(box1.directions[1], box0, box1))
  7338. return false;
  7339. if (!axisOverlap(box1.directions[2], box0, box1))
  7340. return false;
  7341. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7342. return false;
  7343. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7344. return false;
  7345. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7346. return false;
  7347. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7348. return false;
  7349. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7350. return false;
  7351. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7352. return false;
  7353. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7354. return false;
  7355. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7356. return false;
  7357. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7358. return false;
  7359. return true;
  7360. };
  7361. return BoundingInfo;
  7362. })();
  7363. BABYLON.BoundingInfo = BoundingInfo;
  7364. })(BABYLON || (BABYLON = {}));
  7365. var BABYLON;
  7366. (function (BABYLON) {
  7367. var AbstractMesh = (function (_super) {
  7368. __extends(AbstractMesh, _super);
  7369. function AbstractMesh(name, scene) {
  7370. var _this = this;
  7371. _super.call(this, name, scene);
  7372. // Properties
  7373. this.definedFacingForward = true; // orientation for POV movement & rotation
  7374. this.position = new BABYLON.Vector3(0, 0, 0);
  7375. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7376. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7377. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7378. this.visibility = 1.0;
  7379. this.alphaIndex = Number.MAX_VALUE;
  7380. this.infiniteDistance = false;
  7381. this.isVisible = true;
  7382. this.isPickable = true;
  7383. this.showBoundingBox = false;
  7384. this.showSubMeshesBoundingBox = false;
  7385. this.onDispose = null;
  7386. this.isBlocker = false;
  7387. this.renderingGroupId = 0;
  7388. this.receiveShadows = false;
  7389. this.renderOutline = false;
  7390. this.outlineColor = BABYLON.Color3.Red();
  7391. this.outlineWidth = 0.02;
  7392. this.renderOverlay = false;
  7393. this.overlayColor = BABYLON.Color3.Red();
  7394. this.overlayAlpha = 0.5;
  7395. this.hasVertexAlpha = false;
  7396. this.useVertexColors = true;
  7397. this.applyFog = true;
  7398. this.computeBonesUsingShaders = true;
  7399. this.scalingDeterminant = 1;
  7400. this.useOctreeForRenderingSelection = true;
  7401. this.useOctreeForPicking = true;
  7402. this.useOctreeForCollisions = true;
  7403. this.layerMask = 0x0FFFFFFF;
  7404. this.alwaysSelectAsActiveMesh = false;
  7405. // Physics
  7406. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7407. // Collisions
  7408. this._checkCollisions = false;
  7409. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7410. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7411. this._collider = new BABYLON.Collider();
  7412. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7413. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7414. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7415. // Edges
  7416. this.edgesWidth = 1;
  7417. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7418. // Cache
  7419. this._localScaling = BABYLON.Matrix.Zero();
  7420. this._localRotation = BABYLON.Matrix.Zero();
  7421. this._localTranslation = BABYLON.Matrix.Zero();
  7422. this._localBillboard = BABYLON.Matrix.Zero();
  7423. this._localPivotScaling = BABYLON.Matrix.Zero();
  7424. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7425. this._localWorld = BABYLON.Matrix.Zero();
  7426. this._worldMatrix = BABYLON.Matrix.Zero();
  7427. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7428. this._absolutePosition = BABYLON.Vector3.Zero();
  7429. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7430. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7431. this._isDirty = false;
  7432. this._pivotMatrix = BABYLON.Matrix.Identity();
  7433. this._isDisposed = false;
  7434. this._renderId = 0;
  7435. this._intersectionsInProgress = new Array();
  7436. this._onAfterWorldMatrixUpdate = new Array();
  7437. this._isWorldMatrixFrozen = false;
  7438. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7439. if (collidedMesh === void 0) { collidedMesh = null; }
  7440. //TODO move this to the collision coordinator!
  7441. if (_this.getScene().workerCollisions)
  7442. newPosition.multiplyInPlace(_this._collider.radius);
  7443. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7444. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7445. _this.position.addInPlace(_this._diffPositionForCollisions);
  7446. }
  7447. if (_this.onCollide && collidedMesh) {
  7448. _this.onCollide(collidedMesh);
  7449. }
  7450. };
  7451. scene.addMesh(this);
  7452. }
  7453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7454. get: function () {
  7455. return AbstractMesh._BILLBOARDMODE_NONE;
  7456. },
  7457. enumerable: true,
  7458. configurable: true
  7459. });
  7460. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7461. get: function () {
  7462. return AbstractMesh._BILLBOARDMODE_X;
  7463. },
  7464. enumerable: true,
  7465. configurable: true
  7466. });
  7467. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7468. get: function () {
  7469. return AbstractMesh._BILLBOARDMODE_Y;
  7470. },
  7471. enumerable: true,
  7472. configurable: true
  7473. });
  7474. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7475. get: function () {
  7476. return AbstractMesh._BILLBOARDMODE_Z;
  7477. },
  7478. enumerable: true,
  7479. configurable: true
  7480. });
  7481. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7482. get: function () {
  7483. return AbstractMesh._BILLBOARDMODE_ALL;
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. // Methods
  7489. AbstractMesh.prototype.disableEdgesRendering = function () {
  7490. if (this._edgesRenderer !== undefined) {
  7491. this._edgesRenderer.dispose();
  7492. this._edgesRenderer = undefined;
  7493. }
  7494. };
  7495. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7496. if (epsilon === void 0) { epsilon = 0.95; }
  7497. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7498. this.disableEdgesRendering();
  7499. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7500. };
  7501. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7502. get: function () {
  7503. return false;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. AbstractMesh.prototype.getLOD = function (camera) {
  7509. return this;
  7510. };
  7511. AbstractMesh.prototype.getTotalVertices = function () {
  7512. return 0;
  7513. };
  7514. AbstractMesh.prototype.getIndices = function () {
  7515. return null;
  7516. };
  7517. AbstractMesh.prototype.getVerticesData = function (kind) {
  7518. return null;
  7519. };
  7520. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7521. return false;
  7522. };
  7523. AbstractMesh.prototype.getBoundingInfo = function () {
  7524. if (this._masterMesh) {
  7525. return this._masterMesh.getBoundingInfo();
  7526. }
  7527. if (!this._boundingInfo) {
  7528. this._updateBoundingInfo();
  7529. }
  7530. return this._boundingInfo;
  7531. };
  7532. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7533. get: function () {
  7534. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7535. },
  7536. enumerable: true,
  7537. configurable: true
  7538. });
  7539. AbstractMesh.prototype._preActivate = function () {
  7540. };
  7541. AbstractMesh.prototype._activate = function (renderId) {
  7542. this._renderId = renderId;
  7543. };
  7544. AbstractMesh.prototype.getWorldMatrix = function () {
  7545. if (this._masterMesh) {
  7546. return this._masterMesh.getWorldMatrix();
  7547. }
  7548. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7549. this.computeWorldMatrix();
  7550. }
  7551. return this._worldMatrix;
  7552. };
  7553. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7554. get: function () {
  7555. return this._worldMatrix;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7561. get: function () {
  7562. return this._absolutePosition;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7568. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7569. this.computeWorldMatrix(true);
  7570. this._isWorldMatrixFrozen = true;
  7571. };
  7572. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7573. this._isWorldMatrixFrozen = false;
  7574. this.computeWorldMatrix(true);
  7575. };
  7576. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7577. get: function () {
  7578. return this._isWorldMatrixFrozen;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7584. axis.normalize();
  7585. if (!this.rotationQuaternion) {
  7586. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7587. this.rotation = BABYLON.Vector3.Zero();
  7588. }
  7589. var rotationQuaternion;
  7590. if (!space || space === BABYLON.Space.LOCAL) {
  7591. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7592. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7593. }
  7594. else {
  7595. if (this.parent) {
  7596. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7597. invertParentWorldMatrix.invert();
  7598. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7599. }
  7600. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7601. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7602. }
  7603. };
  7604. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7605. var displacementVector = axis.scale(distance);
  7606. if (!space || space === BABYLON.Space.LOCAL) {
  7607. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7608. this.setPositionWithLocalVector(tempV3);
  7609. }
  7610. else {
  7611. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7612. }
  7613. };
  7614. AbstractMesh.prototype.getAbsolutePosition = function () {
  7615. this.computeWorldMatrix();
  7616. return this._absolutePosition;
  7617. };
  7618. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7619. if (!absolutePosition) {
  7620. return;
  7621. }
  7622. var absolutePositionX;
  7623. var absolutePositionY;
  7624. var absolutePositionZ;
  7625. if (absolutePosition.x === undefined) {
  7626. if (arguments.length < 3) {
  7627. return;
  7628. }
  7629. absolutePositionX = arguments[0];
  7630. absolutePositionY = arguments[1];
  7631. absolutePositionZ = arguments[2];
  7632. }
  7633. else {
  7634. absolutePositionX = absolutePosition.x;
  7635. absolutePositionY = absolutePosition.y;
  7636. absolutePositionZ = absolutePosition.z;
  7637. }
  7638. if (this.parent) {
  7639. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7640. invertParentWorldMatrix.invert();
  7641. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7642. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7643. }
  7644. else {
  7645. this.position.x = absolutePositionX;
  7646. this.position.y = absolutePositionY;
  7647. this.position.z = absolutePositionZ;
  7648. }
  7649. };
  7650. // ================================== Point of View Movement =================================
  7651. /**
  7652. * Perform relative position change from the point of view of behind the front of the mesh.
  7653. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7654. * Supports definition of mesh facing forward or backward.
  7655. * @param {number} amountRight
  7656. * @param {number} amountUp
  7657. * @param {number} amountForward
  7658. */
  7659. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7660. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7661. };
  7662. /**
  7663. * Calculate relative position change from the point of view of behind the front of the mesh.
  7664. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7665. * Supports definition of mesh facing forward or backward.
  7666. * @param {number} amountRight
  7667. * @param {number} amountUp
  7668. * @param {number} amountForward
  7669. */
  7670. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7671. var rotMatrix = new BABYLON.Matrix();
  7672. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7673. rotQuaternion.toRotationMatrix(rotMatrix);
  7674. var translationDelta = BABYLON.Vector3.Zero();
  7675. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7676. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7677. return translationDelta;
  7678. };
  7679. // ================================== Point of View Rotation =================================
  7680. /**
  7681. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7682. * Supports definition of mesh facing forward or backward.
  7683. * @param {number} flipBack
  7684. * @param {number} twirlClockwise
  7685. * @param {number} tiltRight
  7686. */
  7687. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7688. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7689. };
  7690. /**
  7691. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7692. * Supports definition of mesh facing forward or backward.
  7693. * @param {number} flipBack
  7694. * @param {number} twirlClockwise
  7695. * @param {number} tiltRight
  7696. */
  7697. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7698. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7699. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7700. };
  7701. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7702. this._pivotMatrix = matrix;
  7703. this._cache.pivotMatrixUpdated = true;
  7704. };
  7705. AbstractMesh.prototype.getPivotMatrix = function () {
  7706. return this._pivotMatrix;
  7707. };
  7708. AbstractMesh.prototype._isSynchronized = function () {
  7709. if (this._isDirty) {
  7710. return false;
  7711. }
  7712. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7713. return false;
  7714. if (this._cache.pivotMatrixUpdated) {
  7715. return false;
  7716. }
  7717. if (this.infiniteDistance) {
  7718. return false;
  7719. }
  7720. if (!this._cache.position.equals(this.position))
  7721. return false;
  7722. if (this.rotationQuaternion) {
  7723. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7724. return false;
  7725. }
  7726. else {
  7727. if (!this._cache.rotation.equals(this.rotation))
  7728. return false;
  7729. }
  7730. if (!this._cache.scaling.equals(this.scaling))
  7731. return false;
  7732. return true;
  7733. };
  7734. AbstractMesh.prototype._initCache = function () {
  7735. _super.prototype._initCache.call(this);
  7736. this._cache.localMatrixUpdated = false;
  7737. this._cache.position = BABYLON.Vector3.Zero();
  7738. this._cache.scaling = BABYLON.Vector3.Zero();
  7739. this._cache.rotation = BABYLON.Vector3.Zero();
  7740. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7741. };
  7742. AbstractMesh.prototype.markAsDirty = function (property) {
  7743. if (property === "rotation") {
  7744. this.rotationQuaternion = null;
  7745. }
  7746. this._currentRenderId = Number.MAX_VALUE;
  7747. this._isDirty = true;
  7748. };
  7749. AbstractMesh.prototype._updateBoundingInfo = function () {
  7750. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7751. this._boundingInfo._update(this.worldMatrixFromCache);
  7752. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7753. };
  7754. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7755. if (!this.subMeshes) {
  7756. return;
  7757. }
  7758. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7759. var subMesh = this.subMeshes[subIndex];
  7760. subMesh.updateBoundingInfo(matrix);
  7761. }
  7762. };
  7763. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7764. if (this._isWorldMatrixFrozen) {
  7765. return this._worldMatrix;
  7766. }
  7767. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7768. return this._worldMatrix;
  7769. }
  7770. this._cache.position.copyFrom(this.position);
  7771. this._cache.scaling.copyFrom(this.scaling);
  7772. this._cache.pivotMatrixUpdated = false;
  7773. this._currentRenderId = this.getScene().getRenderId();
  7774. this._isDirty = false;
  7775. // Scaling
  7776. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7777. // Rotation
  7778. if (this.rotationQuaternion) {
  7779. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7780. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7781. }
  7782. else {
  7783. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7784. this._cache.rotation.copyFrom(this.rotation);
  7785. }
  7786. // Translation
  7787. if (this.infiniteDistance && !this.parent) {
  7788. var camera = this.getScene().activeCamera;
  7789. if (camera) {
  7790. var cameraWorldMatrix = camera.getWorldMatrix();
  7791. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7792. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7793. }
  7794. }
  7795. else {
  7796. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7797. }
  7798. // Composing transformations
  7799. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7800. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7801. // Billboarding
  7802. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7803. var localPosition = this.position.clone();
  7804. var zero = this.getScene().activeCamera.globalPosition.clone();
  7805. if (this.parent && this.parent.position) {
  7806. localPosition.addInPlace(this.parent.position);
  7807. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7808. }
  7809. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7810. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7811. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7812. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7813. zero.y = localPosition.y + 0.001;
  7814. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7815. zero.z = localPosition.z + 0.001;
  7816. }
  7817. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7818. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7819. this._localBillboard.invert();
  7820. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7821. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7822. }
  7823. // Local world
  7824. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7825. // Parent
  7826. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7827. this._markSyncedWithParent();
  7828. if (this._meshToBoneReferal) {
  7829. if (!this._localMeshReferalTransform) {
  7830. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7831. }
  7832. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7833. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7834. }
  7835. else {
  7836. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7837. }
  7838. }
  7839. else {
  7840. this._worldMatrix.copyFrom(this._localWorld);
  7841. }
  7842. // Bounding info
  7843. this._updateBoundingInfo();
  7844. // Absolute position
  7845. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7846. // Callbacks
  7847. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7848. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7849. }
  7850. return this._worldMatrix;
  7851. };
  7852. /**
  7853. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7854. * @param func: callback function to add
  7855. */
  7856. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7857. this._onAfterWorldMatrixUpdate.push(func);
  7858. };
  7859. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7860. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7861. if (index > -1) {
  7862. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7863. }
  7864. };
  7865. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7866. this.computeWorldMatrix();
  7867. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7868. };
  7869. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7870. this.computeWorldMatrix();
  7871. var invLocalWorldMatrix = this._localWorld.clone();
  7872. invLocalWorldMatrix.invert();
  7873. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7874. };
  7875. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7876. this.computeWorldMatrix(true);
  7877. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7878. };
  7879. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7880. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7881. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7882. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7883. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7884. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7885. /// <returns>Mesh oriented towards targetMesh</returns>
  7886. yawCor = yawCor || 0; // default to zero if undefined
  7887. pitchCor = pitchCor || 0;
  7888. rollCor = rollCor || 0;
  7889. var dv = targetPoint.subtract(this.position);
  7890. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7891. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7892. var pitch = Math.atan2(dv.y, len);
  7893. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7894. };
  7895. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  7896. this._meshToBoneReferal = affectedMesh;
  7897. this.parent = bone;
  7898. if (bone.getWorldMatrix().determinant() < 0) {
  7899. this.scalingDeterminant *= -1;
  7900. }
  7901. };
  7902. AbstractMesh.prototype.detachFromBone = function () {
  7903. if (this.parent.getWorldMatrix().determinant() < 0) {
  7904. this.scalingDeterminant *= -1;
  7905. }
  7906. this._meshToBoneReferal = null;
  7907. this.parent = null;
  7908. };
  7909. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7910. return this._boundingInfo.isInFrustum(frustumPlanes);
  7911. };
  7912. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7913. if (!camera) {
  7914. camera = this.getScene().activeCamera;
  7915. }
  7916. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7917. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7918. return false;
  7919. }
  7920. return true;
  7921. };
  7922. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7923. if (!this._boundingInfo || !mesh._boundingInfo) {
  7924. return false;
  7925. }
  7926. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7927. };
  7928. AbstractMesh.prototype.intersectsPoint = function (point) {
  7929. if (!this._boundingInfo) {
  7930. return false;
  7931. }
  7932. return this._boundingInfo.intersectsPoint(point);
  7933. };
  7934. // Physics
  7935. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7936. var physicsEngine = this.getScene().getPhysicsEngine();
  7937. if (!physicsEngine) {
  7938. return null;
  7939. }
  7940. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7941. if (impostor.impostor) {
  7942. // Old API
  7943. options = impostor;
  7944. impostor = impostor.impostor;
  7945. }
  7946. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7947. physicsEngine._unregisterMesh(this);
  7948. return null;
  7949. }
  7950. if (!options) {
  7951. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7952. }
  7953. else {
  7954. if (!options.mass && options.mass !== 0)
  7955. options.mass = 0;
  7956. if (!options.friction && options.friction !== 0)
  7957. options.friction = 0.2;
  7958. if (!options.restitution && options.restitution !== 0)
  7959. options.restitution = 0.2;
  7960. }
  7961. this._physicImpostor = impostor;
  7962. this._physicsMass = options.mass;
  7963. this._physicsFriction = options.friction;
  7964. this._physicRestitution = options.restitution;
  7965. return physicsEngine._registerMesh(this, impostor, options);
  7966. };
  7967. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7968. if (!this._physicImpostor) {
  7969. return BABYLON.PhysicsEngine.NoImpostor;
  7970. }
  7971. return this._physicImpostor;
  7972. };
  7973. AbstractMesh.prototype.getPhysicsMass = function () {
  7974. if (!this._physicsMass) {
  7975. return 0;
  7976. }
  7977. return this._physicsMass;
  7978. };
  7979. AbstractMesh.prototype.getPhysicsFriction = function () {
  7980. if (!this._physicsFriction) {
  7981. return 0;
  7982. }
  7983. return this._physicsFriction;
  7984. };
  7985. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7986. if (!this._physicRestitution) {
  7987. return 0;
  7988. }
  7989. return this._physicRestitution;
  7990. };
  7991. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7992. if (!camera) {
  7993. camera = this.getScene().activeCamera;
  7994. }
  7995. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  7996. };
  7997. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  7998. if (!camera) {
  7999. camera = this.getScene().activeCamera;
  8000. }
  8001. return this.absolutePosition.subtract(camera.position).length();
  8002. };
  8003. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8004. if (!this._physicImpostor) {
  8005. return;
  8006. }
  8007. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8008. };
  8009. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8010. if (!this._physicImpostor) {
  8011. return;
  8012. }
  8013. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8014. };
  8015. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8016. if (!this._physicImpostor) {
  8017. return;
  8018. }
  8019. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8020. };
  8021. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8022. // Collisions
  8023. get: function () {
  8024. return this._checkCollisions;
  8025. },
  8026. set: function (collisionEnabled) {
  8027. this._checkCollisions = collisionEnabled;
  8028. if (this.getScene().workerCollisions) {
  8029. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8030. }
  8031. },
  8032. enumerable: true,
  8033. configurable: true
  8034. });
  8035. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8036. var globalPosition = this.getAbsolutePosition();
  8037. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8038. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8039. this._collider.radius = this.ellipsoid;
  8040. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8041. };
  8042. // Submeshes octree
  8043. /**
  8044. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8045. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8046. */
  8047. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8048. if (maxCapacity === void 0) { maxCapacity = 64; }
  8049. if (maxDepth === void 0) { maxDepth = 2; }
  8050. if (!this._submeshesOctree) {
  8051. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8052. }
  8053. this.computeWorldMatrix(true);
  8054. // Update octree
  8055. var bbox = this.getBoundingInfo().boundingBox;
  8056. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8057. return this._submeshesOctree;
  8058. };
  8059. // Collisions
  8060. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8061. this._generatePointsArray();
  8062. // Transformation
  8063. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8064. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8065. subMesh._lastColliderWorldVertices = [];
  8066. subMesh._trianglePlanes = [];
  8067. var start = subMesh.verticesStart;
  8068. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8069. for (var i = start; i < end; i++) {
  8070. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8071. }
  8072. }
  8073. // Collide
  8074. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8075. if (collider.collisionFound) {
  8076. collider.collidedMesh = this;
  8077. }
  8078. };
  8079. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8080. var subMeshes;
  8081. var len;
  8082. // Octrees
  8083. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8084. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8085. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8086. len = intersections.length;
  8087. subMeshes = intersections.data;
  8088. }
  8089. else {
  8090. subMeshes = this.subMeshes;
  8091. len = subMeshes.length;
  8092. }
  8093. for (var index = 0; index < len; index++) {
  8094. var subMesh = subMeshes[index];
  8095. // Bounding test
  8096. if (len > 1 && !subMesh._checkCollision(collider))
  8097. continue;
  8098. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8099. }
  8100. };
  8101. AbstractMesh.prototype._checkCollision = function (collider) {
  8102. // Bounding box test
  8103. if (!this._boundingInfo._checkCollision(collider))
  8104. return;
  8105. // Transformation matrix
  8106. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8107. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8108. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8109. };
  8110. // Picking
  8111. AbstractMesh.prototype._generatePointsArray = function () {
  8112. return false;
  8113. };
  8114. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8115. var pickingInfo = new BABYLON.PickingInfo();
  8116. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8117. return pickingInfo;
  8118. }
  8119. if (!this._generatePointsArray()) {
  8120. return pickingInfo;
  8121. }
  8122. var intersectInfo = null;
  8123. // Octrees
  8124. var subMeshes;
  8125. var len;
  8126. if (this._submeshesOctree && this.useOctreeForPicking) {
  8127. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8128. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8129. len = intersections.length;
  8130. subMeshes = intersections.data;
  8131. }
  8132. else {
  8133. subMeshes = this.subMeshes;
  8134. len = subMeshes.length;
  8135. }
  8136. for (var index = 0; index < len; index++) {
  8137. var subMesh = subMeshes[index];
  8138. // Bounding test
  8139. if (len > 1 && !subMesh.canIntersects(ray))
  8140. continue;
  8141. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8142. if (currentIntersectInfo) {
  8143. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8144. intersectInfo = currentIntersectInfo;
  8145. intersectInfo.subMeshId = index;
  8146. if (fastCheck) {
  8147. break;
  8148. }
  8149. }
  8150. }
  8151. }
  8152. if (intersectInfo) {
  8153. // Get picked point
  8154. var world = this.getWorldMatrix();
  8155. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8156. var direction = ray.direction.clone();
  8157. direction = direction.scale(intersectInfo.distance);
  8158. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8159. var pickedPoint = worldOrigin.add(worldDirection);
  8160. // Return result
  8161. pickingInfo.hit = true;
  8162. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8163. pickingInfo.pickedPoint = pickedPoint;
  8164. pickingInfo.pickedMesh = this;
  8165. pickingInfo.bu = intersectInfo.bu;
  8166. pickingInfo.bv = intersectInfo.bv;
  8167. pickingInfo.faceId = intersectInfo.faceId;
  8168. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8169. return pickingInfo;
  8170. }
  8171. return pickingInfo;
  8172. };
  8173. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8174. return null;
  8175. };
  8176. AbstractMesh.prototype.releaseSubMeshes = function () {
  8177. if (this.subMeshes) {
  8178. while (this.subMeshes.length) {
  8179. this.subMeshes[0].dispose();
  8180. }
  8181. }
  8182. else {
  8183. this.subMeshes = new Array();
  8184. }
  8185. };
  8186. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8187. var index;
  8188. // Physics
  8189. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8190. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8191. }
  8192. // Intersections in progress
  8193. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8194. var other = this._intersectionsInProgress[index];
  8195. var pos = other._intersectionsInProgress.indexOf(this);
  8196. other._intersectionsInProgress.splice(pos, 1);
  8197. }
  8198. this._intersectionsInProgress = [];
  8199. // Edges
  8200. if (this._edgesRenderer) {
  8201. this._edgesRenderer.dispose();
  8202. this._edgesRenderer = null;
  8203. }
  8204. // SubMeshes
  8205. this.releaseSubMeshes();
  8206. // Remove from scene
  8207. this.getScene().removeMesh(this);
  8208. if (!doNotRecurse) {
  8209. // Particles
  8210. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8211. if (this.getScene().particleSystems[index].emitter === this) {
  8212. this.getScene().particleSystems[index].dispose();
  8213. index--;
  8214. }
  8215. }
  8216. // Children
  8217. var objects = this.getScene().meshes.slice(0);
  8218. for (index = 0; index < objects.length; index++) {
  8219. if (objects[index].parent === this) {
  8220. objects[index].dispose();
  8221. }
  8222. }
  8223. }
  8224. else {
  8225. for (index = 0; index < this.getScene().meshes.length; index++) {
  8226. var obj = this.getScene().meshes[index];
  8227. if (obj.parent === this) {
  8228. obj.parent = null;
  8229. obj.computeWorldMatrix(true);
  8230. }
  8231. }
  8232. }
  8233. this._onAfterWorldMatrixUpdate = [];
  8234. this._isDisposed = true;
  8235. // Callback
  8236. if (this.onDispose) {
  8237. this.onDispose();
  8238. }
  8239. };
  8240. // Statics
  8241. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8242. AbstractMesh._BILLBOARDMODE_X = 1;
  8243. AbstractMesh._BILLBOARDMODE_Y = 2;
  8244. AbstractMesh._BILLBOARDMODE_Z = 4;
  8245. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8246. return AbstractMesh;
  8247. })(BABYLON.Node);
  8248. BABYLON.AbstractMesh = AbstractMesh;
  8249. })(BABYLON || (BABYLON = {}));
  8250. var BABYLON;
  8251. (function (BABYLON) {
  8252. var Light = (function (_super) {
  8253. __extends(Light, _super);
  8254. function Light(name, scene) {
  8255. _super.call(this, name, scene);
  8256. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8257. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8258. this.intensity = 1.0;
  8259. this.range = Number.MAX_VALUE;
  8260. this.includeOnlyWithLayerMask = 0;
  8261. this.includedOnlyMeshes = new Array();
  8262. this.excludedMeshes = new Array();
  8263. this.excludeWithLayerMask = 0;
  8264. this._excludedMeshesIds = new Array();
  8265. this._includedOnlyMeshesIds = new Array();
  8266. scene.addLight(this);
  8267. }
  8268. Light.prototype.getShadowGenerator = function () {
  8269. return this._shadowGenerator;
  8270. };
  8271. Light.prototype.getAbsolutePosition = function () {
  8272. return BABYLON.Vector3.Zero();
  8273. };
  8274. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8275. };
  8276. Light.prototype._getWorldMatrix = function () {
  8277. return BABYLON.Matrix.Identity();
  8278. };
  8279. Light.prototype.canAffectMesh = function (mesh) {
  8280. if (!mesh) {
  8281. return true;
  8282. }
  8283. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8284. return false;
  8285. }
  8286. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8287. return false;
  8288. }
  8289. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8290. return false;
  8291. }
  8292. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8293. return false;
  8294. }
  8295. return true;
  8296. };
  8297. Light.prototype.getWorldMatrix = function () {
  8298. this._currentRenderId = this.getScene().getRenderId();
  8299. var worldMatrix = this._getWorldMatrix();
  8300. if (this.parent && this.parent.getWorldMatrix) {
  8301. if (!this._parentedWorldMatrix) {
  8302. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8303. }
  8304. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8305. this._markSyncedWithParent();
  8306. return this._parentedWorldMatrix;
  8307. }
  8308. return worldMatrix;
  8309. };
  8310. Light.prototype.dispose = function () {
  8311. if (this._shadowGenerator) {
  8312. this._shadowGenerator.dispose();
  8313. this._shadowGenerator = null;
  8314. }
  8315. // Remove from scene
  8316. this.getScene().removeLight(this);
  8317. };
  8318. return Light;
  8319. })(BABYLON.Node);
  8320. BABYLON.Light = Light;
  8321. })(BABYLON || (BABYLON = {}));
  8322. var BABYLON;
  8323. (function (BABYLON) {
  8324. var PointLight = (function (_super) {
  8325. __extends(PointLight, _super);
  8326. function PointLight(name, position, scene) {
  8327. _super.call(this, name, scene);
  8328. this.position = position;
  8329. }
  8330. PointLight.prototype.getAbsolutePosition = function () {
  8331. return this._transformedPosition ? this._transformedPosition : this.position;
  8332. };
  8333. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8334. if (this.parent && this.parent.getWorldMatrix) {
  8335. if (!this._transformedPosition) {
  8336. this._transformedPosition = BABYLON.Vector3.Zero();
  8337. }
  8338. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8339. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8340. return;
  8341. }
  8342. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8343. };
  8344. PointLight.prototype.getShadowGenerator = function () {
  8345. return null;
  8346. };
  8347. PointLight.prototype._getWorldMatrix = function () {
  8348. if (!this._worldMatrix) {
  8349. this._worldMatrix = BABYLON.Matrix.Identity();
  8350. }
  8351. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8352. return this._worldMatrix;
  8353. };
  8354. return PointLight;
  8355. })(BABYLON.Light);
  8356. BABYLON.PointLight = PointLight;
  8357. })(BABYLON || (BABYLON = {}));
  8358. var BABYLON;
  8359. (function (BABYLON) {
  8360. var SpotLight = (function (_super) {
  8361. __extends(SpotLight, _super);
  8362. function SpotLight(name, position, direction, angle, exponent, scene) {
  8363. _super.call(this, name, scene);
  8364. this.position = position;
  8365. this.direction = direction;
  8366. this.angle = angle;
  8367. this.exponent = exponent;
  8368. }
  8369. SpotLight.prototype.getAbsolutePosition = function () {
  8370. return this.transformedPosition ? this.transformedPosition : this.position;
  8371. };
  8372. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8373. var activeCamera = this.getScene().activeCamera;
  8374. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8375. };
  8376. SpotLight.prototype.supportsVSM = function () {
  8377. return true;
  8378. };
  8379. SpotLight.prototype.needRefreshPerFrame = function () {
  8380. return false;
  8381. };
  8382. SpotLight.prototype.setDirectionToTarget = function (target) {
  8383. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8384. return this.direction;
  8385. };
  8386. SpotLight.prototype.computeTransformedPosition = function () {
  8387. if (this.parent && this.parent.getWorldMatrix) {
  8388. if (!this.transformedPosition) {
  8389. this.transformedPosition = BABYLON.Vector3.Zero();
  8390. }
  8391. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8392. return true;
  8393. }
  8394. return false;
  8395. };
  8396. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8397. var normalizeDirection;
  8398. if (this.parent && this.parent.getWorldMatrix) {
  8399. if (!this._transformedDirection) {
  8400. this._transformedDirection = BABYLON.Vector3.Zero();
  8401. }
  8402. this.computeTransformedPosition();
  8403. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8404. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8405. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8406. }
  8407. else {
  8408. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8409. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8410. }
  8411. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8412. };
  8413. SpotLight.prototype._getWorldMatrix = function () {
  8414. if (!this._worldMatrix) {
  8415. this._worldMatrix = BABYLON.Matrix.Identity();
  8416. }
  8417. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8418. return this._worldMatrix;
  8419. };
  8420. return SpotLight;
  8421. })(BABYLON.Light);
  8422. BABYLON.SpotLight = SpotLight;
  8423. })(BABYLON || (BABYLON = {}));
  8424. var BABYLON;
  8425. (function (BABYLON) {
  8426. var HemisphericLight = (function (_super) {
  8427. __extends(HemisphericLight, _super);
  8428. function HemisphericLight(name, direction, scene) {
  8429. _super.call(this, name, scene);
  8430. this.direction = direction;
  8431. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8432. }
  8433. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8434. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8435. return this.direction;
  8436. };
  8437. HemisphericLight.prototype.getShadowGenerator = function () {
  8438. return null;
  8439. };
  8440. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8441. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8442. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8443. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8444. };
  8445. HemisphericLight.prototype._getWorldMatrix = function () {
  8446. if (!this._worldMatrix) {
  8447. this._worldMatrix = BABYLON.Matrix.Identity();
  8448. }
  8449. return this._worldMatrix;
  8450. };
  8451. return HemisphericLight;
  8452. })(BABYLON.Light);
  8453. BABYLON.HemisphericLight = HemisphericLight;
  8454. })(BABYLON || (BABYLON = {}));
  8455. var BABYLON;
  8456. (function (BABYLON) {
  8457. var DirectionalLight = (function (_super) {
  8458. __extends(DirectionalLight, _super);
  8459. function DirectionalLight(name, direction, scene) {
  8460. _super.call(this, name, scene);
  8461. this.direction = direction;
  8462. this.shadowOrthoScale = 0.5;
  8463. this.autoUpdateExtends = true;
  8464. // Cache
  8465. this._orthoLeft = Number.MAX_VALUE;
  8466. this._orthoRight = Number.MIN_VALUE;
  8467. this._orthoTop = Number.MIN_VALUE;
  8468. this._orthoBottom = Number.MAX_VALUE;
  8469. this.position = direction.scale(-1);
  8470. }
  8471. DirectionalLight.prototype.getAbsolutePosition = function () {
  8472. return this.transformedPosition ? this.transformedPosition : this.position;
  8473. };
  8474. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8475. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8476. return this.direction;
  8477. };
  8478. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8479. var activeCamera = this.getScene().activeCamera;
  8480. // Check extends
  8481. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8482. var tempVector3 = BABYLON.Vector3.Zero();
  8483. this._orthoLeft = Number.MAX_VALUE;
  8484. this._orthoRight = Number.MIN_VALUE;
  8485. this._orthoTop = Number.MIN_VALUE;
  8486. this._orthoBottom = Number.MAX_VALUE;
  8487. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8488. var mesh = renderList[meshIndex];
  8489. if (!mesh) {
  8490. continue;
  8491. }
  8492. var boundingInfo = mesh.getBoundingInfo();
  8493. if (!boundingInfo) {
  8494. continue;
  8495. }
  8496. var boundingBox = boundingInfo.boundingBox;
  8497. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8498. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8499. if (tempVector3.x < this._orthoLeft)
  8500. this._orthoLeft = tempVector3.x;
  8501. if (tempVector3.y < this._orthoBottom)
  8502. this._orthoBottom = tempVector3.y;
  8503. if (tempVector3.x > this._orthoRight)
  8504. this._orthoRight = tempVector3.x;
  8505. if (tempVector3.y > this._orthoTop)
  8506. this._orthoTop = tempVector3.y;
  8507. }
  8508. }
  8509. }
  8510. var xOffset = this._orthoRight - this._orthoLeft;
  8511. var yOffset = this._orthoTop - this._orthoBottom;
  8512. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8513. };
  8514. DirectionalLight.prototype.supportsVSM = function () {
  8515. return true;
  8516. };
  8517. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8518. return true;
  8519. };
  8520. DirectionalLight.prototype.computeTransformedPosition = function () {
  8521. if (this.parent && this.parent.getWorldMatrix) {
  8522. if (!this.transformedPosition) {
  8523. this.transformedPosition = BABYLON.Vector3.Zero();
  8524. }
  8525. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8526. return true;
  8527. }
  8528. return false;
  8529. };
  8530. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8531. if (this.parent && this.parent.getWorldMatrix) {
  8532. if (!this._transformedDirection) {
  8533. this._transformedDirection = BABYLON.Vector3.Zero();
  8534. }
  8535. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8536. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8537. return;
  8538. }
  8539. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8540. };
  8541. DirectionalLight.prototype._getWorldMatrix = function () {
  8542. if (!this._worldMatrix) {
  8543. this._worldMatrix = BABYLON.Matrix.Identity();
  8544. }
  8545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8546. return this._worldMatrix;
  8547. };
  8548. return DirectionalLight;
  8549. })(BABYLON.Light);
  8550. BABYLON.DirectionalLight = DirectionalLight;
  8551. })(BABYLON || (BABYLON = {}));
  8552. var BABYLON;
  8553. (function (BABYLON) {
  8554. var ShadowGenerator = (function () {
  8555. function ShadowGenerator(mapSize, light) {
  8556. var _this = this;
  8557. // Members
  8558. this._filter = ShadowGenerator.FILTER_NONE;
  8559. this.blurScale = 2;
  8560. this._blurBoxOffset = 0;
  8561. this._bias = 0.00005;
  8562. this._lightDirection = BABYLON.Vector3.Zero();
  8563. this._darkness = 0;
  8564. this._transparencyShadow = false;
  8565. this._viewMatrix = BABYLON.Matrix.Zero();
  8566. this._projectionMatrix = BABYLON.Matrix.Zero();
  8567. this._transformMatrix = BABYLON.Matrix.Zero();
  8568. this._worldViewProjection = BABYLON.Matrix.Zero();
  8569. this._light = light;
  8570. this._scene = light.getScene();
  8571. this._mapSize = mapSize;
  8572. light._shadowGenerator = this;
  8573. // Render target
  8574. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8575. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8576. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8577. this._shadowMap.anisotropicFilteringLevel = 1;
  8578. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8579. this._shadowMap.renderParticles = false;
  8580. this._shadowMap.onAfterUnbind = function () {
  8581. if (!_this.useBlurVarianceShadowMap) {
  8582. return;
  8583. }
  8584. if (!_this._shadowMap2) {
  8585. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8586. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8587. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8588. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8589. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8590. _this._downSamplePostprocess.onApply = function (effect) {
  8591. effect.setTexture("textureSampler", _this._shadowMap);
  8592. };
  8593. _this.blurBoxOffset = 1;
  8594. }
  8595. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8596. };
  8597. // Custom render function
  8598. var renderSubMesh = function (subMesh) {
  8599. var mesh = subMesh.getRenderingMesh();
  8600. var scene = _this._scene;
  8601. var engine = scene.getEngine();
  8602. // Culling
  8603. engine.setState(subMesh.getMaterial().backFaceCulling);
  8604. // Managing instances
  8605. var batch = mesh._getInstancesRenderList(subMesh._id);
  8606. if (batch.mustReturn) {
  8607. return;
  8608. }
  8609. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8610. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8611. engine.enableEffect(_this._effect);
  8612. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8613. var material = subMesh.getMaterial();
  8614. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8615. // Alpha test
  8616. if (material && material.needAlphaTesting()) {
  8617. var alphaTexture = material.getAlphaTestTexture();
  8618. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8619. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8620. }
  8621. // Bones
  8622. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8623. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8624. }
  8625. // Draw
  8626. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8627. }
  8628. else {
  8629. // Need to reset refresh rate of the shadowMap
  8630. _this._shadowMap.resetRefreshCounter();
  8631. }
  8632. };
  8633. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8634. var index;
  8635. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8636. renderSubMesh(opaqueSubMeshes.data[index]);
  8637. }
  8638. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8639. renderSubMesh(alphaTestSubMeshes.data[index]);
  8640. }
  8641. if (_this._transparencyShadow) {
  8642. for (index = 0; index < transparentSubMeshes.length; index++) {
  8643. renderSubMesh(transparentSubMeshes.data[index]);
  8644. }
  8645. }
  8646. };
  8647. this._shadowMap.onClear = function (engine) {
  8648. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8649. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8650. }
  8651. else {
  8652. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8653. }
  8654. };
  8655. }
  8656. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8657. // Static
  8658. get: function () {
  8659. return ShadowGenerator._FILTER_NONE;
  8660. },
  8661. enumerable: true,
  8662. configurable: true
  8663. });
  8664. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8665. get: function () {
  8666. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8667. },
  8668. enumerable: true,
  8669. configurable: true
  8670. });
  8671. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8672. get: function () {
  8673. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8679. get: function () {
  8680. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8686. get: function () {
  8687. return this._bias;
  8688. },
  8689. set: function (bias) {
  8690. this._bias = bias;
  8691. },
  8692. enumerable: true,
  8693. configurable: true
  8694. });
  8695. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8696. get: function () {
  8697. return this._blurBoxOffset;
  8698. },
  8699. set: function (value) {
  8700. var _this = this;
  8701. if (this._blurBoxOffset === value) {
  8702. return;
  8703. }
  8704. this._blurBoxOffset = value;
  8705. if (this._boxBlurPostprocess) {
  8706. this._boxBlurPostprocess.dispose();
  8707. }
  8708. 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);
  8709. this._boxBlurPostprocess.onApply = function (effect) {
  8710. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8711. };
  8712. },
  8713. enumerable: true,
  8714. configurable: true
  8715. });
  8716. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8717. get: function () {
  8718. return this._filter;
  8719. },
  8720. set: function (value) {
  8721. if (this._filter === value) {
  8722. return;
  8723. }
  8724. this._filter = value;
  8725. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8726. this._shadowMap.anisotropicFilteringLevel = 16;
  8727. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8728. }
  8729. else {
  8730. this._shadowMap.anisotropicFilteringLevel = 1;
  8731. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8732. }
  8733. },
  8734. enumerable: true,
  8735. configurable: true
  8736. });
  8737. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8738. get: function () {
  8739. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8740. },
  8741. set: function (value) {
  8742. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8743. },
  8744. enumerable: true,
  8745. configurable: true
  8746. });
  8747. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8748. get: function () {
  8749. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8750. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8751. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8752. },
  8753. set: function (value) {
  8754. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8760. get: function () {
  8761. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8762. },
  8763. set: function (value) {
  8764. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8765. },
  8766. enumerable: true,
  8767. configurable: true
  8768. });
  8769. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8770. var defines = [];
  8771. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8772. defines.push("#define VSM");
  8773. }
  8774. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8775. var mesh = subMesh.getMesh();
  8776. var material = subMesh.getMaterial();
  8777. // Alpha test
  8778. if (material && material.needAlphaTesting()) {
  8779. defines.push("#define ALPHATEST");
  8780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8781. attribs.push(BABYLON.VertexBuffer.UVKind);
  8782. defines.push("#define UV1");
  8783. }
  8784. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8785. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8786. defines.push("#define UV2");
  8787. }
  8788. }
  8789. // Bones
  8790. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8791. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8792. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8793. defines.push("#define BONES");
  8794. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8795. }
  8796. // Instances
  8797. if (useInstances) {
  8798. defines.push("#define INSTANCES");
  8799. attribs.push("world0");
  8800. attribs.push("world1");
  8801. attribs.push("world2");
  8802. attribs.push("world3");
  8803. }
  8804. // Get correct effect
  8805. var join = defines.join("\n");
  8806. if (this._cachedDefines !== join) {
  8807. this._cachedDefines = join;
  8808. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8809. }
  8810. return this._effect.isReady();
  8811. };
  8812. ShadowGenerator.prototype.getShadowMap = function () {
  8813. return this._shadowMap;
  8814. };
  8815. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8816. if (this._shadowMap2) {
  8817. return this._shadowMap2;
  8818. }
  8819. return this._shadowMap;
  8820. };
  8821. ShadowGenerator.prototype.getLight = function () {
  8822. return this._light;
  8823. };
  8824. // Methods
  8825. ShadowGenerator.prototype.getTransformMatrix = function () {
  8826. var scene = this._scene;
  8827. if (this._currentRenderID === scene.getRenderId()) {
  8828. return this._transformMatrix;
  8829. }
  8830. this._currentRenderID = scene.getRenderId();
  8831. var lightPosition = this._light.position;
  8832. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  8833. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  8834. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  8835. }
  8836. if (this._light.computeTransformedPosition()) {
  8837. lightPosition = this._light.transformedPosition;
  8838. }
  8839. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  8840. this._cachedPosition = lightPosition.clone();
  8841. this._cachedDirection = this._lightDirection.clone();
  8842. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8843. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8844. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8845. }
  8846. return this._transformMatrix;
  8847. };
  8848. ShadowGenerator.prototype.getDarkness = function () {
  8849. return this._darkness;
  8850. };
  8851. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8852. if (darkness >= 1.0)
  8853. this._darkness = 1.0;
  8854. else if (darkness <= 0.0)
  8855. this._darkness = 0.0;
  8856. else
  8857. this._darkness = darkness;
  8858. };
  8859. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8860. this._transparencyShadow = hasShadow;
  8861. };
  8862. ShadowGenerator.prototype._packHalf = function (depth) {
  8863. var scale = depth * 255.0;
  8864. var fract = scale - Math.floor(scale);
  8865. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8866. };
  8867. ShadowGenerator.prototype.dispose = function () {
  8868. this._shadowMap.dispose();
  8869. if (this._shadowMap2) {
  8870. this._shadowMap2.dispose();
  8871. }
  8872. if (this._downSamplePostprocess) {
  8873. this._downSamplePostprocess.dispose();
  8874. }
  8875. if (this._boxBlurPostprocess) {
  8876. this._boxBlurPostprocess.dispose();
  8877. }
  8878. };
  8879. ShadowGenerator._FILTER_NONE = 0;
  8880. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8881. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8882. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8883. return ShadowGenerator;
  8884. })();
  8885. BABYLON.ShadowGenerator = ShadowGenerator;
  8886. })(BABYLON || (BABYLON = {}));
  8887. var BABYLON;
  8888. (function (BABYLON) {
  8889. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8890. if (boxMin.x > sphereCenter.x + sphereRadius)
  8891. return false;
  8892. if (sphereCenter.x - sphereRadius > boxMax.x)
  8893. return false;
  8894. if (boxMin.y > sphereCenter.y + sphereRadius)
  8895. return false;
  8896. if (sphereCenter.y - sphereRadius > boxMax.y)
  8897. return false;
  8898. if (boxMin.z > sphereCenter.z + sphereRadius)
  8899. return false;
  8900. if (sphereCenter.z - sphereRadius > boxMax.z)
  8901. return false;
  8902. return true;
  8903. };
  8904. var getLowestRoot = function (a, b, c, maxR) {
  8905. var determinant = b * b - 4.0 * a * c;
  8906. var result = { root: 0, found: false };
  8907. if (determinant < 0)
  8908. return result;
  8909. var sqrtD = Math.sqrt(determinant);
  8910. var r1 = (-b - sqrtD) / (2.0 * a);
  8911. var r2 = (-b + sqrtD) / (2.0 * a);
  8912. if (r1 > r2) {
  8913. var temp = r2;
  8914. r2 = r1;
  8915. r1 = temp;
  8916. }
  8917. if (r1 > 0 && r1 < maxR) {
  8918. result.root = r1;
  8919. result.found = true;
  8920. return result;
  8921. }
  8922. if (r2 > 0 && r2 < maxR) {
  8923. result.root = r2;
  8924. result.found = true;
  8925. return result;
  8926. }
  8927. return result;
  8928. };
  8929. var Collider = (function () {
  8930. function Collider() {
  8931. this.radius = new BABYLON.Vector3(1, 1, 1);
  8932. this.retry = 0;
  8933. this.basePointWorld = BABYLON.Vector3.Zero();
  8934. this.velocityWorld = BABYLON.Vector3.Zero();
  8935. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8936. this._collisionPoint = BABYLON.Vector3.Zero();
  8937. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8938. this._tempVector = BABYLON.Vector3.Zero();
  8939. this._tempVector2 = BABYLON.Vector3.Zero();
  8940. this._tempVector3 = BABYLON.Vector3.Zero();
  8941. this._tempVector4 = BABYLON.Vector3.Zero();
  8942. this._edge = BABYLON.Vector3.Zero();
  8943. this._baseToVertex = BABYLON.Vector3.Zero();
  8944. this._destinationPoint = BABYLON.Vector3.Zero();
  8945. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8946. this._displacementVector = BABYLON.Vector3.Zero();
  8947. }
  8948. // Methods
  8949. Collider.prototype._initialize = function (source, dir, e) {
  8950. this.velocity = dir;
  8951. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8952. this.basePoint = source;
  8953. source.multiplyToRef(this.radius, this.basePointWorld);
  8954. dir.multiplyToRef(this.radius, this.velocityWorld);
  8955. this.velocityWorldLength = this.velocityWorld.length();
  8956. this.epsilon = e;
  8957. this.collisionFound = false;
  8958. };
  8959. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8960. pa.subtractToRef(point, this._tempVector);
  8961. pb.subtractToRef(point, this._tempVector2);
  8962. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8963. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8964. if (d < 0)
  8965. return false;
  8966. pc.subtractToRef(point, this._tempVector3);
  8967. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8968. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8969. if (d < 0)
  8970. return false;
  8971. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8972. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8973. return d >= 0;
  8974. };
  8975. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8976. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8977. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8978. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8979. return false;
  8980. }
  8981. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8982. return false;
  8983. return true;
  8984. };
  8985. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8986. var t0;
  8987. var embeddedInPlane = false;
  8988. //defensive programming, actually not needed.
  8989. if (!trianglePlaneArray) {
  8990. trianglePlaneArray = [];
  8991. }
  8992. if (!trianglePlaneArray[faceIndex]) {
  8993. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  8994. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  8995. }
  8996. var trianglePlane = trianglePlaneArray[faceIndex];
  8997. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  8998. return;
  8999. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9000. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9001. if (normalDotVelocity == 0) {
  9002. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9003. return;
  9004. embeddedInPlane = true;
  9005. t0 = 0;
  9006. }
  9007. else {
  9008. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9009. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9010. if (t0 > t1) {
  9011. var temp = t1;
  9012. t1 = t0;
  9013. t0 = temp;
  9014. }
  9015. if (t0 > 1.0 || t1 < 0.0)
  9016. return;
  9017. if (t0 < 0)
  9018. t0 = 0;
  9019. if (t0 > 1.0)
  9020. t0 = 1.0;
  9021. }
  9022. this._collisionPoint.copyFromFloats(0, 0, 0);
  9023. var found = false;
  9024. var t = 1.0;
  9025. if (!embeddedInPlane) {
  9026. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9027. this.velocity.scaleToRef(t0, this._tempVector);
  9028. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9029. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9030. found = true;
  9031. t = t0;
  9032. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9033. }
  9034. }
  9035. if (!found) {
  9036. var velocitySquaredLength = this.velocity.lengthSquared();
  9037. var a = velocitySquaredLength;
  9038. this.basePoint.subtractToRef(p1, this._tempVector);
  9039. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9040. var c = this._tempVector.lengthSquared() - 1.0;
  9041. var lowestRoot = getLowestRoot(a, b, c, t);
  9042. if (lowestRoot.found) {
  9043. t = lowestRoot.root;
  9044. found = true;
  9045. this._collisionPoint.copyFrom(p1);
  9046. }
  9047. this.basePoint.subtractToRef(p2, this._tempVector);
  9048. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9049. c = this._tempVector.lengthSquared() - 1.0;
  9050. lowestRoot = getLowestRoot(a, b, c, t);
  9051. if (lowestRoot.found) {
  9052. t = lowestRoot.root;
  9053. found = true;
  9054. this._collisionPoint.copyFrom(p2);
  9055. }
  9056. this.basePoint.subtractToRef(p3, this._tempVector);
  9057. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9058. c = this._tempVector.lengthSquared() - 1.0;
  9059. lowestRoot = getLowestRoot(a, b, c, t);
  9060. if (lowestRoot.found) {
  9061. t = lowestRoot.root;
  9062. found = true;
  9063. this._collisionPoint.copyFrom(p3);
  9064. }
  9065. p2.subtractToRef(p1, this._edge);
  9066. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9067. var edgeSquaredLength = this._edge.lengthSquared();
  9068. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9069. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9070. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9071. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9072. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9073. lowestRoot = getLowestRoot(a, b, c, t);
  9074. if (lowestRoot.found) {
  9075. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9076. if (f >= 0.0 && f <= 1.0) {
  9077. t = lowestRoot.root;
  9078. found = true;
  9079. this._edge.scaleInPlace(f);
  9080. p1.addToRef(this._edge, this._collisionPoint);
  9081. }
  9082. }
  9083. p3.subtractToRef(p2, this._edge);
  9084. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9085. edgeSquaredLength = this._edge.lengthSquared();
  9086. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9087. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9088. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9089. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9090. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9091. lowestRoot = getLowestRoot(a, b, c, t);
  9092. if (lowestRoot.found) {
  9093. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9094. if (f >= 0.0 && f <= 1.0) {
  9095. t = lowestRoot.root;
  9096. found = true;
  9097. this._edge.scaleInPlace(f);
  9098. p2.addToRef(this._edge, this._collisionPoint);
  9099. }
  9100. }
  9101. p1.subtractToRef(p3, this._edge);
  9102. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9103. edgeSquaredLength = this._edge.lengthSquared();
  9104. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9105. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9106. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9107. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9108. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9109. lowestRoot = getLowestRoot(a, b, c, t);
  9110. if (lowestRoot.found) {
  9111. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9112. if (f >= 0.0 && f <= 1.0) {
  9113. t = lowestRoot.root;
  9114. found = true;
  9115. this._edge.scaleInPlace(f);
  9116. p3.addToRef(this._edge, this._collisionPoint);
  9117. }
  9118. }
  9119. }
  9120. if (found) {
  9121. var distToCollision = t * this.velocity.length();
  9122. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9123. if (!this.intersectionPoint) {
  9124. this.intersectionPoint = this._collisionPoint.clone();
  9125. }
  9126. else {
  9127. this.intersectionPoint.copyFrom(this._collisionPoint);
  9128. }
  9129. this.nearestDistance = distToCollision;
  9130. this.collisionFound = true;
  9131. }
  9132. }
  9133. };
  9134. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9135. for (var i = indexStart; i < indexEnd; i += 3) {
  9136. var p1 = pts[indices[i] - decal];
  9137. var p2 = pts[indices[i + 1] - decal];
  9138. var p3 = pts[indices[i + 2] - decal];
  9139. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9140. }
  9141. };
  9142. Collider.prototype._getResponse = function (pos, vel) {
  9143. pos.addToRef(vel, this._destinationPoint);
  9144. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9145. this.basePoint.addToRef(vel, pos);
  9146. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9147. this._slidePlaneNormal.normalize();
  9148. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9149. pos.addInPlace(this._displacementVector);
  9150. this.intersectionPoint.addInPlace(this._displacementVector);
  9151. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9152. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9153. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9154. };
  9155. return Collider;
  9156. })();
  9157. BABYLON.Collider = Collider;
  9158. })(BABYLON || (BABYLON = {}));
  9159. var BABYLON;
  9160. (function (BABYLON) {
  9161. //WebWorker code will be inserted to this variable.
  9162. BABYLON.CollisionWorker = "";
  9163. (function (WorkerTaskType) {
  9164. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9165. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9166. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9167. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9168. var WorkerTaskType = BABYLON.WorkerTaskType;
  9169. (function (WorkerReplyType) {
  9170. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9171. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9172. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9173. var WorkerReplyType = BABYLON.WorkerReplyType;
  9174. var CollisionCoordinatorWorker = (function () {
  9175. function CollisionCoordinatorWorker() {
  9176. var _this = this;
  9177. this._scaledPosition = BABYLON.Vector3.Zero();
  9178. this._scaledVelocity = BABYLON.Vector3.Zero();
  9179. this.onMeshUpdated = function (mesh) {
  9180. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9181. };
  9182. this.onGeometryUpdated = function (geometry) {
  9183. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9184. };
  9185. this._afterRender = function () {
  9186. if (!_this._init)
  9187. return;
  9188. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9189. return;
  9190. }
  9191. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9192. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9193. if (_this._runningUpdated > 4) {
  9194. return;
  9195. }
  9196. ++_this._runningUpdated;
  9197. var payload = {
  9198. updatedMeshes: _this._addUpdateMeshesList,
  9199. updatedGeometries: _this._addUpdateGeometriesList,
  9200. removedGeometries: _this._toRemoveGeometryArray,
  9201. removedMeshes: _this._toRemoveMeshesArray
  9202. };
  9203. var message = {
  9204. payload: payload,
  9205. taskType: WorkerTaskType.UPDATE
  9206. };
  9207. var serializable = [];
  9208. for (var id in payload.updatedGeometries) {
  9209. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9210. //prepare transferables
  9211. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9212. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9213. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9214. }
  9215. }
  9216. _this._worker.postMessage(message, serializable);
  9217. _this._addUpdateMeshesList = {};
  9218. _this._addUpdateGeometriesList = {};
  9219. _this._toRemoveGeometryArray = [];
  9220. _this._toRemoveMeshesArray = [];
  9221. };
  9222. this._onMessageFromWorker = function (e) {
  9223. var returnData = e.data;
  9224. if (returnData.error != WorkerReplyType.SUCCESS) {
  9225. //TODO what errors can be returned from the worker?
  9226. BABYLON.Tools.Warn("error returned from worker!");
  9227. return;
  9228. }
  9229. switch (returnData.taskType) {
  9230. case WorkerTaskType.INIT:
  9231. _this._init = true;
  9232. //Update the worked with ALL of the scene's current state
  9233. _this._scene.meshes.forEach(function (mesh) {
  9234. _this.onMeshAdded(mesh);
  9235. });
  9236. _this._scene.getGeometries().forEach(function (geometry) {
  9237. _this.onGeometryAdded(geometry);
  9238. });
  9239. break;
  9240. case WorkerTaskType.UPDATE:
  9241. _this._runningUpdated--;
  9242. break;
  9243. case WorkerTaskType.COLLIDE:
  9244. _this._runningCollisionTask = false;
  9245. var returnPayload = returnData.payload;
  9246. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9247. return;
  9248. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9249. //cleanup
  9250. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9251. break;
  9252. }
  9253. };
  9254. this._collisionsCallbackArray = [];
  9255. this._init = false;
  9256. this._runningUpdated = 0;
  9257. this._runningCollisionTask = false;
  9258. this._addUpdateMeshesList = {};
  9259. this._addUpdateGeometriesList = {};
  9260. this._toRemoveGeometryArray = [];
  9261. this._toRemoveMeshesArray = [];
  9262. }
  9263. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9264. if (!this._init)
  9265. return;
  9266. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9267. return;
  9268. position.divideToRef(collider.radius, this._scaledPosition);
  9269. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9270. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9271. var payload = {
  9272. collider: {
  9273. position: this._scaledPosition.asArray(),
  9274. velocity: this._scaledVelocity.asArray(),
  9275. radius: collider.radius.asArray()
  9276. },
  9277. collisionId: collisionIndex,
  9278. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9279. maximumRetry: maximumRetry
  9280. };
  9281. var message = {
  9282. payload: payload,
  9283. taskType: WorkerTaskType.COLLIDE
  9284. };
  9285. this._worker.postMessage(message);
  9286. };
  9287. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9288. this._scene = scene;
  9289. this._scene.registerAfterRender(this._afterRender);
  9290. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9291. this._worker = new Worker(workerUrl);
  9292. this._worker.onmessage = this._onMessageFromWorker;
  9293. var message = {
  9294. payload: {},
  9295. taskType: WorkerTaskType.INIT
  9296. };
  9297. this._worker.postMessage(message);
  9298. };
  9299. CollisionCoordinatorWorker.prototype.destroy = function () {
  9300. this._scene.unregisterAfterRender(this._afterRender);
  9301. this._worker.terminate();
  9302. };
  9303. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9304. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9305. this.onMeshUpdated(mesh);
  9306. };
  9307. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9308. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9309. };
  9310. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9311. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9312. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9313. this.onGeometryUpdated(geometry);
  9314. };
  9315. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9316. this._toRemoveGeometryArray.push(geometry.id);
  9317. };
  9318. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9319. var submeshes = [];
  9320. if (mesh.subMeshes) {
  9321. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9322. return {
  9323. position: idx,
  9324. verticesStart: sm.verticesStart,
  9325. verticesCount: sm.verticesCount,
  9326. indexStart: sm.indexStart,
  9327. indexCount: sm.indexCount,
  9328. hasMaterial: !!sm.getMaterial(),
  9329. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9330. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9331. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9332. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9333. };
  9334. });
  9335. }
  9336. var geometryId = null;
  9337. if (mesh instanceof BABYLON.Mesh) {
  9338. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9339. }
  9340. else if (mesh instanceof BABYLON.InstancedMesh) {
  9341. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9342. }
  9343. return {
  9344. uniqueId: mesh.uniqueId,
  9345. id: mesh.id,
  9346. name: mesh.name,
  9347. geometryId: geometryId,
  9348. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9349. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9350. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9351. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9352. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9353. subMeshes: submeshes,
  9354. checkCollisions: mesh.checkCollisions
  9355. };
  9356. };
  9357. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9358. return {
  9359. id: geometry.id,
  9360. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9361. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9362. indices: new Int32Array(geometry.getIndices() || []),
  9363. };
  9364. };
  9365. return CollisionCoordinatorWorker;
  9366. })();
  9367. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9368. var CollisionCoordinatorLegacy = (function () {
  9369. function CollisionCoordinatorLegacy() {
  9370. this._scaledPosition = BABYLON.Vector3.Zero();
  9371. this._scaledVelocity = BABYLON.Vector3.Zero();
  9372. this._finalPosition = BABYLON.Vector3.Zero();
  9373. }
  9374. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9375. position.divideToRef(collider.radius, this._scaledPosition);
  9376. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9377. collider.collidedMesh = null;
  9378. collider.retry = 0;
  9379. collider.initialVelocity = this._scaledVelocity;
  9380. collider.initialPosition = this._scaledPosition;
  9381. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9382. this._finalPosition.multiplyInPlace(collider.radius);
  9383. //run the callback
  9384. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9385. };
  9386. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9387. this._scene = scene;
  9388. };
  9389. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9390. //Legacy need no destruction method.
  9391. };
  9392. //No update in legacy mode
  9393. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9394. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9395. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9396. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9397. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9398. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9399. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9400. if (excludedMesh === void 0) { excludedMesh = null; }
  9401. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9402. if (collider.retry >= maximumRetry) {
  9403. finalPosition.copyFrom(position);
  9404. return;
  9405. }
  9406. collider._initialize(position, velocity, closeDistance);
  9407. // Check all meshes
  9408. for (var index = 0; index < this._scene.meshes.length; index++) {
  9409. var mesh = this._scene.meshes[index];
  9410. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9411. mesh._checkCollision(collider);
  9412. }
  9413. }
  9414. if (!collider.collisionFound) {
  9415. position.addToRef(velocity, finalPosition);
  9416. return;
  9417. }
  9418. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9419. collider._getResponse(position, velocity);
  9420. }
  9421. if (velocity.length() <= closeDistance) {
  9422. finalPosition.copyFrom(position);
  9423. return;
  9424. }
  9425. collider.retry++;
  9426. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9427. };
  9428. return CollisionCoordinatorLegacy;
  9429. })();
  9430. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9431. })(BABYLON || (BABYLON = {}));
  9432. var BABYLON;
  9433. (function (BABYLON) {
  9434. var VRCameraMetrics = (function () {
  9435. function VRCameraMetrics() {
  9436. this.compensateDistortion = true;
  9437. }
  9438. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9439. get: function () {
  9440. return this.hResolution / (2 * this.vResolution);
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9446. get: function () {
  9447. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9453. get: function () {
  9454. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9455. var h = (4 * meters) / this.hScreenSize;
  9456. return BABYLON.Matrix.Translation(h, 0, 0);
  9457. },
  9458. enumerable: true,
  9459. configurable: true
  9460. });
  9461. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9462. get: function () {
  9463. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9464. var h = (4 * meters) / this.hScreenSize;
  9465. return BABYLON.Matrix.Translation(-h, 0, 0);
  9466. },
  9467. enumerable: true,
  9468. configurable: true
  9469. });
  9470. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9471. get: function () {
  9472. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9473. },
  9474. enumerable: true,
  9475. configurable: true
  9476. });
  9477. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9478. get: function () {
  9479. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9480. },
  9481. enumerable: true,
  9482. configurable: true
  9483. });
  9484. VRCameraMetrics.GetDefault = function () {
  9485. var result = new VRCameraMetrics();
  9486. result.hResolution = 1280;
  9487. result.vResolution = 800;
  9488. result.hScreenSize = 0.149759993;
  9489. result.vScreenSize = 0.0935999975;
  9490. result.vScreenCenter = 0.0467999987,
  9491. result.eyeToScreenDistance = 0.0410000011;
  9492. result.lensSeparationDistance = 0.0635000020;
  9493. result.interpupillaryDistance = 0.0640000030;
  9494. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9495. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9496. result.postProcessScaleFactor = 1.714605507808412;
  9497. result.lensCenterOffset = 0.151976421;
  9498. return result;
  9499. };
  9500. return VRCameraMetrics;
  9501. })();
  9502. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9503. var Camera = (function (_super) {
  9504. __extends(Camera, _super);
  9505. function Camera(name, position, scene) {
  9506. _super.call(this, name, scene);
  9507. this.position = position;
  9508. // Members
  9509. this.upVector = BABYLON.Vector3.Up();
  9510. this.orthoLeft = null;
  9511. this.orthoRight = null;
  9512. this.orthoBottom = null;
  9513. this.orthoTop = null;
  9514. this.fov = 0.8;
  9515. this.minZ = 1.0;
  9516. this.maxZ = 10000.0;
  9517. this.inertia = 0.9;
  9518. this.mode = Camera.PERSPECTIVE_CAMERA;
  9519. this.isIntermediate = false;
  9520. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9521. this.layerMask = 0x0FFFFFFF;
  9522. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9523. // Camera rig members
  9524. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9525. this._rigCameras = new Array();
  9526. // Cache
  9527. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9528. this._projectionMatrix = new BABYLON.Matrix();
  9529. this._postProcesses = new Array();
  9530. this._postProcessesTakenIndices = [];
  9531. this._activeMeshes = new BABYLON.SmartArray(256);
  9532. this._globalPosition = BABYLON.Vector3.Zero();
  9533. scene.addCamera(this);
  9534. if (!scene.activeCamera) {
  9535. scene.activeCamera = this;
  9536. }
  9537. }
  9538. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9539. get: function () {
  9540. return Camera._PERSPECTIVE_CAMERA;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9546. get: function () {
  9547. return Camera._ORTHOGRAPHIC_CAMERA;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9553. get: function () {
  9554. return Camera._FOVMODE_VERTICAL_FIXED;
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9560. get: function () {
  9561. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9567. get: function () {
  9568. return Camera._RIG_MODE_NONE;
  9569. },
  9570. enumerable: true,
  9571. configurable: true
  9572. });
  9573. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9574. get: function () {
  9575. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9581. get: function () {
  9582. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9588. get: function () {
  9589. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9595. get: function () {
  9596. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9597. },
  9598. enumerable: true,
  9599. configurable: true
  9600. });
  9601. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9602. get: function () {
  9603. return Camera._RIG_MODE_VR;
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Object.defineProperty(Camera.prototype, "globalPosition", {
  9609. get: function () {
  9610. return this._globalPosition;
  9611. },
  9612. enumerable: true,
  9613. configurable: true
  9614. });
  9615. Camera.prototype.getActiveMeshes = function () {
  9616. return this._activeMeshes;
  9617. };
  9618. Camera.prototype.isActiveMesh = function (mesh) {
  9619. return (this._activeMeshes.indexOf(mesh) !== -1);
  9620. };
  9621. //Cache
  9622. Camera.prototype._initCache = function () {
  9623. _super.prototype._initCache.call(this);
  9624. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9625. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9626. this._cache.mode = undefined;
  9627. this._cache.minZ = undefined;
  9628. this._cache.maxZ = undefined;
  9629. this._cache.fov = undefined;
  9630. this._cache.aspectRatio = undefined;
  9631. this._cache.orthoLeft = undefined;
  9632. this._cache.orthoRight = undefined;
  9633. this._cache.orthoBottom = undefined;
  9634. this._cache.orthoTop = undefined;
  9635. this._cache.renderWidth = undefined;
  9636. this._cache.renderHeight = undefined;
  9637. };
  9638. Camera.prototype._updateCache = function (ignoreParentClass) {
  9639. if (!ignoreParentClass) {
  9640. _super.prototype._updateCache.call(this);
  9641. }
  9642. var engine = this.getEngine();
  9643. this._cache.position.copyFrom(this.position);
  9644. this._cache.upVector.copyFrom(this.upVector);
  9645. this._cache.mode = this.mode;
  9646. this._cache.minZ = this.minZ;
  9647. this._cache.maxZ = this.maxZ;
  9648. this._cache.fov = this.fov;
  9649. this._cache.aspectRatio = engine.getAspectRatio(this);
  9650. this._cache.orthoLeft = this.orthoLeft;
  9651. this._cache.orthoRight = this.orthoRight;
  9652. this._cache.orthoBottom = this.orthoBottom;
  9653. this._cache.orthoTop = this.orthoTop;
  9654. this._cache.renderWidth = engine.getRenderWidth();
  9655. this._cache.renderHeight = engine.getRenderHeight();
  9656. };
  9657. Camera.prototype._updateFromScene = function () {
  9658. this.updateCache();
  9659. this._update();
  9660. };
  9661. // Synchronized
  9662. Camera.prototype._isSynchronized = function () {
  9663. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9664. };
  9665. Camera.prototype._isSynchronizedViewMatrix = function () {
  9666. if (!_super.prototype._isSynchronized.call(this))
  9667. return false;
  9668. return this._cache.position.equals(this.position)
  9669. && this._cache.upVector.equals(this.upVector)
  9670. && this.isSynchronizedWithParent();
  9671. };
  9672. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9673. var check = this._cache.mode === this.mode
  9674. && this._cache.minZ === this.minZ
  9675. && this._cache.maxZ === this.maxZ;
  9676. if (!check) {
  9677. return false;
  9678. }
  9679. var engine = this.getEngine();
  9680. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9681. check = this._cache.fov === this.fov
  9682. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9683. }
  9684. else {
  9685. check = this._cache.orthoLeft === this.orthoLeft
  9686. && this._cache.orthoRight === this.orthoRight
  9687. && this._cache.orthoBottom === this.orthoBottom
  9688. && this._cache.orthoTop === this.orthoTop
  9689. && this._cache.renderWidth === engine.getRenderWidth()
  9690. && this._cache.renderHeight === engine.getRenderHeight();
  9691. }
  9692. return check;
  9693. };
  9694. // Controls
  9695. Camera.prototype.attachControl = function (element) {
  9696. };
  9697. Camera.prototype.detachControl = function (element) {
  9698. };
  9699. Camera.prototype._update = function () {
  9700. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9701. this._updateRigCameras();
  9702. }
  9703. this._checkInputs();
  9704. };
  9705. Camera.prototype._checkInputs = function () {
  9706. };
  9707. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9708. if (insertAt === void 0) { insertAt = null; }
  9709. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9710. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9711. return 0;
  9712. }
  9713. if (insertAt == null || insertAt < 0) {
  9714. this._postProcesses.push(postProcess);
  9715. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9716. return this._postProcesses.length - 1;
  9717. }
  9718. var add = 0;
  9719. var i;
  9720. var start;
  9721. if (this._postProcesses[insertAt]) {
  9722. start = this._postProcesses.length - 1;
  9723. for (i = start; i >= insertAt + 1; --i) {
  9724. this._postProcesses[i + 1] = this._postProcesses[i];
  9725. }
  9726. add = 1;
  9727. }
  9728. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9729. if (this._postProcessesTakenIndices[i] < insertAt) {
  9730. continue;
  9731. }
  9732. start = this._postProcessesTakenIndices.length - 1;
  9733. for (var j = start; j >= i; --j) {
  9734. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9735. }
  9736. this._postProcessesTakenIndices[i] = insertAt;
  9737. break;
  9738. }
  9739. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9740. this._postProcessesTakenIndices.push(insertAt);
  9741. }
  9742. var result = insertAt + add;
  9743. this._postProcesses[result] = postProcess;
  9744. return result;
  9745. };
  9746. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9747. if (atIndices === void 0) { atIndices = null; }
  9748. var result = [];
  9749. var i;
  9750. var index;
  9751. if (!atIndices) {
  9752. var length = this._postProcesses.length;
  9753. for (i = 0; i < length; i++) {
  9754. if (this._postProcesses[i] !== postProcess) {
  9755. continue;
  9756. }
  9757. delete this._postProcesses[i];
  9758. index = this._postProcessesTakenIndices.indexOf(i);
  9759. this._postProcessesTakenIndices.splice(index, 1);
  9760. }
  9761. }
  9762. else {
  9763. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9764. for (i = 0; i < atIndices.length; i++) {
  9765. var foundPostProcess = this._postProcesses[atIndices[i]];
  9766. if (foundPostProcess !== postProcess) {
  9767. result.push(i);
  9768. continue;
  9769. }
  9770. delete this._postProcesses[atIndices[i]];
  9771. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9772. this._postProcessesTakenIndices.splice(index, 1);
  9773. }
  9774. }
  9775. return result;
  9776. };
  9777. Camera.prototype.getWorldMatrix = function () {
  9778. if (!this._worldMatrix) {
  9779. this._worldMatrix = BABYLON.Matrix.Identity();
  9780. }
  9781. var viewMatrix = this.getViewMatrix();
  9782. viewMatrix.invertToRef(this._worldMatrix);
  9783. return this._worldMatrix;
  9784. };
  9785. Camera.prototype._getViewMatrix = function () {
  9786. return BABYLON.Matrix.Identity();
  9787. };
  9788. Camera.prototype.getViewMatrix = function (force) {
  9789. this._computedViewMatrix = this._computeViewMatrix(force);
  9790. if (!force && this._isSynchronizedViewMatrix()) {
  9791. return this._computedViewMatrix;
  9792. }
  9793. if (!this.parent || !this.parent.getWorldMatrix) {
  9794. this._globalPosition.copyFrom(this.position);
  9795. }
  9796. else {
  9797. if (!this._worldMatrix) {
  9798. this._worldMatrix = BABYLON.Matrix.Identity();
  9799. }
  9800. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9801. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9802. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9803. this._computedViewMatrix.invert();
  9804. this._markSyncedWithParent();
  9805. }
  9806. this._currentRenderId = this.getScene().getRenderId();
  9807. return this._computedViewMatrix;
  9808. };
  9809. Camera.prototype._computeViewMatrix = function (force) {
  9810. if (!force && this._isSynchronizedViewMatrix()) {
  9811. return this._computedViewMatrix;
  9812. }
  9813. this._computedViewMatrix = this._getViewMatrix();
  9814. this._currentRenderId = this.getScene().getRenderId();
  9815. return this._computedViewMatrix;
  9816. };
  9817. Camera.prototype.getProjectionMatrix = function (force) {
  9818. if (!force && this._isSynchronizedProjectionMatrix()) {
  9819. return this._projectionMatrix;
  9820. }
  9821. var engine = this.getEngine();
  9822. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9823. if (this.minZ <= 0) {
  9824. this.minZ = 0.1;
  9825. }
  9826. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9827. return this._projectionMatrix;
  9828. }
  9829. var halfWidth = engine.getRenderWidth() / 2.0;
  9830. var halfHeight = engine.getRenderHeight() / 2.0;
  9831. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9832. return this._projectionMatrix;
  9833. };
  9834. Camera.prototype.dispose = function () {
  9835. // Remove from scene
  9836. this.getScene().removeCamera(this);
  9837. while (this._rigCameras.length > 0) {
  9838. this._rigCameras.pop().dispose();
  9839. }
  9840. // Postprocesses
  9841. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9842. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9843. }
  9844. };
  9845. // ---- Camera rigs section ----
  9846. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9847. while (this._rigCameras.length > 0) {
  9848. this._rigCameras.pop().dispose();
  9849. }
  9850. this.cameraRigMode = mode;
  9851. this._cameraRigParams = {};
  9852. switch (this.cameraRigMode) {
  9853. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9854. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9855. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9856. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9857. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  9858. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  9859. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  9860. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  9861. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9862. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9863. break;
  9864. }
  9865. var postProcesses = new Array();
  9866. switch (this.cameraRigMode) {
  9867. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9868. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  9869. this._rigCameras[0].isIntermediate = true;
  9870. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  9871. postProcesses[1].onApply = function (effect) {
  9872. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  9873. };
  9874. break;
  9875. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9876. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9877. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9878. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  9879. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  9880. var secondCamIndex = 1 - firstCamIndex;
  9881. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  9882. this._rigCameras[firstCamIndex].isIntermediate = true;
  9883. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  9884. break;
  9885. case Camera.RIG_MODE_VR:
  9886. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9887. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9888. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  9889. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  9890. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9891. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  9892. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  9893. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  9894. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  9895. if (metrics.compensateDistortion) {
  9896. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  9897. }
  9898. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  9899. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  9900. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  9901. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  9902. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  9903. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  9904. if (metrics.compensateDistortion) {
  9905. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  9906. }
  9907. break;
  9908. }
  9909. this._update();
  9910. };
  9911. Camera.prototype._getVRProjectionMatrix = function () {
  9912. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  9913. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  9914. return this._projectionMatrix;
  9915. };
  9916. Camera.prototype.setCameraRigParameter = function (name, value) {
  9917. this._cameraRigParams[name] = value;
  9918. //provisionnally:
  9919. if (name === "interaxialDistance") {
  9920. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  9921. }
  9922. };
  9923. /**
  9924. * May needs to be overridden by children so sub has required properties to be copied
  9925. */
  9926. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  9927. return null;
  9928. };
  9929. /**
  9930. * May needs to be overridden by children
  9931. */
  9932. Camera.prototype._updateRigCameras = function () {
  9933. for (var i = 0; i < this._rigCameras.length; i++) {
  9934. this._rigCameras[i].minZ = this.minZ;
  9935. this._rigCameras[i].maxZ = this.maxZ;
  9936. this._rigCameras[i].fov = this.fov;
  9937. }
  9938. // only update viewport when ANAGLYPH
  9939. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  9940. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  9941. }
  9942. };
  9943. // Statics
  9944. Camera._PERSPECTIVE_CAMERA = 0;
  9945. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9946. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9947. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9948. Camera._RIG_MODE_NONE = 0;
  9949. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  9950. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  9951. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  9952. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  9953. Camera._RIG_MODE_VR = 20;
  9954. return Camera;
  9955. })(BABYLON.Node);
  9956. BABYLON.Camera = Camera;
  9957. })(BABYLON || (BABYLON = {}));
  9958. var BABYLON;
  9959. (function (BABYLON) {
  9960. var TargetCamera = (function (_super) {
  9961. __extends(TargetCamera, _super);
  9962. function TargetCamera(name, position, scene) {
  9963. _super.call(this, name, position, scene);
  9964. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9965. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9966. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9967. this.speed = 2.0;
  9968. this.noRotationConstraint = false;
  9969. this.lockedTarget = null;
  9970. this._currentTarget = BABYLON.Vector3.Zero();
  9971. this._viewMatrix = BABYLON.Matrix.Zero();
  9972. this._camMatrix = BABYLON.Matrix.Zero();
  9973. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9974. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9975. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9976. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9977. this._lookAtTemp = BABYLON.Matrix.Zero();
  9978. this._tempMatrix = BABYLON.Matrix.Zero();
  9979. }
  9980. TargetCamera.prototype.getFrontPosition = function (distance) {
  9981. var direction = this.getTarget().subtract(this.position);
  9982. direction.normalize();
  9983. direction.scaleInPlace(distance);
  9984. return this.globalPosition.add(direction);
  9985. };
  9986. TargetCamera.prototype._getLockedTargetPosition = function () {
  9987. if (!this.lockedTarget) {
  9988. return null;
  9989. }
  9990. return this.lockedTarget.position || this.lockedTarget;
  9991. };
  9992. // Cache
  9993. TargetCamera.prototype._initCache = function () {
  9994. _super.prototype._initCache.call(this);
  9995. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9996. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9997. };
  9998. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  9999. if (!ignoreParentClass) {
  10000. _super.prototype._updateCache.call(this);
  10001. }
  10002. var lockedTargetPosition = this._getLockedTargetPosition();
  10003. if (!lockedTargetPosition) {
  10004. this._cache.lockedTarget = null;
  10005. }
  10006. else {
  10007. if (!this._cache.lockedTarget) {
  10008. this._cache.lockedTarget = lockedTargetPosition.clone();
  10009. }
  10010. else {
  10011. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10012. }
  10013. }
  10014. this._cache.rotation.copyFrom(this.rotation);
  10015. };
  10016. // Synchronized
  10017. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10018. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10019. return false;
  10020. }
  10021. var lockedTargetPosition = this._getLockedTargetPosition();
  10022. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10023. && this._cache.rotation.equals(this.rotation);
  10024. };
  10025. // Methods
  10026. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10027. var engine = this.getEngine();
  10028. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10029. };
  10030. // Target
  10031. TargetCamera.prototype.setTarget = function (target) {
  10032. this.upVector.normalize();
  10033. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10034. this._camMatrix.invert();
  10035. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10036. var vDir = target.subtract(this.position);
  10037. if (vDir.x >= 0.0) {
  10038. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10039. }
  10040. else {
  10041. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10042. }
  10043. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10044. if (isNaN(this.rotation.x)) {
  10045. this.rotation.x = 0;
  10046. }
  10047. if (isNaN(this.rotation.y)) {
  10048. this.rotation.y = 0;
  10049. }
  10050. if (isNaN(this.rotation.z)) {
  10051. this.rotation.z = 0;
  10052. }
  10053. };
  10054. TargetCamera.prototype.getTarget = function () {
  10055. return this._currentTarget;
  10056. };
  10057. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10058. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10059. };
  10060. TargetCamera.prototype._updatePosition = function () {
  10061. this.position.addInPlace(this.cameraDirection);
  10062. };
  10063. TargetCamera.prototype._checkInputs = function () {
  10064. var needToMove = this._decideIfNeedsToMove();
  10065. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10066. // Move
  10067. if (needToMove) {
  10068. this._updatePosition();
  10069. }
  10070. // Rotate
  10071. if (needToRotate) {
  10072. this.rotation.x += this.cameraRotation.x;
  10073. this.rotation.y += this.cameraRotation.y;
  10074. if (!this.noRotationConstraint) {
  10075. var limit = (Math.PI / 2) * 0.95;
  10076. if (this.rotation.x > limit)
  10077. this.rotation.x = limit;
  10078. if (this.rotation.x < -limit)
  10079. this.rotation.x = -limit;
  10080. }
  10081. }
  10082. // Inertia
  10083. if (needToMove) {
  10084. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10085. this.cameraDirection.x = 0;
  10086. }
  10087. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10088. this.cameraDirection.y = 0;
  10089. }
  10090. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10091. this.cameraDirection.z = 0;
  10092. }
  10093. this.cameraDirection.scaleInPlace(this.inertia);
  10094. }
  10095. if (needToRotate) {
  10096. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10097. this.cameraRotation.x = 0;
  10098. }
  10099. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10100. this.cameraRotation.y = 0;
  10101. }
  10102. this.cameraRotation.scaleInPlace(this.inertia);
  10103. }
  10104. _super.prototype._checkInputs.call(this);
  10105. };
  10106. TargetCamera.prototype._getViewMatrix = function () {
  10107. if (!this.lockedTarget) {
  10108. // Compute
  10109. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10110. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10111. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10112. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10113. this._lookAtTemp.invert();
  10114. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10115. }
  10116. else {
  10117. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10118. }
  10119. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10120. // Computing target and final matrix
  10121. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10122. }
  10123. else {
  10124. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10125. }
  10126. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10127. return this._viewMatrix;
  10128. };
  10129. TargetCamera.prototype._getVRViewMatrix = function () {
  10130. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10131. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10132. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10133. // Computing target and final matrix
  10134. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10135. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10136. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10137. return this._viewMatrix;
  10138. };
  10139. /**
  10140. * @override
  10141. * Override Camera.createRigCamera
  10142. */
  10143. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10144. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10145. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10146. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10147. rigCamera._cameraRigParams = {};
  10148. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10149. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10150. }
  10151. return rigCamera;
  10152. }
  10153. return null;
  10154. };
  10155. /**
  10156. * @override
  10157. * Override Camera._updateRigCameras
  10158. */
  10159. TargetCamera.prototype._updateRigCameras = function () {
  10160. switch (this.cameraRigMode) {
  10161. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10162. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10165. case BABYLON.Camera.RIG_MODE_VR:
  10166. var camLeft = this._rigCameras[0];
  10167. var camRight = this._rigCameras[1];
  10168. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10169. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10170. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10171. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10172. camLeft.position.copyFrom(this.position);
  10173. camRight.position.copyFrom(this.position);
  10174. }
  10175. else {
  10176. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10177. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10178. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10179. camLeft.setTarget(this.getTarget());
  10180. camRight.setTarget(this.getTarget());
  10181. }
  10182. break;
  10183. }
  10184. _super.prototype._updateRigCameras.call(this);
  10185. };
  10186. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10187. if (!this._rigCamTransformMatrix) {
  10188. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10189. }
  10190. var target = this.getTarget();
  10191. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10192. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10193. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10194. };
  10195. return TargetCamera;
  10196. })(BABYLON.Camera);
  10197. BABYLON.TargetCamera = TargetCamera;
  10198. })(BABYLON || (BABYLON = {}));
  10199. var BABYLON;
  10200. (function (BABYLON) {
  10201. var FreeCamera = (function (_super) {
  10202. __extends(FreeCamera, _super);
  10203. function FreeCamera(name, position, scene) {
  10204. var _this = this;
  10205. _super.call(this, name, position, scene);
  10206. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10207. this.keysUp = [38];
  10208. this.keysDown = [40];
  10209. this.keysLeft = [37];
  10210. this.keysRight = [39];
  10211. this.checkCollisions = false;
  10212. this.applyGravity = false;
  10213. this.angularSensibility = 2000.0;
  10214. this._keys = [];
  10215. this._collider = new BABYLON.Collider();
  10216. this._needMoveForGravity = false;
  10217. this._oldPosition = BABYLON.Vector3.Zero();
  10218. this._diffPosition = BABYLON.Vector3.Zero();
  10219. this._newPosition = BABYLON.Vector3.Zero();
  10220. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10221. if (collidedMesh === void 0) { collidedMesh = null; }
  10222. //TODO move this to the collision coordinator!
  10223. if (_this.getScene().workerCollisions)
  10224. newPosition.multiplyInPlace(_this._collider.radius);
  10225. var updatePosition = function (newPos) {
  10226. _this._newPosition.copyFrom(newPos);
  10227. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10228. var oldPosition = _this.position.clone();
  10229. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10230. _this.position.addInPlace(_this._diffPosition);
  10231. if (_this.onCollide && collidedMesh) {
  10232. _this.onCollide(collidedMesh);
  10233. }
  10234. }
  10235. };
  10236. updatePosition(newPosition);
  10237. };
  10238. }
  10239. // Controls
  10240. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10241. var _this = this;
  10242. var previousPosition;
  10243. var engine = this.getEngine();
  10244. if (this._attachedElement) {
  10245. return;
  10246. }
  10247. this._attachedElement = element;
  10248. if (this._onMouseDown === undefined) {
  10249. this._onMouseDown = function (evt) {
  10250. previousPosition = {
  10251. x: evt.clientX,
  10252. y: evt.clientY
  10253. };
  10254. if (!noPreventDefault) {
  10255. evt.preventDefault();
  10256. }
  10257. };
  10258. this._onMouseUp = function (evt) {
  10259. previousPosition = null;
  10260. if (!noPreventDefault) {
  10261. evt.preventDefault();
  10262. }
  10263. };
  10264. this._onMouseOut = function (evt) {
  10265. previousPosition = null;
  10266. _this._keys = [];
  10267. if (!noPreventDefault) {
  10268. evt.preventDefault();
  10269. }
  10270. };
  10271. this._onMouseMove = function (evt) {
  10272. if (!previousPosition && !engine.isPointerLock) {
  10273. return;
  10274. }
  10275. var offsetX;
  10276. var offsetY;
  10277. if (!engine.isPointerLock) {
  10278. offsetX = evt.clientX - previousPosition.x;
  10279. offsetY = evt.clientY - previousPosition.y;
  10280. }
  10281. else {
  10282. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10283. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10284. }
  10285. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10286. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10287. previousPosition = {
  10288. x: evt.clientX,
  10289. y: evt.clientY
  10290. };
  10291. if (!noPreventDefault) {
  10292. evt.preventDefault();
  10293. }
  10294. };
  10295. this._onKeyDown = function (evt) {
  10296. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10297. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10298. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10299. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10300. var index = _this._keys.indexOf(evt.keyCode);
  10301. if (index === -1) {
  10302. _this._keys.push(evt.keyCode);
  10303. }
  10304. if (!noPreventDefault) {
  10305. evt.preventDefault();
  10306. }
  10307. }
  10308. };
  10309. this._onKeyUp = function (evt) {
  10310. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10311. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10312. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10313. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10314. var index = _this._keys.indexOf(evt.keyCode);
  10315. if (index >= 0) {
  10316. _this._keys.splice(index, 1);
  10317. }
  10318. if (!noPreventDefault) {
  10319. evt.preventDefault();
  10320. }
  10321. }
  10322. };
  10323. this._onLostFocus = function () {
  10324. _this._keys = [];
  10325. };
  10326. this._reset = function () {
  10327. _this._keys = [];
  10328. previousPosition = null;
  10329. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10330. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10331. };
  10332. }
  10333. element.addEventListener("mousedown", this._onMouseDown, false);
  10334. element.addEventListener("mouseup", this._onMouseUp, false);
  10335. element.addEventListener("mouseout", this._onMouseOut, false);
  10336. element.addEventListener("mousemove", this._onMouseMove, false);
  10337. BABYLON.Tools.RegisterTopRootEvents([
  10338. { name: "keydown", handler: this._onKeyDown },
  10339. { name: "keyup", handler: this._onKeyUp },
  10340. { name: "blur", handler: this._onLostFocus }
  10341. ]);
  10342. };
  10343. FreeCamera.prototype.detachControl = function (element) {
  10344. if (this._attachedElement != element) {
  10345. return;
  10346. }
  10347. element.removeEventListener("mousedown", this._onMouseDown);
  10348. element.removeEventListener("mouseup", this._onMouseUp);
  10349. element.removeEventListener("mouseout", this._onMouseOut);
  10350. element.removeEventListener("mousemove", this._onMouseMove);
  10351. BABYLON.Tools.UnregisterTopRootEvents([
  10352. { name: "keydown", handler: this._onKeyDown },
  10353. { name: "keyup", handler: this._onKeyUp },
  10354. { name: "blur", handler: this._onLostFocus }
  10355. ]);
  10356. this._attachedElement = null;
  10357. if (this._reset) {
  10358. this._reset();
  10359. }
  10360. };
  10361. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10362. var globalPosition;
  10363. if (this.parent) {
  10364. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10365. }
  10366. else {
  10367. globalPosition = this.position;
  10368. }
  10369. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10370. this._collider.radius = this.ellipsoid;
  10371. //no need for clone, as long as gravity is not on.
  10372. var actualVelocity = velocity;
  10373. //add gravity to the velocity to prevent the dual-collision checking
  10374. if (this.applyGravity) {
  10375. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10376. actualVelocity = velocity.add(this.getScene().gravity);
  10377. }
  10378. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10379. };
  10380. FreeCamera.prototype._checkInputs = function () {
  10381. if (!this._localDirection) {
  10382. this._localDirection = BABYLON.Vector3.Zero();
  10383. this._transformedDirection = BABYLON.Vector3.Zero();
  10384. }
  10385. // Keyboard
  10386. for (var index = 0; index < this._keys.length; index++) {
  10387. var keyCode = this._keys[index];
  10388. var speed = this._computeLocalCameraSpeed();
  10389. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10390. this._localDirection.copyFromFloats(-speed, 0, 0);
  10391. }
  10392. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10393. this._localDirection.copyFromFloats(0, 0, speed);
  10394. }
  10395. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10396. this._localDirection.copyFromFloats(speed, 0, 0);
  10397. }
  10398. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10399. this._localDirection.copyFromFloats(0, 0, -speed);
  10400. }
  10401. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10402. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10403. this.cameraDirection.addInPlace(this._transformedDirection);
  10404. }
  10405. _super.prototype._checkInputs.call(this);
  10406. };
  10407. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10408. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10409. };
  10410. FreeCamera.prototype._updatePosition = function () {
  10411. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10412. this._collideWithWorld(this.cameraDirection);
  10413. }
  10414. else {
  10415. this.position.addInPlace(this.cameraDirection);
  10416. }
  10417. };
  10418. return FreeCamera;
  10419. })(BABYLON.TargetCamera);
  10420. BABYLON.FreeCamera = FreeCamera;
  10421. })(BABYLON || (BABYLON = {}));
  10422. var BABYLON;
  10423. (function (BABYLON) {
  10424. var FollowCamera = (function (_super) {
  10425. __extends(FollowCamera, _super);
  10426. function FollowCamera(name, position, scene) {
  10427. _super.call(this, name, position, scene);
  10428. this.radius = 12;
  10429. this.rotationOffset = 0;
  10430. this.heightOffset = 4;
  10431. this.cameraAcceleration = 0.05;
  10432. this.maxCameraSpeed = 20;
  10433. }
  10434. FollowCamera.prototype.getRadians = function (degrees) {
  10435. return degrees * Math.PI / 180;
  10436. };
  10437. FollowCamera.prototype.follow = function (cameraTarget) {
  10438. if (!cameraTarget)
  10439. return;
  10440. var yRotation;
  10441. if (cameraTarget.rotationQuaternion) {
  10442. var rotMatrix = new BABYLON.Matrix();
  10443. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10444. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10445. }
  10446. else {
  10447. yRotation = cameraTarget.rotation.y;
  10448. }
  10449. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10450. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10451. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10452. var dx = targetX - this.position.x;
  10453. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10454. var dz = (targetZ) - this.position.z;
  10455. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10456. var vy = dy * this.cameraAcceleration;
  10457. var vz = dz * this.cameraAcceleration * 2;
  10458. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10459. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10460. }
  10461. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10462. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10463. }
  10464. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10465. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10466. }
  10467. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10468. this.setTarget(cameraTarget.position);
  10469. };
  10470. FollowCamera.prototype._checkInputs = function () {
  10471. _super.prototype._checkInputs.call(this);
  10472. this.follow(this.target);
  10473. };
  10474. return FollowCamera;
  10475. })(BABYLON.TargetCamera);
  10476. BABYLON.FollowCamera = FollowCamera;
  10477. var ArcFollowCamera = (function (_super) {
  10478. __extends(ArcFollowCamera, _super);
  10479. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10480. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10481. this.alpha = alpha;
  10482. this.beta = beta;
  10483. this.radius = radius;
  10484. this.target = target;
  10485. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10486. this.follow();
  10487. }
  10488. ArcFollowCamera.prototype.follow = function () {
  10489. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10490. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10491. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10492. this.position = this.target.position.add(this._cartesianCoordinates);
  10493. this.setTarget(this.target.position);
  10494. };
  10495. ArcFollowCamera.prototype._checkInputs = function () {
  10496. _super.prototype._checkInputs.call(this);
  10497. this.follow();
  10498. };
  10499. return ArcFollowCamera;
  10500. })(BABYLON.TargetCamera);
  10501. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10502. })(BABYLON || (BABYLON = {}));
  10503. var BABYLON;
  10504. (function (BABYLON) {
  10505. // We're mainly based on the logic defined into the FreeCamera code
  10506. var TouchCamera = (function (_super) {
  10507. __extends(TouchCamera, _super);
  10508. function TouchCamera(name, position, scene) {
  10509. _super.call(this, name, position, scene);
  10510. this._offsetX = null;
  10511. this._offsetY = null;
  10512. this._pointerCount = 0;
  10513. this._pointerPressed = [];
  10514. this.angularSensibility = 200000.0;
  10515. this.moveSensibility = 500.0;
  10516. }
  10517. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10518. var _this = this;
  10519. var previousPosition;
  10520. if (this._attachedCanvas) {
  10521. return;
  10522. }
  10523. this._attachedCanvas = canvas;
  10524. if (this._onPointerDown === undefined) {
  10525. this._onPointerDown = function (evt) {
  10526. if (!noPreventDefault) {
  10527. evt.preventDefault();
  10528. }
  10529. _this._pointerPressed.push(evt.pointerId);
  10530. if (_this._pointerPressed.length !== 1) {
  10531. return;
  10532. }
  10533. previousPosition = {
  10534. x: evt.clientX,
  10535. y: evt.clientY
  10536. };
  10537. };
  10538. this._onPointerUp = function (evt) {
  10539. if (!noPreventDefault) {
  10540. evt.preventDefault();
  10541. }
  10542. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10543. if (index === -1) {
  10544. return;
  10545. }
  10546. _this._pointerPressed.splice(index, 1);
  10547. if (index != 0) {
  10548. return;
  10549. }
  10550. previousPosition = null;
  10551. _this._offsetX = null;
  10552. _this._offsetY = null;
  10553. };
  10554. this._onPointerMove = function (evt) {
  10555. if (!noPreventDefault) {
  10556. evt.preventDefault();
  10557. }
  10558. if (!previousPosition) {
  10559. return;
  10560. }
  10561. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10562. if (index != 0) {
  10563. return;
  10564. }
  10565. _this._offsetX = evt.clientX - previousPosition.x;
  10566. _this._offsetY = -(evt.clientY - previousPosition.y);
  10567. };
  10568. this._onLostFocus = function () {
  10569. _this._offsetX = null;
  10570. _this._offsetY = null;
  10571. };
  10572. }
  10573. canvas.addEventListener("pointerdown", this._onPointerDown);
  10574. canvas.addEventListener("pointerup", this._onPointerUp);
  10575. canvas.addEventListener("pointerout", this._onPointerUp);
  10576. canvas.addEventListener("pointermove", this._onPointerMove);
  10577. BABYLON.Tools.RegisterTopRootEvents([
  10578. { name: "blur", handler: this._onLostFocus }
  10579. ]);
  10580. };
  10581. TouchCamera.prototype.detachControl = function (canvas) {
  10582. if (this._attachedCanvas != canvas) {
  10583. return;
  10584. }
  10585. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10586. canvas.removeEventListener("pointerup", this._onPointerUp);
  10587. canvas.removeEventListener("pointerout", this._onPointerUp);
  10588. canvas.removeEventListener("pointermove", this._onPointerMove);
  10589. BABYLON.Tools.UnregisterTopRootEvents([
  10590. { name: "blur", handler: this._onLostFocus }
  10591. ]);
  10592. this._attachedCanvas = null;
  10593. };
  10594. TouchCamera.prototype._checkInputs = function () {
  10595. if (this._offsetX) {
  10596. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10597. if (this._pointerPressed.length > 1) {
  10598. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10599. }
  10600. else {
  10601. var speed = this._computeLocalCameraSpeed();
  10602. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10603. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10604. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10605. }
  10606. }
  10607. _super.prototype._checkInputs.call(this);
  10608. };
  10609. return TouchCamera;
  10610. })(BABYLON.FreeCamera);
  10611. BABYLON.TouchCamera = TouchCamera;
  10612. })(BABYLON || (BABYLON = {}));
  10613. var BABYLON;
  10614. (function (BABYLON) {
  10615. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10616. var ArcRotateCamera = (function (_super) {
  10617. __extends(ArcRotateCamera, _super);
  10618. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10619. var _this = this;
  10620. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10621. this.alpha = alpha;
  10622. this.beta = beta;
  10623. this.radius = radius;
  10624. this.target = target;
  10625. this.inertialAlphaOffset = 0;
  10626. this.inertialBetaOffset = 0;
  10627. this.inertialRadiusOffset = 0;
  10628. this.lowerAlphaLimit = null;
  10629. this.upperAlphaLimit = null;
  10630. this.lowerBetaLimit = 0.01;
  10631. this.upperBetaLimit = Math.PI;
  10632. this.lowerRadiusLimit = null;
  10633. this.upperRadiusLimit = null;
  10634. this.angularSensibilityX = 1000.0;
  10635. this.angularSensibilityY = 1000.0;
  10636. this.wheelPrecision = 3.0;
  10637. this.pinchPrecision = 2.0;
  10638. this.panningSensibility = 50.0;
  10639. this.inertialPanningX = 0;
  10640. this.inertialPanningY = 0;
  10641. this.keysUp = [38];
  10642. this.keysDown = [40];
  10643. this.keysLeft = [37];
  10644. this.keysRight = [39];
  10645. this.zoomOnFactor = 1;
  10646. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10647. this.pinchInwards = true;
  10648. this.allowUpsideDown = true;
  10649. this._keys = [];
  10650. this._viewMatrix = new BABYLON.Matrix();
  10651. this._isRightClick = false;
  10652. this._isCtrlPushed = false;
  10653. this.checkCollisions = false;
  10654. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10655. this._collider = new BABYLON.Collider();
  10656. this._previousPosition = BABYLON.Vector3.Zero();
  10657. this._collisionVelocity = BABYLON.Vector3.Zero();
  10658. this._newPosition = BABYLON.Vector3.Zero();
  10659. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10660. if (collidedMesh === void 0) { collidedMesh = null; }
  10661. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10662. newPosition.multiplyInPlace(_this._collider.radius);
  10663. }
  10664. if (!collidedMesh) {
  10665. _this._previousPosition.copyFrom(_this.position);
  10666. }
  10667. else {
  10668. _this.setPosition(_this.position);
  10669. if (_this.onCollide) {
  10670. _this.onCollide(collidedMesh);
  10671. }
  10672. }
  10673. // Recompute because of constraints
  10674. var cosa = Math.cos(_this.alpha);
  10675. var sina = Math.sin(_this.alpha);
  10676. var cosb = Math.cos(_this.beta);
  10677. var sinb = Math.sin(_this.beta);
  10678. var target = _this._getTargetPosition();
  10679. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10680. _this.position.copyFrom(_this._newPosition);
  10681. var up = _this.upVector;
  10682. if (_this.allowUpsideDown && _this.beta < 0) {
  10683. var up = up.clone();
  10684. up = up.negate();
  10685. }
  10686. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10687. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10688. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10689. _this._collisionTriggered = false;
  10690. };
  10691. if (!this.target) {
  10692. this.target = BABYLON.Vector3.Zero();
  10693. }
  10694. this.getViewMatrix();
  10695. }
  10696. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10697. //deprecated angularSensibility support
  10698. get: function () {
  10699. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10700. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10701. },
  10702. //deprecated angularSensibility support
  10703. set: function (value) {
  10704. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10705. this.angularSensibilityX = value;
  10706. this.angularSensibilityY = value;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. ArcRotateCamera.prototype._getTargetPosition = function () {
  10712. return this.target.position || this.target;
  10713. };
  10714. // Cache
  10715. ArcRotateCamera.prototype._initCache = function () {
  10716. _super.prototype._initCache.call(this);
  10717. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10718. this._cache.alpha = undefined;
  10719. this._cache.beta = undefined;
  10720. this._cache.radius = undefined;
  10721. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10722. };
  10723. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10724. if (!ignoreParentClass) {
  10725. _super.prototype._updateCache.call(this);
  10726. }
  10727. this._cache.target.copyFrom(this._getTargetPosition());
  10728. this._cache.alpha = this.alpha;
  10729. this._cache.beta = this.beta;
  10730. this._cache.radius = this.radius;
  10731. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10732. };
  10733. // Synchronized
  10734. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10735. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10736. return false;
  10737. return this._cache.target.equals(this._getTargetPosition())
  10738. && this._cache.alpha === this.alpha
  10739. && this._cache.beta === this.beta
  10740. && this._cache.radius === this.radius
  10741. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10742. };
  10743. // Methods
  10744. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10745. var _this = this;
  10746. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10747. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10748. var previousPinchDistance = 0;
  10749. var pointers = new BABYLON.SmartCollection();
  10750. if (this._attachedElement) {
  10751. return;
  10752. }
  10753. this._attachedElement = element;
  10754. var engine = this.getEngine();
  10755. if (this._onPointerDown === undefined) {
  10756. this._onPointerDown = function (evt) {
  10757. // Manage panning with right click
  10758. _this._isRightClick = evt.button === 2 ? true : false;
  10759. // manage pointers
  10760. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10761. cacheSoloPointer = pointers.item(evt.pointerId);
  10762. if (!noPreventDefault) {
  10763. evt.preventDefault();
  10764. }
  10765. };
  10766. this._onPointerUp = function (evt) {
  10767. cacheSoloPointer = null;
  10768. previousPinchDistance = 0;
  10769. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10770. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10771. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10772. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10773. pointers.empty();
  10774. if (!noPreventDefault) {
  10775. evt.preventDefault();
  10776. }
  10777. };
  10778. this._onContextMenu = function (evt) {
  10779. evt.preventDefault();
  10780. };
  10781. this._onPointerMove = function (evt) {
  10782. if (!noPreventDefault) {
  10783. evt.preventDefault();
  10784. }
  10785. switch (pointers.count) {
  10786. case 1:
  10787. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  10788. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10789. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10790. }
  10791. else {
  10792. var offsetX = evt.clientX - cacheSoloPointer.x;
  10793. var offsetY = evt.clientY - cacheSoloPointer.y;
  10794. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10795. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10796. }
  10797. cacheSoloPointer.x = evt.clientX;
  10798. cacheSoloPointer.y = evt.clientY;
  10799. break;
  10800. case 2:
  10801. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10802. pointers.item(evt.pointerId).x = evt.clientX;
  10803. pointers.item(evt.pointerId).y = evt.clientY;
  10804. var direction = _this.pinchInwards ? 1 : -1;
  10805. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10806. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10807. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10808. if (previousPinchDistance === 0) {
  10809. previousPinchDistance = pinchSquaredDistance;
  10810. return;
  10811. }
  10812. if (pinchSquaredDistance !== previousPinchDistance) {
  10813. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10814. previousPinchDistance = pinchSquaredDistance;
  10815. }
  10816. break;
  10817. default:
  10818. if (pointers.item(evt.pointerId)) {
  10819. pointers.item(evt.pointerId).x = evt.clientX;
  10820. pointers.item(evt.pointerId).y = evt.clientY;
  10821. }
  10822. }
  10823. };
  10824. this._onMouseMove = function (evt) {
  10825. if (!engine.isPointerLock) {
  10826. return;
  10827. }
  10828. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10829. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10830. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10831. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10832. if (!noPreventDefault) {
  10833. evt.preventDefault();
  10834. }
  10835. };
  10836. this._wheel = function (event) {
  10837. var delta = 0;
  10838. if (event.wheelDelta) {
  10839. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10840. }
  10841. else if (event.detail) {
  10842. delta = -event.detail / _this.wheelPrecision;
  10843. }
  10844. if (delta)
  10845. _this.inertialRadiusOffset += delta;
  10846. if (event.preventDefault) {
  10847. if (!noPreventDefault) {
  10848. event.preventDefault();
  10849. }
  10850. }
  10851. };
  10852. this._onKeyDown = function (evt) {
  10853. _this._isCtrlPushed = evt.ctrlKey;
  10854. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10855. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10856. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10857. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10858. var index = _this._keys.indexOf(evt.keyCode);
  10859. if (index === -1) {
  10860. _this._keys.push(evt.keyCode);
  10861. }
  10862. if (evt.preventDefault) {
  10863. if (!noPreventDefault) {
  10864. evt.preventDefault();
  10865. }
  10866. }
  10867. }
  10868. };
  10869. this._onKeyUp = function (evt) {
  10870. _this._isCtrlPushed = evt.ctrlKey;
  10871. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10872. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10873. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10874. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10875. var index = _this._keys.indexOf(evt.keyCode);
  10876. if (index >= 0) {
  10877. _this._keys.splice(index, 1);
  10878. }
  10879. if (evt.preventDefault) {
  10880. if (!noPreventDefault) {
  10881. evt.preventDefault();
  10882. }
  10883. }
  10884. }
  10885. };
  10886. this._onLostFocus = function () {
  10887. _this._keys = [];
  10888. pointers.empty();
  10889. previousPinchDistance = 0;
  10890. cacheSoloPointer = null;
  10891. };
  10892. this._onGestureStart = function (e) {
  10893. if (window.MSGesture === undefined) {
  10894. return;
  10895. }
  10896. if (!_this._MSGestureHandler) {
  10897. _this._MSGestureHandler = new MSGesture();
  10898. _this._MSGestureHandler.target = element;
  10899. }
  10900. _this._MSGestureHandler.addPointer(e.pointerId);
  10901. };
  10902. this._onGesture = function (e) {
  10903. _this.radius *= e.scale;
  10904. if (e.preventDefault) {
  10905. if (!noPreventDefault) {
  10906. e.stopPropagation();
  10907. e.preventDefault();
  10908. }
  10909. }
  10910. };
  10911. this._reset = function () {
  10912. _this._keys = [];
  10913. _this.inertialAlphaOffset = 0;
  10914. _this.inertialBetaOffset = 0;
  10915. _this.inertialRadiusOffset = 0;
  10916. pointers.empty();
  10917. previousPinchDistance = 0;
  10918. cacheSoloPointer = null;
  10919. };
  10920. }
  10921. if (!useCtrlForPanning) {
  10922. element.addEventListener("contextmenu", this._onContextMenu, false);
  10923. }
  10924. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10925. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10926. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10927. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10928. element.addEventListener("mousemove", this._onMouseMove, false);
  10929. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10930. element.addEventListener("MSGestureChange", this._onGesture, false);
  10931. element.addEventListener('mousewheel', this._wheel, false);
  10932. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10933. BABYLON.Tools.RegisterTopRootEvents([
  10934. { name: "keydown", handler: this._onKeyDown },
  10935. { name: "keyup", handler: this._onKeyUp },
  10936. { name: "blur", handler: this._onLostFocus }
  10937. ]);
  10938. };
  10939. ArcRotateCamera.prototype.detachControl = function (element) {
  10940. if (this._attachedElement !== element) {
  10941. return;
  10942. }
  10943. element.removeEventListener("contextmenu", this._onContextMenu);
  10944. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10945. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10946. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10947. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10948. element.removeEventListener("mousemove", this._onMouseMove);
  10949. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10950. element.removeEventListener("MSGestureChange", this._onGesture);
  10951. element.removeEventListener('mousewheel', this._wheel);
  10952. element.removeEventListener('DOMMouseScroll', this._wheel);
  10953. BABYLON.Tools.UnregisterTopRootEvents([
  10954. { name: "keydown", handler: this._onKeyDown },
  10955. { name: "keyup", handler: this._onKeyUp },
  10956. { name: "blur", handler: this._onLostFocus }
  10957. ]);
  10958. this._MSGestureHandler = null;
  10959. this._attachedElement = null;
  10960. if (this._reset) {
  10961. this._reset();
  10962. }
  10963. };
  10964. ArcRotateCamera.prototype._checkInputs = function () {
  10965. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10966. if (this._collisionTriggered) {
  10967. return;
  10968. }
  10969. // Keyboard
  10970. for (var index = 0; index < this._keys.length; index++) {
  10971. var keyCode = this._keys[index];
  10972. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10973. this.inertialAlphaOffset -= 0.01;
  10974. }
  10975. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10976. this.inertialBetaOffset -= 0.01;
  10977. }
  10978. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10979. this.inertialAlphaOffset += 0.01;
  10980. }
  10981. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10982. this.inertialBetaOffset += 0.01;
  10983. }
  10984. }
  10985. // Inertia
  10986. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10987. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  10988. this.beta += this.inertialBetaOffset;
  10989. this.radius -= this.inertialRadiusOffset;
  10990. this.inertialAlphaOffset *= this.inertia;
  10991. this.inertialBetaOffset *= this.inertia;
  10992. this.inertialRadiusOffset *= this.inertia;
  10993. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10994. this.inertialAlphaOffset = 0;
  10995. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10996. this.inertialBetaOffset = 0;
  10997. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  10998. this.inertialRadiusOffset = 0;
  10999. }
  11000. // Panning inertia
  11001. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11002. if (!this._localDirection) {
  11003. this._localDirection = BABYLON.Vector3.Zero();
  11004. this._transformedDirection = BABYLON.Vector3.Zero();
  11005. }
  11006. this.inertialPanningX *= this.inertia;
  11007. this.inertialPanningY *= this.inertia;
  11008. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11009. this.inertialPanningX = 0;
  11010. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11011. this.inertialPanningY = 0;
  11012. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11013. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11014. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11015. this.target.addInPlace(this._transformedDirection);
  11016. }
  11017. // Limits
  11018. this._checkLimits();
  11019. _super.prototype._checkInputs.call(this);
  11020. };
  11021. ArcRotateCamera.prototype._checkLimits = function () {
  11022. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11023. if (this.allowUpsideDown && this.beta > Math.PI) {
  11024. this.beta = this.beta - (2 * Math.PI);
  11025. }
  11026. }
  11027. else {
  11028. if (this.beta < this.lowerBetaLimit) {
  11029. this.beta = this.lowerBetaLimit;
  11030. }
  11031. }
  11032. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11033. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11034. this.beta = this.beta + (2 * Math.PI);
  11035. }
  11036. }
  11037. else {
  11038. if (this.beta > this.upperBetaLimit) {
  11039. this.beta = this.upperBetaLimit;
  11040. }
  11041. }
  11042. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11043. this.alpha = this.lowerAlphaLimit;
  11044. }
  11045. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11046. this.alpha = this.upperAlphaLimit;
  11047. }
  11048. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11049. this.radius = this.lowerRadiusLimit;
  11050. }
  11051. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11052. this.radius = this.upperRadiusLimit;
  11053. }
  11054. };
  11055. ArcRotateCamera.prototype.setPosition = function (position) {
  11056. var radiusv3 = position.subtract(this._getTargetPosition());
  11057. this.radius = radiusv3.length();
  11058. // Alpha
  11059. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11060. if (radiusv3.z < 0) {
  11061. this.alpha = 2 * Math.PI - this.alpha;
  11062. }
  11063. // Beta
  11064. this.beta = Math.acos(radiusv3.y / this.radius);
  11065. this._checkLimits();
  11066. };
  11067. ArcRotateCamera.prototype.setTarget = function (target) {
  11068. this.target = target;
  11069. };
  11070. ArcRotateCamera.prototype._getViewMatrix = function () {
  11071. // Compute
  11072. var cosa = Math.cos(this.alpha);
  11073. var sina = Math.sin(this.alpha);
  11074. var cosb = Math.cos(this.beta);
  11075. var sinb = Math.sin(this.beta);
  11076. var target = this._getTargetPosition();
  11077. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11078. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11079. this._collider.radius = this.collisionRadius;
  11080. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11081. this._collisionTriggered = true;
  11082. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11083. }
  11084. else {
  11085. this.position.copyFrom(this._newPosition);
  11086. var up = this.upVector;
  11087. if (this.allowUpsideDown && this.beta < 0) {
  11088. var up = up.clone();
  11089. up = up.negate();
  11090. }
  11091. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11092. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11093. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11094. }
  11095. return this._viewMatrix;
  11096. };
  11097. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11098. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11099. meshes = meshes || this.getScene().meshes;
  11100. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11101. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11102. this.radius = distance * this.zoomOnFactor;
  11103. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11104. };
  11105. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11106. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11107. var meshesOrMinMaxVector;
  11108. var distance;
  11109. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11110. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11111. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11112. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11113. }
  11114. else {
  11115. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11116. distance = meshesOrMinMaxVectorAndDistance.distance;
  11117. }
  11118. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11119. if (!doNotUpdateMaxZ) {
  11120. this.maxZ = distance * 2;
  11121. }
  11122. };
  11123. /**
  11124. * @override
  11125. * Override Camera.createRigCamera
  11126. */
  11127. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11128. switch (this.cameraRigMode) {
  11129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11132. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11133. case BABYLON.Camera.RIG_MODE_VR:
  11134. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11135. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11136. }
  11137. };
  11138. /**
  11139. * @override
  11140. * Override Camera._updateRigCameras
  11141. */
  11142. ArcRotateCamera.prototype._updateRigCameras = function () {
  11143. switch (this.cameraRigMode) {
  11144. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11145. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11146. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11147. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11148. case BABYLON.Camera.RIG_MODE_VR:
  11149. var camLeft = this._rigCameras[0];
  11150. var camRight = this._rigCameras[1];
  11151. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11152. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11153. camLeft.beta = camRight.beta = this.beta;
  11154. camLeft.radius = camRight.radius = this.radius;
  11155. break;
  11156. }
  11157. _super.prototype._updateRigCameras.call(this);
  11158. };
  11159. return ArcRotateCamera;
  11160. })(BABYLON.TargetCamera);
  11161. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11162. })(BABYLON || (BABYLON = {}));
  11163. var BABYLON;
  11164. (function (BABYLON) {
  11165. var RenderingManager = (function () {
  11166. function RenderingManager(scene) {
  11167. this._renderingGroups = new Array();
  11168. this._scene = scene;
  11169. }
  11170. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11171. if (this._scene._activeParticleSystems.length === 0) {
  11172. return;
  11173. }
  11174. // Particles
  11175. var activeCamera = this._scene.activeCamera;
  11176. var beforeParticlesDate = BABYLON.Tools.Now;
  11177. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11178. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11179. if (particleSystem.renderingGroupId !== index) {
  11180. continue;
  11181. }
  11182. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11183. continue;
  11184. }
  11185. this._clearDepthBuffer();
  11186. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11187. this._scene._activeParticles += particleSystem.render();
  11188. }
  11189. }
  11190. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11191. };
  11192. RenderingManager.prototype._renderSprites = function (index) {
  11193. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11194. return;
  11195. }
  11196. // Sprites
  11197. var activeCamera = this._scene.activeCamera;
  11198. var beforeSpritessDate = BABYLON.Tools.Now;
  11199. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11200. var spriteManager = this._scene.spriteManagers[id];
  11201. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11202. this._clearDepthBuffer();
  11203. spriteManager.render();
  11204. }
  11205. }
  11206. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11207. };
  11208. RenderingManager.prototype._clearDepthBuffer = function () {
  11209. if (this._depthBufferAlreadyCleaned) {
  11210. return;
  11211. }
  11212. this._scene.getEngine().clear(0, false, true);
  11213. this._depthBufferAlreadyCleaned = true;
  11214. };
  11215. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11216. if (this._currentRenderSprites) {
  11217. this._renderSprites(this._currentIndex);
  11218. }
  11219. if (this._currentRenderParticles) {
  11220. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11221. }
  11222. };
  11223. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11224. this._currentActiveMeshes = activeMeshes;
  11225. this._currentRenderParticles = renderParticles;
  11226. this._currentRenderSprites = renderSprites;
  11227. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11228. this._depthBufferAlreadyCleaned = false;
  11229. var renderingGroup = this._renderingGroups[index];
  11230. var needToStepBack = false;
  11231. this._currentIndex = index;
  11232. if (renderingGroup) {
  11233. this._clearDepthBuffer();
  11234. if (!renderingGroup.onBeforeTransparentRendering) {
  11235. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11236. }
  11237. if (!renderingGroup.render(customRenderFunction)) {
  11238. this._renderingGroups.splice(index, 1);
  11239. needToStepBack = true;
  11240. this._renderSpritesAndParticles();
  11241. }
  11242. }
  11243. else {
  11244. this._renderSpritesAndParticles();
  11245. }
  11246. if (needToStepBack) {
  11247. index--;
  11248. }
  11249. }
  11250. };
  11251. RenderingManager.prototype.reset = function () {
  11252. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11253. if (renderingGroup) {
  11254. renderingGroup.prepare();
  11255. }
  11256. });
  11257. };
  11258. RenderingManager.prototype.dispatch = function (subMesh) {
  11259. var mesh = subMesh.getMesh();
  11260. var renderingGroupId = mesh.renderingGroupId || 0;
  11261. if (!this._renderingGroups[renderingGroupId]) {
  11262. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11263. }
  11264. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11265. };
  11266. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11267. return RenderingManager;
  11268. })();
  11269. BABYLON.RenderingManager = RenderingManager;
  11270. })(BABYLON || (BABYLON = {}));
  11271. var BABYLON;
  11272. (function (BABYLON) {
  11273. var RenderingGroup = (function () {
  11274. function RenderingGroup(index, scene) {
  11275. this.index = index;
  11276. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11277. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11278. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11279. this._scene = scene;
  11280. }
  11281. RenderingGroup.prototype.render = function (customRenderFunction) {
  11282. if (customRenderFunction) {
  11283. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11284. return true;
  11285. }
  11286. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11287. if (this.onBeforeTransparentRendering) {
  11288. this.onBeforeTransparentRendering();
  11289. }
  11290. return false;
  11291. }
  11292. var engine = this._scene.getEngine();
  11293. // Opaque
  11294. var subIndex;
  11295. var submesh;
  11296. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11297. submesh = this._opaqueSubMeshes.data[subIndex];
  11298. submesh.render(false);
  11299. }
  11300. // Alpha test
  11301. engine.setAlphaTesting(true);
  11302. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11303. submesh = this._alphaTestSubMeshes.data[subIndex];
  11304. submesh.render(false);
  11305. }
  11306. engine.setAlphaTesting(false);
  11307. if (this.onBeforeTransparentRendering) {
  11308. this.onBeforeTransparentRendering();
  11309. }
  11310. // Transparent
  11311. if (this._transparentSubMeshes.length) {
  11312. // Sorting
  11313. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11314. submesh = this._transparentSubMeshes.data[subIndex];
  11315. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11316. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11317. }
  11318. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11319. sortedArray.sort(function (a, b) {
  11320. // Alpha index first
  11321. if (a._alphaIndex > b._alphaIndex) {
  11322. return 1;
  11323. }
  11324. if (a._alphaIndex < b._alphaIndex) {
  11325. return -1;
  11326. }
  11327. // Then distance to camera
  11328. if (a._distanceToCamera < b._distanceToCamera) {
  11329. return 1;
  11330. }
  11331. if (a._distanceToCamera > b._distanceToCamera) {
  11332. return -1;
  11333. }
  11334. return 0;
  11335. });
  11336. // Rendering
  11337. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11338. submesh = sortedArray[subIndex];
  11339. submesh.render(true);
  11340. }
  11341. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11342. }
  11343. return true;
  11344. };
  11345. RenderingGroup.prototype.prepare = function () {
  11346. this._opaqueSubMeshes.reset();
  11347. this._transparentSubMeshes.reset();
  11348. this._alphaTestSubMeshes.reset();
  11349. };
  11350. RenderingGroup.prototype.dispatch = function (subMesh) {
  11351. var material = subMesh.getMaterial();
  11352. var mesh = subMesh.getMesh();
  11353. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11354. this._transparentSubMeshes.push(subMesh);
  11355. }
  11356. else if (material.needAlphaTesting()) {
  11357. this._alphaTestSubMeshes.push(subMesh);
  11358. }
  11359. else {
  11360. this._opaqueSubMeshes.push(subMesh); // Opaque
  11361. }
  11362. };
  11363. return RenderingGroup;
  11364. })();
  11365. BABYLON.RenderingGroup = RenderingGroup;
  11366. })(BABYLON || (BABYLON = {}));
  11367. var BABYLON;
  11368. (function (BABYLON) {
  11369. /**
  11370. * Represents a scene to be rendered by the engine.
  11371. * @see http://doc.babylonjs.com/page.php?p=21911
  11372. */
  11373. var Scene = (function () {
  11374. /**
  11375. * @constructor
  11376. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11377. */
  11378. function Scene(engine) {
  11379. // Members
  11380. this.autoClear = true;
  11381. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11382. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11383. this.forceWireframe = false;
  11384. this.forcePointsCloud = false;
  11385. this.forceShowBoundingBoxes = false;
  11386. this.animationsEnabled = true;
  11387. this.constantlyUpdateMeshUnderPointer = false;
  11388. 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
  11389. // Fog
  11390. /**
  11391. * is fog enabled on this scene.
  11392. * @type {boolean}
  11393. */
  11394. this.fogEnabled = true;
  11395. this.fogMode = Scene.FOGMODE_NONE;
  11396. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11397. this.fogDensity = 0.1;
  11398. this.fogStart = 0;
  11399. this.fogEnd = 1000.0;
  11400. // Lights
  11401. /**
  11402. * is shadow enabled on this scene.
  11403. * @type {boolean}
  11404. */
  11405. this.shadowsEnabled = true;
  11406. /**
  11407. * is light enabled on this scene.
  11408. * @type {boolean}
  11409. */
  11410. this.lightsEnabled = true;
  11411. /**
  11412. * All of the lights added to this scene.
  11413. * @see BABYLON.Light
  11414. * @type {BABYLON.Light[]}
  11415. */
  11416. this.lights = new Array();
  11417. // Cameras
  11418. /**
  11419. * All of the cameras added to this scene.
  11420. * @see BABYLON.Camera
  11421. * @type {BABYLON.Camera[]}
  11422. */
  11423. this.cameras = new Array();
  11424. this.activeCameras = new Array();
  11425. // Meshes
  11426. /**
  11427. * All of the (abstract) meshes added to this scene.
  11428. * @see BABYLON.AbstractMesh
  11429. * @type {BABYLON.AbstractMesh[]}
  11430. */
  11431. this.meshes = new Array();
  11432. // Geometries
  11433. this._geometries = new Array();
  11434. this.materials = new Array();
  11435. this.multiMaterials = new Array();
  11436. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11437. // Textures
  11438. this.texturesEnabled = true;
  11439. this.textures = new Array();
  11440. // Particles
  11441. this.particlesEnabled = true;
  11442. this.particleSystems = new Array();
  11443. // Sprites
  11444. this.spritesEnabled = true;
  11445. this.spriteManagers = new Array();
  11446. // Layers
  11447. this.layers = new Array();
  11448. // Skeletons
  11449. this.skeletonsEnabled = true;
  11450. this.skeletons = new Array();
  11451. // Lens flares
  11452. this.lensFlaresEnabled = true;
  11453. this.lensFlareSystems = new Array();
  11454. // Collisions
  11455. this.collisionsEnabled = true;
  11456. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11457. // Postprocesses
  11458. this.postProcessesEnabled = true;
  11459. // Customs render targets
  11460. this.renderTargetsEnabled = true;
  11461. this.dumpNextRenderTargets = false;
  11462. this.customRenderTargets = new Array();
  11463. // Imported meshes
  11464. this.importedMeshesFiles = new Array();
  11465. // Probes
  11466. this.probesEnabled = true;
  11467. this.reflectionProbes = new Array();
  11468. this._actionManagers = new Array();
  11469. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11470. // Procedural textures
  11471. this.proceduralTexturesEnabled = true;
  11472. this._proceduralTextures = new Array();
  11473. this.soundTracks = new Array();
  11474. this._audioEnabled = true;
  11475. this._headphone = false;
  11476. this._totalVertices = 0;
  11477. this._activeIndices = 0;
  11478. this._activeParticles = 0;
  11479. this._lastFrameDuration = 0;
  11480. this._evaluateActiveMeshesDuration = 0;
  11481. this._renderTargetsDuration = 0;
  11482. this._particlesDuration = 0;
  11483. this._renderDuration = 0;
  11484. this._spritesDuration = 0;
  11485. this._animationRatio = 0;
  11486. this._renderId = 0;
  11487. this._executeWhenReadyTimeoutId = -1;
  11488. this._toBeDisposed = new BABYLON.SmartArray(256);
  11489. this._onReadyCallbacks = new Array();
  11490. this._pendingData = []; //ANY
  11491. this._onBeforeRenderCallbacks = new Array();
  11492. this._onAfterRenderCallbacks = new Array();
  11493. this._activeMeshes = new BABYLON.SmartArray(256);
  11494. this._processedMaterials = new BABYLON.SmartArray(256);
  11495. this._renderTargets = new BABYLON.SmartArray(256);
  11496. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11497. this._activeSkeletons = new BABYLON.SmartArray(32);
  11498. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11499. this._activeBones = 0;
  11500. this._activeAnimatables = new Array();
  11501. this._transformMatrix = BABYLON.Matrix.Zero();
  11502. this._edgesRenderers = new BABYLON.SmartArray(16);
  11503. this._uniqueIdCounter = 0;
  11504. this._engine = engine;
  11505. engine.scenes.push(this);
  11506. this._renderingManager = new BABYLON.RenderingManager(this);
  11507. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11508. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11509. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11510. if (BABYLON.OutlineRenderer) {
  11511. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11512. }
  11513. this.attachControl();
  11514. this._debugLayer = new BABYLON.DebugLayer(this);
  11515. if (BABYLON.SoundTrack) {
  11516. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11517. }
  11518. //simplification queue
  11519. if (BABYLON.SimplificationQueue) {
  11520. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11521. }
  11522. //collision coordinator initialization. For now legacy per default.
  11523. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11524. }
  11525. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11526. get: function () {
  11527. return Scene._FOGMODE_NONE;
  11528. },
  11529. enumerable: true,
  11530. configurable: true
  11531. });
  11532. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11533. get: function () {
  11534. return Scene._FOGMODE_EXP;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11540. get: function () {
  11541. return Scene._FOGMODE_EXP2;
  11542. },
  11543. enumerable: true,
  11544. configurable: true
  11545. });
  11546. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11547. get: function () {
  11548. return Scene._FOGMODE_LINEAR;
  11549. },
  11550. enumerable: true,
  11551. configurable: true
  11552. });
  11553. Object.defineProperty(Scene.prototype, "debugLayer", {
  11554. // Properties
  11555. get: function () {
  11556. return this._debugLayer;
  11557. },
  11558. enumerable: true,
  11559. configurable: true
  11560. });
  11561. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11562. get: function () {
  11563. return this._workerCollisions;
  11564. },
  11565. set: function (enabled) {
  11566. enabled = (enabled && !!Worker);
  11567. this._workerCollisions = enabled;
  11568. if (this.collisionCoordinator) {
  11569. this.collisionCoordinator.destroy();
  11570. }
  11571. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11572. this.collisionCoordinator.init(this);
  11573. },
  11574. enumerable: true,
  11575. configurable: true
  11576. });
  11577. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11578. get: function () {
  11579. return this._selectionOctree;
  11580. },
  11581. enumerable: true,
  11582. configurable: true
  11583. });
  11584. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11585. /**
  11586. * The mesh that is currently under the pointer.
  11587. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11588. */
  11589. get: function () {
  11590. return this._meshUnderPointer;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Scene.prototype, "pointerX", {
  11596. /**
  11597. * Current on-screen X position of the pointer
  11598. * @return {number} X position of the pointer
  11599. */
  11600. get: function () {
  11601. return this._pointerX;
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. Object.defineProperty(Scene.prototype, "pointerY", {
  11607. /**
  11608. * Current on-screen Y position of the pointer
  11609. * @return {number} Y position of the pointer
  11610. */
  11611. get: function () {
  11612. return this._pointerY;
  11613. },
  11614. enumerable: true,
  11615. configurable: true
  11616. });
  11617. Scene.prototype.getCachedMaterial = function () {
  11618. return this._cachedMaterial;
  11619. };
  11620. Scene.prototype.getBoundingBoxRenderer = function () {
  11621. return this._boundingBoxRenderer;
  11622. };
  11623. Scene.prototype.getOutlineRenderer = function () {
  11624. return this._outlineRenderer;
  11625. };
  11626. Scene.prototype.getEngine = function () {
  11627. return this._engine;
  11628. };
  11629. Scene.prototype.getTotalVertices = function () {
  11630. return this._totalVertices;
  11631. };
  11632. Scene.prototype.getActiveIndices = function () {
  11633. return this._activeIndices;
  11634. };
  11635. Scene.prototype.getActiveParticles = function () {
  11636. return this._activeParticles;
  11637. };
  11638. Scene.prototype.getActiveBones = function () {
  11639. return this._activeBones;
  11640. };
  11641. // Stats
  11642. Scene.prototype.getLastFrameDuration = function () {
  11643. return this._lastFrameDuration;
  11644. };
  11645. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11646. return this._evaluateActiveMeshesDuration;
  11647. };
  11648. Scene.prototype.getActiveMeshes = function () {
  11649. return this._activeMeshes;
  11650. };
  11651. Scene.prototype.getRenderTargetsDuration = function () {
  11652. return this._renderTargetsDuration;
  11653. };
  11654. Scene.prototype.getRenderDuration = function () {
  11655. return this._renderDuration;
  11656. };
  11657. Scene.prototype.getParticlesDuration = function () {
  11658. return this._particlesDuration;
  11659. };
  11660. Scene.prototype.getSpritesDuration = function () {
  11661. return this._spritesDuration;
  11662. };
  11663. Scene.prototype.getAnimationRatio = function () {
  11664. return this._animationRatio;
  11665. };
  11666. Scene.prototype.getRenderId = function () {
  11667. return this._renderId;
  11668. };
  11669. Scene.prototype.incrementRenderId = function () {
  11670. this._renderId++;
  11671. };
  11672. Scene.prototype._updatePointerPosition = function (evt) {
  11673. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11674. this._pointerX = evt.clientX - canvasRect.left;
  11675. this._pointerY = evt.clientY - canvasRect.top;
  11676. if (this.cameraToUseForPointers) {
  11677. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11678. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11679. }
  11680. };
  11681. // Pointers handling
  11682. Scene.prototype.attachControl = function () {
  11683. var _this = this;
  11684. var spritePredicate = function (sprite) {
  11685. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11686. };
  11687. this._onPointerMove = function (evt) {
  11688. var canvas = _this._engine.getRenderingCanvas();
  11689. _this._updatePointerPosition(evt);
  11690. // Meshes
  11691. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  11692. if (pickResult.hit && pickResult.pickedMesh) {
  11693. _this._meshUnderPointer = pickResult.pickedMesh;
  11694. _this.setPointerOverMesh(pickResult.pickedMesh);
  11695. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11696. canvas.style.cursor = "pointer";
  11697. }
  11698. else {
  11699. canvas.style.cursor = "";
  11700. }
  11701. }
  11702. else {
  11703. // Sprites
  11704. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11705. if (pickResult.hit && pickResult.pickedSprite) {
  11706. canvas.style.cursor = "pointer";
  11707. return;
  11708. }
  11709. // Restore pointer
  11710. _this.setPointerOverMesh(null);
  11711. canvas.style.cursor = "";
  11712. _this._meshUnderPointer = null;
  11713. }
  11714. };
  11715. this._onPointerDown = function (evt) {
  11716. _this._updatePointerPosition(evt);
  11717. var predicate = null;
  11718. // Meshes
  11719. if (!_this.onPointerDown) {
  11720. predicate = function (mesh) {
  11721. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11722. };
  11723. }
  11724. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11725. if (pickResult.hit && pickResult.pickedMesh) {
  11726. if (pickResult.pickedMesh.actionManager) {
  11727. switch (evt.button) {
  11728. case 0:
  11729. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11730. break;
  11731. case 1:
  11732. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11733. break;
  11734. case 2:
  11735. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11736. break;
  11737. }
  11738. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11739. }
  11740. }
  11741. if (_this.onPointerDown) {
  11742. _this.onPointerDown(evt, pickResult);
  11743. }
  11744. // Sprites
  11745. if (_this.spriteManagers.length > 0) {
  11746. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11747. if (pickResult.hit && pickResult.pickedSprite) {
  11748. if (pickResult.pickedSprite.actionManager) {
  11749. switch (evt.button) {
  11750. case 0:
  11751. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11752. break;
  11753. case 1:
  11754. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11755. break;
  11756. case 2:
  11757. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11758. break;
  11759. }
  11760. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11761. }
  11762. }
  11763. }
  11764. };
  11765. this._onPointerUp = function (evt) {
  11766. var predicate = null;
  11767. _this._updatePointerPosition(evt);
  11768. if (!_this.onPointerUp) {
  11769. predicate = function (mesh) {
  11770. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11771. };
  11772. }
  11773. // Meshes
  11774. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11775. if (pickResult.hit && pickResult.pickedMesh) {
  11776. if (pickResult.pickedMesh.actionManager) {
  11777. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11778. }
  11779. }
  11780. if (_this.onPointerUp) {
  11781. _this.onPointerUp(evt, pickResult);
  11782. }
  11783. // Sprites
  11784. if (_this.spriteManagers.length > 0) {
  11785. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11786. if (pickResult.hit && pickResult.pickedSprite) {
  11787. if (pickResult.pickedSprite.actionManager) {
  11788. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11789. }
  11790. }
  11791. }
  11792. };
  11793. this._onKeyDown = function (evt) {
  11794. if (_this.actionManager) {
  11795. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11796. }
  11797. };
  11798. this._onKeyUp = function (evt) {
  11799. if (_this.actionManager) {
  11800. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11801. }
  11802. };
  11803. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11804. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11805. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11806. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11807. // Wheel
  11808. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11809. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11810. BABYLON.Tools.RegisterTopRootEvents([
  11811. { name: "keydown", handler: this._onKeyDown },
  11812. { name: "keyup", handler: this._onKeyUp }
  11813. ]);
  11814. };
  11815. Scene.prototype.detachControl = function () {
  11816. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11817. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11818. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11819. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11820. // Wheel
  11821. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  11822. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  11823. BABYLON.Tools.UnregisterTopRootEvents([
  11824. { name: "keydown", handler: this._onKeyDown },
  11825. { name: "keyup", handler: this._onKeyUp }
  11826. ]);
  11827. };
  11828. // Ready
  11829. Scene.prototype.isReady = function () {
  11830. if (this._pendingData.length > 0) {
  11831. return false;
  11832. }
  11833. var index;
  11834. for (index = 0; index < this._geometries.length; index++) {
  11835. var geometry = this._geometries[index];
  11836. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11837. return false;
  11838. }
  11839. }
  11840. for (index = 0; index < this.meshes.length; index++) {
  11841. var mesh = this.meshes[index];
  11842. if (!mesh.isReady()) {
  11843. return false;
  11844. }
  11845. var mat = mesh.material;
  11846. if (mat) {
  11847. if (!mat.isReady(mesh)) {
  11848. return false;
  11849. }
  11850. }
  11851. }
  11852. return true;
  11853. };
  11854. Scene.prototype.resetCachedMaterial = function () {
  11855. this._cachedMaterial = null;
  11856. };
  11857. Scene.prototype.registerBeforeRender = function (func) {
  11858. this._onBeforeRenderCallbacks.push(func);
  11859. };
  11860. Scene.prototype.unregisterBeforeRender = function (func) {
  11861. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11862. if (index > -1) {
  11863. this._onBeforeRenderCallbacks.splice(index, 1);
  11864. }
  11865. };
  11866. Scene.prototype.registerAfterRender = function (func) {
  11867. this._onAfterRenderCallbacks.push(func);
  11868. };
  11869. Scene.prototype.unregisterAfterRender = function (func) {
  11870. var index = this._onAfterRenderCallbacks.indexOf(func);
  11871. if (index > -1) {
  11872. this._onAfterRenderCallbacks.splice(index, 1);
  11873. }
  11874. };
  11875. Scene.prototype._addPendingData = function (data) {
  11876. this._pendingData.push(data);
  11877. };
  11878. Scene.prototype._removePendingData = function (data) {
  11879. var index = this._pendingData.indexOf(data);
  11880. if (index !== -1) {
  11881. this._pendingData.splice(index, 1);
  11882. }
  11883. };
  11884. Scene.prototype.getWaitingItemsCount = function () {
  11885. return this._pendingData.length;
  11886. };
  11887. /**
  11888. * Registers a function to be executed when the scene is ready.
  11889. * @param {Function} func - the function to be executed.
  11890. */
  11891. Scene.prototype.executeWhenReady = function (func) {
  11892. var _this = this;
  11893. this._onReadyCallbacks.push(func);
  11894. if (this._executeWhenReadyTimeoutId !== -1) {
  11895. return;
  11896. }
  11897. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11898. _this._checkIsReady();
  11899. }, 150);
  11900. };
  11901. Scene.prototype._checkIsReady = function () {
  11902. var _this = this;
  11903. if (this.isReady()) {
  11904. this._onReadyCallbacks.forEach(function (func) {
  11905. func();
  11906. });
  11907. this._onReadyCallbacks = [];
  11908. this._executeWhenReadyTimeoutId = -1;
  11909. return;
  11910. }
  11911. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11912. _this._checkIsReady();
  11913. }, 150);
  11914. };
  11915. // Animations
  11916. /**
  11917. * Will start the animation sequence of a given target
  11918. * @param target - the target
  11919. * @param {number} from - from which frame should animation start
  11920. * @param {number} to - till which frame should animation run.
  11921. * @param {boolean} [loop] - should the animation loop
  11922. * @param {number} [speedRatio] - the speed in which to run the animation
  11923. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11924. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11925. * @return {BABYLON.Animatable} the animatable object created for this animation
  11926. * @see BABYLON.Animatable
  11927. * @see http://doc.babylonjs.com/page.php?p=22081
  11928. */
  11929. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11930. if (speedRatio === void 0) { speedRatio = 1.0; }
  11931. this.stopAnimation(target);
  11932. if (!animatable) {
  11933. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11934. }
  11935. // Local animations
  11936. if (target.animations) {
  11937. animatable.appendAnimations(target, target.animations);
  11938. }
  11939. // Children animations
  11940. if (target.getAnimatables) {
  11941. var animatables = target.getAnimatables();
  11942. for (var index = 0; index < animatables.length; index++) {
  11943. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11944. }
  11945. }
  11946. return animatable;
  11947. };
  11948. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11949. if (speedRatio === undefined) {
  11950. speedRatio = 1.0;
  11951. }
  11952. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11953. return animatable;
  11954. };
  11955. Scene.prototype.getAnimatableByTarget = function (target) {
  11956. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11957. if (this._activeAnimatables[index].target === target) {
  11958. return this._activeAnimatables[index];
  11959. }
  11960. }
  11961. return null;
  11962. };
  11963. /**
  11964. * Will stop the animation of the given target
  11965. * @param target - the target
  11966. * @see beginAnimation
  11967. */
  11968. Scene.prototype.stopAnimation = function (target) {
  11969. var animatable = this.getAnimatableByTarget(target);
  11970. if (animatable) {
  11971. animatable.stop();
  11972. }
  11973. };
  11974. Scene.prototype._animate = function () {
  11975. if (!this.animationsEnabled) {
  11976. return;
  11977. }
  11978. if (!this._animationStartDate) {
  11979. this._animationStartDate = BABYLON.Tools.Now;
  11980. }
  11981. // Getting time
  11982. var now = BABYLON.Tools.Now;
  11983. var delay = now - this._animationStartDate;
  11984. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11985. this._activeAnimatables[index]._animate(delay);
  11986. }
  11987. };
  11988. // Matrix
  11989. Scene.prototype.getViewMatrix = function () {
  11990. return this._viewMatrix;
  11991. };
  11992. Scene.prototype.getProjectionMatrix = function () {
  11993. return this._projectionMatrix;
  11994. };
  11995. Scene.prototype.getTransformMatrix = function () {
  11996. return this._transformMatrix;
  11997. };
  11998. Scene.prototype.setTransformMatrix = function (view, projection) {
  11999. this._viewMatrix = view;
  12000. this._projectionMatrix = projection;
  12001. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12002. };
  12003. // Methods
  12004. Scene.prototype.addMesh = function (newMesh) {
  12005. newMesh.uniqueId = this._uniqueIdCounter++;
  12006. var position = this.meshes.push(newMesh);
  12007. //notify the collision coordinator
  12008. this.collisionCoordinator.onMeshAdded(newMesh);
  12009. if (this.onNewMeshAdded) {
  12010. this.onNewMeshAdded(newMesh, position, this);
  12011. }
  12012. };
  12013. Scene.prototype.removeMesh = function (toRemove) {
  12014. var index = this.meshes.indexOf(toRemove);
  12015. if (index !== -1) {
  12016. // Remove from the scene if mesh found
  12017. this.meshes.splice(index, 1);
  12018. }
  12019. //notify the collision coordinator
  12020. this.collisionCoordinator.onMeshRemoved(toRemove);
  12021. if (this.onMeshRemoved) {
  12022. this.onMeshRemoved(toRemove);
  12023. }
  12024. return index;
  12025. };
  12026. Scene.prototype.removeLight = function (toRemove) {
  12027. var index = this.lights.indexOf(toRemove);
  12028. if (index !== -1) {
  12029. // Remove from the scene if mesh found
  12030. this.lights.splice(index, 1);
  12031. }
  12032. if (this.onLightRemoved) {
  12033. this.onLightRemoved(toRemove);
  12034. }
  12035. return index;
  12036. };
  12037. Scene.prototype.removeCamera = function (toRemove) {
  12038. var index = this.cameras.indexOf(toRemove);
  12039. if (index !== -1) {
  12040. // Remove from the scene if mesh found
  12041. this.cameras.splice(index, 1);
  12042. }
  12043. // Remove from activeCameras
  12044. var index2 = this.activeCameras.indexOf(toRemove);
  12045. if (index2 !== -1) {
  12046. // Remove from the scene if mesh found
  12047. this.activeCameras.splice(index2, 1);
  12048. }
  12049. // Reset the activeCamera
  12050. if (this.activeCamera === toRemove) {
  12051. if (this.cameras.length > 0) {
  12052. this.activeCamera = this.cameras[0];
  12053. }
  12054. else {
  12055. this.activeCamera = null;
  12056. }
  12057. }
  12058. if (this.onCameraRemoved) {
  12059. this.onCameraRemoved(toRemove);
  12060. }
  12061. return index;
  12062. };
  12063. Scene.prototype.addLight = function (newLight) {
  12064. newLight.uniqueId = this._uniqueIdCounter++;
  12065. var position = this.lights.push(newLight);
  12066. if (this.onNewLightAdded) {
  12067. this.onNewLightAdded(newLight, position, this);
  12068. }
  12069. };
  12070. Scene.prototype.addCamera = function (newCamera) {
  12071. newCamera.uniqueId = this._uniqueIdCounter++;
  12072. var position = this.cameras.push(newCamera);
  12073. if (this.onNewCameraAdded) {
  12074. this.onNewCameraAdded(newCamera, position, this);
  12075. }
  12076. };
  12077. /**
  12078. * sets the active camera of the scene using its ID
  12079. * @param {string} id - the camera's ID
  12080. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12081. * @see activeCamera
  12082. */
  12083. Scene.prototype.setActiveCameraByID = function (id) {
  12084. var camera = this.getCameraByID(id);
  12085. if (camera) {
  12086. this.activeCamera = camera;
  12087. return camera;
  12088. }
  12089. return null;
  12090. };
  12091. /**
  12092. * sets the active camera of the scene using its name
  12093. * @param {string} name - the camera's name
  12094. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12095. * @see activeCamera
  12096. */
  12097. Scene.prototype.setActiveCameraByName = function (name) {
  12098. var camera = this.getCameraByName(name);
  12099. if (camera) {
  12100. this.activeCamera = camera;
  12101. return camera;
  12102. }
  12103. return null;
  12104. };
  12105. /**
  12106. * get a material using its id
  12107. * @param {string} the material's ID
  12108. * @return {BABYLON.Material|null} the material or null if none found.
  12109. */
  12110. Scene.prototype.getMaterialByID = function (id) {
  12111. for (var index = 0; index < this.materials.length; index++) {
  12112. if (this.materials[index].id === id) {
  12113. return this.materials[index];
  12114. }
  12115. }
  12116. return null;
  12117. };
  12118. /**
  12119. * get a material using its name
  12120. * @param {string} the material's name
  12121. * @return {BABYLON.Material|null} the material or null if none found.
  12122. */
  12123. Scene.prototype.getMaterialByName = function (name) {
  12124. for (var index = 0; index < this.materials.length; index++) {
  12125. if (this.materials[index].name === name) {
  12126. return this.materials[index];
  12127. }
  12128. }
  12129. return null;
  12130. };
  12131. Scene.prototype.getLensFlareSystemByName = function (name) {
  12132. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12133. if (this.lensFlareSystems[index].name === name) {
  12134. return this.lensFlareSystems[index];
  12135. }
  12136. }
  12137. return null;
  12138. };
  12139. Scene.prototype.getCameraByID = function (id) {
  12140. for (var index = 0; index < this.cameras.length; index++) {
  12141. if (this.cameras[index].id === id) {
  12142. return this.cameras[index];
  12143. }
  12144. }
  12145. return null;
  12146. };
  12147. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12148. for (var index = 0; index < this.cameras.length; index++) {
  12149. if (this.cameras[index].uniqueId === uniqueId) {
  12150. return this.cameras[index];
  12151. }
  12152. }
  12153. return null;
  12154. };
  12155. /**
  12156. * get a camera using its name
  12157. * @param {string} the camera's name
  12158. * @return {BABYLON.Camera|null} the camera or null if none found.
  12159. */
  12160. Scene.prototype.getCameraByName = function (name) {
  12161. for (var index = 0; index < this.cameras.length; index++) {
  12162. if (this.cameras[index].name === name) {
  12163. return this.cameras[index];
  12164. }
  12165. }
  12166. return null;
  12167. };
  12168. /**
  12169. * get a light node using its name
  12170. * @param {string} the light's name
  12171. * @return {BABYLON.Light|null} the light or null if none found.
  12172. */
  12173. Scene.prototype.getLightByName = function (name) {
  12174. for (var index = 0; index < this.lights.length; index++) {
  12175. if (this.lights[index].name === name) {
  12176. return this.lights[index];
  12177. }
  12178. }
  12179. return null;
  12180. };
  12181. /**
  12182. * get a light node using its ID
  12183. * @param {string} the light's id
  12184. * @return {BABYLON.Light|null} the light or null if none found.
  12185. */
  12186. Scene.prototype.getLightByID = function (id) {
  12187. for (var index = 0; index < this.lights.length; index++) {
  12188. if (this.lights[index].id === id) {
  12189. return this.lights[index];
  12190. }
  12191. }
  12192. return null;
  12193. };
  12194. /**
  12195. * get a light node using its scene-generated unique ID
  12196. * @param {number} the light's unique id
  12197. * @return {BABYLON.Light|null} the light or null if none found.
  12198. */
  12199. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12200. for (var index = 0; index < this.lights.length; index++) {
  12201. if (this.lights[index].uniqueId === uniqueId) {
  12202. return this.lights[index];
  12203. }
  12204. }
  12205. return null;
  12206. };
  12207. /**
  12208. * get a geometry using its ID
  12209. * @param {string} the geometry's id
  12210. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12211. */
  12212. Scene.prototype.getGeometryByID = function (id) {
  12213. for (var index = 0; index < this._geometries.length; index++) {
  12214. if (this._geometries[index].id === id) {
  12215. return this._geometries[index];
  12216. }
  12217. }
  12218. return null;
  12219. };
  12220. /**
  12221. * add a new geometry to this scene.
  12222. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12223. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12224. * @return {boolean} was the geometry added or not
  12225. */
  12226. Scene.prototype.pushGeometry = function (geometry, force) {
  12227. if (!force && this.getGeometryByID(geometry.id)) {
  12228. return false;
  12229. }
  12230. this._geometries.push(geometry);
  12231. //notify the collision coordinator
  12232. this.collisionCoordinator.onGeometryAdded(geometry);
  12233. if (this.onGeometryAdded) {
  12234. this.onGeometryAdded(geometry);
  12235. }
  12236. return true;
  12237. };
  12238. /**
  12239. * Removes an existing geometry
  12240. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12241. * @return {boolean} was the geometry removed or not
  12242. */
  12243. Scene.prototype.removeGeometry = function (geometry) {
  12244. var index = this._geometries.indexOf(geometry);
  12245. if (index > -1) {
  12246. this._geometries.splice(index, 1);
  12247. //notify the collision coordinator
  12248. this.collisionCoordinator.onGeometryDeleted(geometry);
  12249. if (this.onGeometryRemoved) {
  12250. this.onGeometryRemoved(geometry);
  12251. }
  12252. return true;
  12253. }
  12254. return false;
  12255. };
  12256. Scene.prototype.getGeometries = function () {
  12257. return this._geometries;
  12258. };
  12259. /**
  12260. * Get the first added mesh found of a given ID
  12261. * @param {string} id - the id to search for
  12262. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12263. */
  12264. Scene.prototype.getMeshByID = function (id) {
  12265. for (var index = 0; index < this.meshes.length; index++) {
  12266. if (this.meshes[index].id === id) {
  12267. return this.meshes[index];
  12268. }
  12269. }
  12270. return null;
  12271. };
  12272. /**
  12273. * Get a mesh with its auto-generated unique id
  12274. * @param {number} uniqueId - the unique id to search for
  12275. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12276. */
  12277. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12278. for (var index = 0; index < this.meshes.length; index++) {
  12279. if (this.meshes[index].uniqueId === uniqueId) {
  12280. return this.meshes[index];
  12281. }
  12282. }
  12283. return null;
  12284. };
  12285. /**
  12286. * Get a the last added mesh found of a given ID
  12287. * @param {string} id - the id to search for
  12288. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12289. */
  12290. Scene.prototype.getLastMeshByID = function (id) {
  12291. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12292. if (this.meshes[index].id === id) {
  12293. return this.meshes[index];
  12294. }
  12295. }
  12296. return null;
  12297. };
  12298. /**
  12299. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12300. * @param {string} id - the id to search for
  12301. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12302. */
  12303. Scene.prototype.getLastEntryByID = function (id) {
  12304. var index;
  12305. for (index = this.meshes.length - 1; index >= 0; index--) {
  12306. if (this.meshes[index].id === id) {
  12307. return this.meshes[index];
  12308. }
  12309. }
  12310. for (index = this.cameras.length - 1; index >= 0; index--) {
  12311. if (this.cameras[index].id === id) {
  12312. return this.cameras[index];
  12313. }
  12314. }
  12315. for (index = this.lights.length - 1; index >= 0; index--) {
  12316. if (this.lights[index].id === id) {
  12317. return this.lights[index];
  12318. }
  12319. }
  12320. return null;
  12321. };
  12322. Scene.prototype.getNodeByID = function (id) {
  12323. var mesh = this.getMeshByID(id);
  12324. if (mesh) {
  12325. return mesh;
  12326. }
  12327. var light = this.getLightByID(id);
  12328. if (light) {
  12329. return light;
  12330. }
  12331. return this.getCameraByID(id);
  12332. };
  12333. Scene.prototype.getNodeByName = function (name) {
  12334. var mesh = this.getMeshByName(name);
  12335. if (mesh) {
  12336. return mesh;
  12337. }
  12338. var light = this.getLightByName(name);
  12339. if (light) {
  12340. return light;
  12341. }
  12342. return this.getCameraByName(name);
  12343. };
  12344. Scene.prototype.getMeshByName = function (name) {
  12345. for (var index = 0; index < this.meshes.length; index++) {
  12346. if (this.meshes[index].name === name) {
  12347. return this.meshes[index];
  12348. }
  12349. }
  12350. return null;
  12351. };
  12352. Scene.prototype.getSoundByName = function (name) {
  12353. var index;
  12354. if (BABYLON.AudioEngine) {
  12355. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12356. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12357. return this.mainSoundTrack.soundCollection[index];
  12358. }
  12359. }
  12360. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12361. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12362. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12363. return this.soundTracks[sdIndex].soundCollection[index];
  12364. }
  12365. }
  12366. }
  12367. }
  12368. return null;
  12369. };
  12370. Scene.prototype.getLastSkeletonByID = function (id) {
  12371. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12372. if (this.skeletons[index].id === id) {
  12373. return this.skeletons[index];
  12374. }
  12375. }
  12376. return null;
  12377. };
  12378. Scene.prototype.getSkeletonById = function (id) {
  12379. for (var index = 0; index < this.skeletons.length; index++) {
  12380. if (this.skeletons[index].id === id) {
  12381. return this.skeletons[index];
  12382. }
  12383. }
  12384. return null;
  12385. };
  12386. Scene.prototype.getSkeletonByName = function (name) {
  12387. for (var index = 0; index < this.skeletons.length; index++) {
  12388. if (this.skeletons[index].name === name) {
  12389. return this.skeletons[index];
  12390. }
  12391. }
  12392. return null;
  12393. };
  12394. Scene.prototype.isActiveMesh = function (mesh) {
  12395. return (this._activeMeshes.indexOf(mesh) !== -1);
  12396. };
  12397. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12398. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12399. var material = subMesh.getMaterial();
  12400. if (mesh.showSubMeshesBoundingBox) {
  12401. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12402. }
  12403. if (material) {
  12404. // Render targets
  12405. if (material.getRenderTargetTextures) {
  12406. if (this._processedMaterials.indexOf(material) === -1) {
  12407. this._processedMaterials.push(material);
  12408. this._renderTargets.concat(material.getRenderTargetTextures());
  12409. }
  12410. }
  12411. // Dispatch
  12412. this._activeIndices += subMesh.indexCount;
  12413. this._renderingManager.dispatch(subMesh);
  12414. }
  12415. }
  12416. };
  12417. Scene.prototype._evaluateActiveMeshes = function () {
  12418. this.activeCamera._activeMeshes.reset();
  12419. this._activeMeshes.reset();
  12420. this._renderingManager.reset();
  12421. this._processedMaterials.reset();
  12422. this._activeParticleSystems.reset();
  12423. this._activeSkeletons.reset();
  12424. this._softwareSkinnedMeshes.reset();
  12425. this._boundingBoxRenderer.reset();
  12426. this._edgesRenderers.reset();
  12427. if (!this._frustumPlanes) {
  12428. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12429. }
  12430. else {
  12431. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12432. }
  12433. // Meshes
  12434. var meshes;
  12435. var len;
  12436. if (this._selectionOctree) {
  12437. var selection = this._selectionOctree.select(this._frustumPlanes);
  12438. meshes = selection.data;
  12439. len = selection.length;
  12440. }
  12441. else {
  12442. len = this.meshes.length;
  12443. meshes = this.meshes;
  12444. }
  12445. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12446. var mesh = meshes[meshIndex];
  12447. if (mesh.isBlocked) {
  12448. continue;
  12449. }
  12450. this._totalVertices += mesh.getTotalVertices();
  12451. if (!mesh.isReady() || !mesh.isEnabled()) {
  12452. continue;
  12453. }
  12454. mesh.computeWorldMatrix();
  12455. // Intersections
  12456. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12457. this._meshesForIntersections.pushNoDuplicate(mesh);
  12458. }
  12459. // Switch to current LOD
  12460. var meshLOD = mesh.getLOD(this.activeCamera);
  12461. if (!meshLOD) {
  12462. continue;
  12463. }
  12464. mesh._preActivate();
  12465. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12466. this._activeMeshes.push(mesh);
  12467. this.activeCamera._activeMeshes.push(mesh);
  12468. mesh._activate(this._renderId);
  12469. this._activeMesh(meshLOD);
  12470. }
  12471. }
  12472. // Particle systems
  12473. var beforeParticlesDate = BABYLON.Tools.Now;
  12474. if (this.particlesEnabled) {
  12475. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12476. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12477. var particleSystem = this.particleSystems[particleIndex];
  12478. if (!particleSystem.isStarted()) {
  12479. continue;
  12480. }
  12481. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12482. this._activeParticleSystems.push(particleSystem);
  12483. particleSystem.animate();
  12484. }
  12485. }
  12486. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12487. }
  12488. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12489. };
  12490. Scene.prototype._activeMesh = function (mesh) {
  12491. if (mesh.skeleton && this.skeletonsEnabled) {
  12492. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12493. if (!mesh.computeBonesUsingShaders) {
  12494. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12495. }
  12496. }
  12497. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12498. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12499. }
  12500. if (mesh._edgesRenderer) {
  12501. this._edgesRenderers.push(mesh._edgesRenderer);
  12502. }
  12503. if (mesh && mesh.subMeshes) {
  12504. // Submeshes Octrees
  12505. var len;
  12506. var subMeshes;
  12507. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12508. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12509. len = intersections.length;
  12510. subMeshes = intersections.data;
  12511. }
  12512. else {
  12513. subMeshes = mesh.subMeshes;
  12514. len = subMeshes.length;
  12515. }
  12516. for (var subIndex = 0; subIndex < len; subIndex++) {
  12517. var subMesh = subMeshes[subIndex];
  12518. this._evaluateSubMesh(subMesh, mesh);
  12519. }
  12520. }
  12521. };
  12522. Scene.prototype.updateTransformMatrix = function (force) {
  12523. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12524. };
  12525. Scene.prototype._renderForCamera = function (camera) {
  12526. var engine = this._engine;
  12527. this.activeCamera = camera;
  12528. if (!this.activeCamera)
  12529. throw new Error("Active camera not set");
  12530. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12531. // Viewport
  12532. engine.setViewport(this.activeCamera.viewport);
  12533. // Camera
  12534. this.resetCachedMaterial();
  12535. this._renderId++;
  12536. this.updateTransformMatrix();
  12537. if (this.beforeCameraRender) {
  12538. this.beforeCameraRender(this.activeCamera);
  12539. }
  12540. // Meshes
  12541. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12542. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12543. this._evaluateActiveMeshes();
  12544. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12545. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12546. // Skeletons
  12547. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12548. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12549. skeleton.prepare();
  12550. }
  12551. // Software skinning
  12552. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12553. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12554. mesh.applySkeleton(mesh.skeleton);
  12555. }
  12556. // Render targets
  12557. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12558. if (this.renderTargetsEnabled) {
  12559. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12560. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12561. var renderTarget = this._renderTargets.data[renderIndex];
  12562. if (renderTarget._shouldRender()) {
  12563. this._renderId++;
  12564. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12565. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12566. }
  12567. }
  12568. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12569. this._renderId++;
  12570. }
  12571. if (this._renderTargets.length > 0) {
  12572. engine.restoreDefaultFramebuffer();
  12573. }
  12574. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12575. // Prepare Frame
  12576. this.postProcessManager._prepareFrame();
  12577. var beforeRenderDate = BABYLON.Tools.Now;
  12578. // Backgrounds
  12579. var layerIndex;
  12580. var layer;
  12581. if (this.layers.length) {
  12582. engine.setDepthBuffer(false);
  12583. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12584. layer = this.layers[layerIndex];
  12585. if (layer.isBackground) {
  12586. layer.render();
  12587. }
  12588. }
  12589. engine.setDepthBuffer(true);
  12590. }
  12591. // Render
  12592. BABYLON.Tools.StartPerformanceCounter("Main render");
  12593. this._renderingManager.render(null, null, true, true);
  12594. BABYLON.Tools.EndPerformanceCounter("Main render");
  12595. // Bounding boxes
  12596. this._boundingBoxRenderer.render();
  12597. // Edges
  12598. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12599. this._edgesRenderers.data[edgesRendererIndex].render();
  12600. }
  12601. // Lens flares
  12602. if (this.lensFlaresEnabled) {
  12603. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12604. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12605. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12606. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12607. lensFlareSystem.render();
  12608. }
  12609. }
  12610. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12611. }
  12612. // Foregrounds
  12613. if (this.layers.length) {
  12614. engine.setDepthBuffer(false);
  12615. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12616. layer = this.layers[layerIndex];
  12617. if (!layer.isBackground) {
  12618. layer.render();
  12619. }
  12620. }
  12621. engine.setDepthBuffer(true);
  12622. }
  12623. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12624. // Finalize frame
  12625. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12626. // Update camera
  12627. this.activeCamera._updateFromScene();
  12628. // Reset some special arrays
  12629. this._renderTargets.reset();
  12630. if (this.afterCameraRender) {
  12631. this.afterCameraRender(this.activeCamera);
  12632. }
  12633. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12634. };
  12635. Scene.prototype._processSubCameras = function (camera) {
  12636. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12637. this._renderForCamera(camera);
  12638. return;
  12639. }
  12640. // rig cameras
  12641. for (var index = 0; index < camera._rigCameras.length; index++) {
  12642. this._renderForCamera(camera._rigCameras[index]);
  12643. }
  12644. this.activeCamera = camera;
  12645. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12646. // Update camera
  12647. this.activeCamera._updateFromScene();
  12648. };
  12649. Scene.prototype._checkIntersections = function () {
  12650. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12651. var sourceMesh = this._meshesForIntersections.data[index];
  12652. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12653. var action = sourceMesh.actionManager.actions[actionIndex];
  12654. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12655. var parameters = action.getTriggerParameter();
  12656. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12657. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12658. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12659. if (areIntersecting && currentIntersectionInProgress === -1) {
  12660. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12661. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12662. sourceMesh._intersectionsInProgress.push(otherMesh);
  12663. }
  12664. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12665. sourceMesh._intersectionsInProgress.push(otherMesh);
  12666. }
  12667. }
  12668. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12669. //They intersected, and now they don't.
  12670. //is this trigger an exit trigger? execute an event.
  12671. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12672. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12673. }
  12674. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12675. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12676. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12677. }
  12678. }
  12679. }
  12680. }
  12681. }
  12682. };
  12683. Scene.prototype.render = function () {
  12684. var startDate = BABYLON.Tools.Now;
  12685. this._particlesDuration = 0;
  12686. this._spritesDuration = 0;
  12687. this._activeParticles = 0;
  12688. this._renderDuration = 0;
  12689. this._renderTargetsDuration = 0;
  12690. this._evaluateActiveMeshesDuration = 0;
  12691. this._totalVertices = 0;
  12692. this._activeIndices = 0;
  12693. this._activeBones = 0;
  12694. this.getEngine().resetDrawCalls();
  12695. this._meshesForIntersections.reset();
  12696. this.resetCachedMaterial();
  12697. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12698. // Actions
  12699. if (this.actionManager) {
  12700. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12701. }
  12702. //Simplification Queue
  12703. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12704. this.simplificationQueue.executeNext();
  12705. }
  12706. // Animations
  12707. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12708. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12709. this._animate();
  12710. // Physics
  12711. if (this._physicsEngine) {
  12712. BABYLON.Tools.StartPerformanceCounter("Physics");
  12713. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12714. BABYLON.Tools.EndPerformanceCounter("Physics");
  12715. }
  12716. // Before render
  12717. if (this.beforeRender) {
  12718. this.beforeRender();
  12719. }
  12720. var callbackIndex;
  12721. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12722. this._onBeforeRenderCallbacks[callbackIndex]();
  12723. }
  12724. // Customs render targets
  12725. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12726. var engine = this.getEngine();
  12727. var currentActiveCamera = this.activeCamera;
  12728. if (this.renderTargetsEnabled) {
  12729. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12730. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12731. var renderTarget = this.customRenderTargets[customIndex];
  12732. if (renderTarget._shouldRender()) {
  12733. this._renderId++;
  12734. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12735. if (!this.activeCamera)
  12736. throw new Error("Active camera not set");
  12737. // Viewport
  12738. engine.setViewport(this.activeCamera.viewport);
  12739. // Camera
  12740. this.updateTransformMatrix();
  12741. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12742. }
  12743. }
  12744. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12745. this._renderId++;
  12746. }
  12747. if (this.customRenderTargets.length > 0) {
  12748. engine.restoreDefaultFramebuffer();
  12749. }
  12750. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12751. this.activeCamera = currentActiveCamera;
  12752. // Procedural textures
  12753. if (this.proceduralTexturesEnabled) {
  12754. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12755. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12756. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12757. if (proceduralTexture._shouldRender()) {
  12758. proceduralTexture.render();
  12759. }
  12760. }
  12761. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12762. }
  12763. // Clear
  12764. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12765. // Shadows
  12766. if (this.shadowsEnabled) {
  12767. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12768. var light = this.lights[lightIndex];
  12769. var shadowGenerator = light.getShadowGenerator();
  12770. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12771. this._renderTargets.push(shadowGenerator.getShadowMap());
  12772. }
  12773. }
  12774. }
  12775. // Depth renderer
  12776. if (this._depthRenderer) {
  12777. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12778. }
  12779. // RenderPipeline
  12780. this.postProcessRenderPipelineManager.update();
  12781. // Multi-cameras?
  12782. if (this.activeCameras.length > 0) {
  12783. var currentRenderId = this._renderId;
  12784. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12785. this._renderId = currentRenderId;
  12786. this._processSubCameras(this.activeCameras[cameraIndex]);
  12787. }
  12788. }
  12789. else {
  12790. if (!this.activeCamera) {
  12791. throw new Error("No camera defined");
  12792. }
  12793. this._processSubCameras(this.activeCamera);
  12794. }
  12795. // Intersection checks
  12796. this._checkIntersections();
  12797. // Update the audio listener attached to the camera
  12798. if (BABYLON.AudioEngine) {
  12799. this._updateAudioParameters();
  12800. }
  12801. // After render
  12802. if (this.afterRender) {
  12803. this.afterRender();
  12804. }
  12805. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12806. this._onAfterRenderCallbacks[callbackIndex]();
  12807. }
  12808. // Cleaning
  12809. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12810. this._toBeDisposed.data[index].dispose();
  12811. this._toBeDisposed[index] = null;
  12812. }
  12813. this._toBeDisposed.reset();
  12814. if (this.dumpNextRenderTargets) {
  12815. this.dumpNextRenderTargets = false;
  12816. }
  12817. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12818. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12819. };
  12820. Scene.prototype._updateAudioParameters = function () {
  12821. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  12822. return;
  12823. }
  12824. var listeningCamera;
  12825. var audioEngine = BABYLON.Engine.audioEngine;
  12826. if (this.activeCameras.length > 0) {
  12827. listeningCamera = this.activeCameras[0];
  12828. }
  12829. else {
  12830. listeningCamera = this.activeCamera;
  12831. }
  12832. if (listeningCamera && audioEngine.canUseWebAudio) {
  12833. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12834. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12835. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12836. cameraDirection.normalize();
  12837. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12838. var i;
  12839. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12840. var sound = this.mainSoundTrack.soundCollection[i];
  12841. if (sound.useCustomAttenuation) {
  12842. sound.updateDistanceFromListener();
  12843. }
  12844. }
  12845. for (i = 0; i < this.soundTracks.length; i++) {
  12846. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12847. sound = this.soundTracks[i].soundCollection[j];
  12848. if (sound.useCustomAttenuation) {
  12849. sound.updateDistanceFromListener();
  12850. }
  12851. }
  12852. }
  12853. }
  12854. };
  12855. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12856. // Audio
  12857. get: function () {
  12858. return this._audioEnabled;
  12859. },
  12860. set: function (value) {
  12861. this._audioEnabled = value;
  12862. if (BABYLON.AudioEngine) {
  12863. if (this._audioEnabled) {
  12864. this._enableAudio();
  12865. }
  12866. else {
  12867. this._disableAudio();
  12868. }
  12869. }
  12870. },
  12871. enumerable: true,
  12872. configurable: true
  12873. });
  12874. Scene.prototype._disableAudio = function () {
  12875. var i;
  12876. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12877. this.mainSoundTrack.soundCollection[i].pause();
  12878. }
  12879. for (i = 0; i < this.soundTracks.length; i++) {
  12880. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12881. this.soundTracks[i].soundCollection[j].pause();
  12882. }
  12883. }
  12884. };
  12885. Scene.prototype._enableAudio = function () {
  12886. var i;
  12887. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12888. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12889. this.mainSoundTrack.soundCollection[i].play();
  12890. }
  12891. }
  12892. for (i = 0; i < this.soundTracks.length; i++) {
  12893. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12894. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12895. this.soundTracks[i].soundCollection[j].play();
  12896. }
  12897. }
  12898. }
  12899. };
  12900. Object.defineProperty(Scene.prototype, "headphone", {
  12901. get: function () {
  12902. return this._headphone;
  12903. },
  12904. set: function (value) {
  12905. this._headphone = value;
  12906. if (BABYLON.AudioEngine) {
  12907. if (this._headphone) {
  12908. this._switchAudioModeForHeadphones();
  12909. }
  12910. else {
  12911. this._switchAudioModeForNormalSpeakers();
  12912. }
  12913. }
  12914. },
  12915. enumerable: true,
  12916. configurable: true
  12917. });
  12918. Scene.prototype._switchAudioModeForHeadphones = function () {
  12919. this.mainSoundTrack.switchPanningModelToHRTF();
  12920. for (var i = 0; i < this.soundTracks.length; i++) {
  12921. this.soundTracks[i].switchPanningModelToHRTF();
  12922. }
  12923. };
  12924. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12925. this.mainSoundTrack.switchPanningModelToEqualPower();
  12926. for (var i = 0; i < this.soundTracks.length; i++) {
  12927. this.soundTracks[i].switchPanningModelToEqualPower();
  12928. }
  12929. };
  12930. Scene.prototype.enableDepthRenderer = function () {
  12931. if (this._depthRenderer) {
  12932. return this._depthRenderer;
  12933. }
  12934. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12935. return this._depthRenderer;
  12936. };
  12937. Scene.prototype.disableDepthRenderer = function () {
  12938. if (!this._depthRenderer) {
  12939. return;
  12940. }
  12941. this._depthRenderer.dispose();
  12942. this._depthRenderer = null;
  12943. };
  12944. Scene.prototype.dispose = function () {
  12945. this.beforeRender = null;
  12946. this.afterRender = null;
  12947. this.skeletons = [];
  12948. this._boundingBoxRenderer.dispose();
  12949. if (this._depthRenderer) {
  12950. this._depthRenderer.dispose();
  12951. }
  12952. // Debug layer
  12953. this.debugLayer.hide();
  12954. // Events
  12955. if (this.onDispose) {
  12956. this.onDispose();
  12957. }
  12958. this._onBeforeRenderCallbacks = [];
  12959. this._onAfterRenderCallbacks = [];
  12960. this.detachControl();
  12961. // Release sounds & sounds tracks
  12962. if (BABYLON.AudioEngine) {
  12963. this.disposeSounds();
  12964. }
  12965. // Detach cameras
  12966. var canvas = this._engine.getRenderingCanvas();
  12967. var index;
  12968. for (index = 0; index < this.cameras.length; index++) {
  12969. this.cameras[index].detachControl(canvas);
  12970. }
  12971. // Release lights
  12972. while (this.lights.length) {
  12973. this.lights[0].dispose();
  12974. }
  12975. // Release meshes
  12976. while (this.meshes.length) {
  12977. this.meshes[0].dispose(true);
  12978. }
  12979. // Release cameras
  12980. while (this.cameras.length) {
  12981. this.cameras[0].dispose();
  12982. }
  12983. // Release materials
  12984. while (this.materials.length) {
  12985. this.materials[0].dispose();
  12986. }
  12987. // Release particles
  12988. while (this.particleSystems.length) {
  12989. this.particleSystems[0].dispose();
  12990. }
  12991. // Release sprites
  12992. while (this.spriteManagers.length) {
  12993. this.spriteManagers[0].dispose();
  12994. }
  12995. // Release layers
  12996. while (this.layers.length) {
  12997. this.layers[0].dispose();
  12998. }
  12999. // Release textures
  13000. while (this.textures.length) {
  13001. this.textures[0].dispose();
  13002. }
  13003. // Post-processes
  13004. this.postProcessManager.dispose();
  13005. // Physics
  13006. if (this._physicsEngine) {
  13007. this.disablePhysicsEngine();
  13008. }
  13009. // Remove from engine
  13010. index = this._engine.scenes.indexOf(this);
  13011. if (index > -1) {
  13012. this._engine.scenes.splice(index, 1);
  13013. }
  13014. this._engine.wipeCaches();
  13015. };
  13016. // Release sounds & sounds tracks
  13017. Scene.prototype.disposeSounds = function () {
  13018. this.mainSoundTrack.dispose();
  13019. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13020. this.soundTracks[scIndex].dispose();
  13021. }
  13022. };
  13023. // Octrees
  13024. Scene.prototype.getWorldExtends = function () {
  13025. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13026. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13027. for (var index = 0; index < this.meshes.length; index++) {
  13028. var mesh = this.meshes[index];
  13029. mesh.computeWorldMatrix(true);
  13030. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13031. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13032. BABYLON.Tools.CheckExtends(minBox, min, max);
  13033. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13034. }
  13035. return {
  13036. min: min,
  13037. max: max
  13038. };
  13039. };
  13040. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13041. if (maxCapacity === void 0) { maxCapacity = 64; }
  13042. if (maxDepth === void 0) { maxDepth = 2; }
  13043. if (!this._selectionOctree) {
  13044. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13045. }
  13046. var worldExtends = this.getWorldExtends();
  13047. // Update octree
  13048. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13049. return this._selectionOctree;
  13050. };
  13051. // Picking
  13052. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13053. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13054. var engine = this._engine;
  13055. if (!camera) {
  13056. if (!this.activeCamera)
  13057. throw new Error("Active camera not set");
  13058. camera = this.activeCamera;
  13059. }
  13060. var cameraViewport = camera.viewport;
  13061. var viewport = cameraViewport.toGlobal(engine);
  13062. // Moving coordinates to local viewport world
  13063. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13064. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13065. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13066. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13067. };
  13068. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13069. var engine = this._engine;
  13070. if (!camera) {
  13071. if (!this.activeCamera)
  13072. throw new Error("Active camera not set");
  13073. camera = this.activeCamera;
  13074. }
  13075. var cameraViewport = camera.viewport;
  13076. var viewport = cameraViewport.toGlobal(engine);
  13077. var identity = BABYLON.Matrix.Identity();
  13078. // Moving coordinates to local viewport world
  13079. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13080. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13081. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13082. };
  13083. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13084. var pickingInfo = null;
  13085. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13086. var mesh = this.meshes[meshIndex];
  13087. if (predicate) {
  13088. if (!predicate(mesh)) {
  13089. continue;
  13090. }
  13091. }
  13092. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13093. continue;
  13094. }
  13095. var world = mesh.getWorldMatrix();
  13096. var ray = rayFunction(world);
  13097. var result = mesh.intersects(ray, fastCheck);
  13098. if (!result || !result.hit)
  13099. continue;
  13100. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13101. continue;
  13102. pickingInfo = result;
  13103. if (fastCheck) {
  13104. break;
  13105. }
  13106. }
  13107. return pickingInfo || new BABYLON.PickingInfo();
  13108. };
  13109. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13110. var pickingInfo = null;
  13111. camera = camera || this.activeCamera;
  13112. if (this.spriteManagers.length > 0) {
  13113. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13114. var spriteManager = this.spriteManagers[spriteIndex];
  13115. if (!spriteManager.isPickable) {
  13116. continue;
  13117. }
  13118. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13119. if (!result || !result.hit)
  13120. continue;
  13121. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13122. continue;
  13123. pickingInfo = result;
  13124. if (fastCheck) {
  13125. break;
  13126. }
  13127. }
  13128. }
  13129. return pickingInfo || new BABYLON.PickingInfo();
  13130. };
  13131. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13132. var _this = this;
  13133. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13134. /// <param name="x">X position on screen</param>
  13135. /// <param name="y">Y position on screen</param>
  13136. /// <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>
  13137. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13138. /// <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>
  13139. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13140. };
  13141. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13142. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13143. /// <param name="x">X position on screen</param>
  13144. /// <param name="y">Y position on screen</param>
  13145. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  13146. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13147. /// <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>
  13148. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13149. };
  13150. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13151. var _this = this;
  13152. return this._internalPick(function (world) {
  13153. if (!_this._pickWithRayInverseMatrix) {
  13154. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13155. }
  13156. world.invertToRef(_this._pickWithRayInverseMatrix);
  13157. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13158. }, predicate, fastCheck);
  13159. };
  13160. Scene.prototype.setPointerOverMesh = function (mesh) {
  13161. if (this._pointerOverMesh === mesh) {
  13162. return;
  13163. }
  13164. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13165. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13166. }
  13167. this._pointerOverMesh = mesh;
  13168. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13169. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13170. }
  13171. };
  13172. Scene.prototype.getPointerOverMesh = function () {
  13173. return this._pointerOverMesh;
  13174. };
  13175. // Physics
  13176. Scene.prototype.getPhysicsEngine = function () {
  13177. return this._physicsEngine;
  13178. };
  13179. /**
  13180. * Enables physics to the current scene
  13181. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13182. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13183. * @return {boolean} was the physics engine initialized
  13184. */
  13185. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13186. if (this._physicsEngine) {
  13187. return true;
  13188. }
  13189. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13190. if (!this._physicsEngine.isSupported()) {
  13191. this._physicsEngine = null;
  13192. return false;
  13193. }
  13194. this._physicsEngine._initialize(gravity);
  13195. return true;
  13196. };
  13197. Scene.prototype.disablePhysicsEngine = function () {
  13198. if (!this._physicsEngine) {
  13199. return;
  13200. }
  13201. this._physicsEngine.dispose();
  13202. this._physicsEngine = undefined;
  13203. };
  13204. Scene.prototype.isPhysicsEnabled = function () {
  13205. return this._physicsEngine !== undefined;
  13206. };
  13207. /**
  13208. * Sets the gravity of the physics engine (and NOT of the scene)
  13209. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13210. */
  13211. Scene.prototype.setGravity = function (gravity) {
  13212. if (!this._physicsEngine) {
  13213. return;
  13214. }
  13215. this._physicsEngine._setGravity(gravity);
  13216. };
  13217. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13218. if (parts.parts) {
  13219. options = parts;
  13220. parts = parts.parts;
  13221. }
  13222. if (!this._physicsEngine) {
  13223. return null;
  13224. }
  13225. for (var index = 0; index < parts.length; index++) {
  13226. var mesh = parts[index].mesh;
  13227. mesh._physicImpostor = parts[index].impostor;
  13228. mesh._physicsMass = options.mass / parts.length;
  13229. mesh._physicsFriction = options.friction;
  13230. mesh._physicRestitution = options.restitution;
  13231. }
  13232. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13233. };
  13234. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13235. for (var index = 0; index < compound.parts.length; index++) {
  13236. var mesh = compound.parts[index].mesh;
  13237. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13238. this._physicsEngine._unregisterMesh(mesh);
  13239. }
  13240. };
  13241. // Misc.
  13242. Scene.prototype.createDefaultCameraOrLight = function () {
  13243. // Light
  13244. if (this.lights.length === 0) {
  13245. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13246. }
  13247. // Camera
  13248. if (!this.activeCamera) {
  13249. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13250. // Compute position
  13251. var worldExtends = this.getWorldExtends();
  13252. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13253. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13254. camera.setTarget(worldCenter);
  13255. this.activeCamera = camera;
  13256. }
  13257. };
  13258. // Tags
  13259. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13260. if (tagsQuery === undefined) {
  13261. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13262. return list;
  13263. }
  13264. var listByTags = [];
  13265. forEach = forEach || (function (item) { return; });
  13266. for (var i in list) {
  13267. var item = list[i];
  13268. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13269. listByTags.push(item);
  13270. forEach(item);
  13271. }
  13272. }
  13273. return listByTags;
  13274. };
  13275. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13276. return this._getByTags(this.meshes, tagsQuery, forEach);
  13277. };
  13278. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13279. return this._getByTags(this.cameras, tagsQuery, forEach);
  13280. };
  13281. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13282. return this._getByTags(this.lights, tagsQuery, forEach);
  13283. };
  13284. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13285. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13286. };
  13287. // Statics
  13288. Scene._FOGMODE_NONE = 0;
  13289. Scene._FOGMODE_EXP = 1;
  13290. Scene._FOGMODE_EXP2 = 2;
  13291. Scene._FOGMODE_LINEAR = 3;
  13292. Scene.MinDeltaTime = 1.0;
  13293. Scene.MaxDeltaTime = 1000.0;
  13294. return Scene;
  13295. })();
  13296. BABYLON.Scene = Scene;
  13297. })(BABYLON || (BABYLON = {}));
  13298. var BABYLON;
  13299. (function (BABYLON) {
  13300. var VertexBuffer = (function () {
  13301. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13302. if (engine instanceof BABYLON.Mesh) {
  13303. this._engine = engine.getScene().getEngine();
  13304. }
  13305. else {
  13306. this._engine = engine;
  13307. }
  13308. this._updatable = updatable;
  13309. this._data = data;
  13310. if (!postponeInternalCreation) {
  13311. this.create();
  13312. }
  13313. this._kind = kind;
  13314. if (stride) {
  13315. this._strideSize = stride;
  13316. return;
  13317. }
  13318. // Deduce stride from kind
  13319. switch (kind) {
  13320. case VertexBuffer.PositionKind:
  13321. this._strideSize = 3;
  13322. break;
  13323. case VertexBuffer.NormalKind:
  13324. this._strideSize = 3;
  13325. break;
  13326. case VertexBuffer.UVKind:
  13327. case VertexBuffer.UV2Kind:
  13328. case VertexBuffer.UV3Kind:
  13329. case VertexBuffer.UV4Kind:
  13330. case VertexBuffer.UV5Kind:
  13331. case VertexBuffer.UV6Kind:
  13332. this._strideSize = 2;
  13333. break;
  13334. case VertexBuffer.ColorKind:
  13335. this._strideSize = 4;
  13336. break;
  13337. case VertexBuffer.MatricesIndicesKind:
  13338. this._strideSize = 4;
  13339. break;
  13340. case VertexBuffer.MatricesWeightsKind:
  13341. this._strideSize = 4;
  13342. break;
  13343. }
  13344. }
  13345. // Properties
  13346. VertexBuffer.prototype.isUpdatable = function () {
  13347. return this._updatable;
  13348. };
  13349. VertexBuffer.prototype.getData = function () {
  13350. return this._data;
  13351. };
  13352. VertexBuffer.prototype.getBuffer = function () {
  13353. return this._buffer;
  13354. };
  13355. VertexBuffer.prototype.getStrideSize = function () {
  13356. return this._strideSize;
  13357. };
  13358. // Methods
  13359. VertexBuffer.prototype.create = function (data) {
  13360. if (!data && this._buffer) {
  13361. return; // nothing to do
  13362. }
  13363. data = data || this._data;
  13364. if (!this._buffer) {
  13365. if (this._updatable) {
  13366. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13367. }
  13368. else {
  13369. this._buffer = this._engine.createVertexBuffer(data);
  13370. }
  13371. }
  13372. if (this._updatable) {
  13373. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13374. this._data = data;
  13375. }
  13376. };
  13377. VertexBuffer.prototype.update = function (data) {
  13378. this.create(data);
  13379. };
  13380. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13381. if (!this._buffer) {
  13382. return;
  13383. }
  13384. if (this._updatable) {
  13385. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13386. this._data = null;
  13387. }
  13388. };
  13389. VertexBuffer.prototype.dispose = function () {
  13390. if (!this._buffer) {
  13391. return;
  13392. }
  13393. if (this._engine._releaseBuffer(this._buffer)) {
  13394. this._buffer = null;
  13395. }
  13396. };
  13397. Object.defineProperty(VertexBuffer, "PositionKind", {
  13398. get: function () {
  13399. return VertexBuffer._PositionKind;
  13400. },
  13401. enumerable: true,
  13402. configurable: true
  13403. });
  13404. Object.defineProperty(VertexBuffer, "NormalKind", {
  13405. get: function () {
  13406. return VertexBuffer._NormalKind;
  13407. },
  13408. enumerable: true,
  13409. configurable: true
  13410. });
  13411. Object.defineProperty(VertexBuffer, "UVKind", {
  13412. get: function () {
  13413. return VertexBuffer._UVKind;
  13414. },
  13415. enumerable: true,
  13416. configurable: true
  13417. });
  13418. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13419. get: function () {
  13420. return VertexBuffer._UV2Kind;
  13421. },
  13422. enumerable: true,
  13423. configurable: true
  13424. });
  13425. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13426. get: function () {
  13427. return VertexBuffer._UV3Kind;
  13428. },
  13429. enumerable: true,
  13430. configurable: true
  13431. });
  13432. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13433. get: function () {
  13434. return VertexBuffer._UV4Kind;
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13440. get: function () {
  13441. return VertexBuffer._UV5Kind;
  13442. },
  13443. enumerable: true,
  13444. configurable: true
  13445. });
  13446. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13447. get: function () {
  13448. return VertexBuffer._UV6Kind;
  13449. },
  13450. enumerable: true,
  13451. configurable: true
  13452. });
  13453. Object.defineProperty(VertexBuffer, "ColorKind", {
  13454. get: function () {
  13455. return VertexBuffer._ColorKind;
  13456. },
  13457. enumerable: true,
  13458. configurable: true
  13459. });
  13460. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13461. get: function () {
  13462. return VertexBuffer._MatricesIndicesKind;
  13463. },
  13464. enumerable: true,
  13465. configurable: true
  13466. });
  13467. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13468. get: function () {
  13469. return VertexBuffer._MatricesWeightsKind;
  13470. },
  13471. enumerable: true,
  13472. configurable: true
  13473. });
  13474. // Enums
  13475. VertexBuffer._PositionKind = "position";
  13476. VertexBuffer._NormalKind = "normal";
  13477. VertexBuffer._UVKind = "uv";
  13478. VertexBuffer._UV2Kind = "uv2";
  13479. VertexBuffer._UV3Kind = "uv3";
  13480. VertexBuffer._UV4Kind = "uv4";
  13481. VertexBuffer._UV5Kind = "uv5";
  13482. VertexBuffer._UV6Kind = "uv6";
  13483. VertexBuffer._ColorKind = "color";
  13484. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13485. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13486. return VertexBuffer;
  13487. })();
  13488. BABYLON.VertexBuffer = VertexBuffer;
  13489. })(BABYLON || (BABYLON = {}));
  13490. var BABYLON;
  13491. (function (BABYLON) {
  13492. /**
  13493. * Creates an instance based on a source mesh.
  13494. */
  13495. var InstancedMesh = (function (_super) {
  13496. __extends(InstancedMesh, _super);
  13497. function InstancedMesh(name, source) {
  13498. _super.call(this, name, source.getScene());
  13499. source.instances.push(this);
  13500. this._sourceMesh = source;
  13501. this.position.copyFrom(source.position);
  13502. this.rotation.copyFrom(source.rotation);
  13503. this.scaling.copyFrom(source.scaling);
  13504. if (source.rotationQuaternion) {
  13505. this.rotationQuaternion = source.rotationQuaternion.clone();
  13506. }
  13507. this.infiniteDistance = source.infiniteDistance;
  13508. this.setPivotMatrix(source.getPivotMatrix());
  13509. this.refreshBoundingInfo();
  13510. this._syncSubMeshes();
  13511. }
  13512. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13513. // Methods
  13514. get: function () {
  13515. return this._sourceMesh.receiveShadows;
  13516. },
  13517. enumerable: true,
  13518. configurable: true
  13519. });
  13520. Object.defineProperty(InstancedMesh.prototype, "material", {
  13521. get: function () {
  13522. return this._sourceMesh.material;
  13523. },
  13524. enumerable: true,
  13525. configurable: true
  13526. });
  13527. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13528. get: function () {
  13529. return this._sourceMesh.visibility;
  13530. },
  13531. enumerable: true,
  13532. configurable: true
  13533. });
  13534. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13535. get: function () {
  13536. return this._sourceMesh.skeleton;
  13537. },
  13538. enumerable: true,
  13539. configurable: true
  13540. });
  13541. InstancedMesh.prototype.getTotalVertices = function () {
  13542. return this._sourceMesh.getTotalVertices();
  13543. };
  13544. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13545. get: function () {
  13546. return this._sourceMesh;
  13547. },
  13548. enumerable: true,
  13549. configurable: true
  13550. });
  13551. InstancedMesh.prototype.getVerticesData = function (kind) {
  13552. return this._sourceMesh.getVerticesData(kind);
  13553. };
  13554. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13555. return this._sourceMesh.isVerticesDataPresent(kind);
  13556. };
  13557. InstancedMesh.prototype.getIndices = function () {
  13558. return this._sourceMesh.getIndices();
  13559. };
  13560. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13561. get: function () {
  13562. return this._sourceMesh._positions;
  13563. },
  13564. enumerable: true,
  13565. configurable: true
  13566. });
  13567. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13568. var meshBB = this._sourceMesh.getBoundingInfo();
  13569. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum, meshBB.maximum);
  13570. this._updateBoundingInfo();
  13571. };
  13572. InstancedMesh.prototype._preActivate = function () {
  13573. if (this._currentLOD) {
  13574. this._currentLOD._preActivate();
  13575. }
  13576. };
  13577. InstancedMesh.prototype._activate = function (renderId) {
  13578. if (this._currentLOD) {
  13579. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13580. }
  13581. };
  13582. InstancedMesh.prototype.getLOD = function (camera) {
  13583. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13584. if (this._currentLOD === this.sourceMesh) {
  13585. return this;
  13586. }
  13587. return this._currentLOD;
  13588. };
  13589. InstancedMesh.prototype._syncSubMeshes = function () {
  13590. this.releaseSubMeshes();
  13591. if (this._sourceMesh.subMeshes) {
  13592. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13593. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13594. }
  13595. }
  13596. };
  13597. InstancedMesh.prototype._generatePointsArray = function () {
  13598. return this._sourceMesh._generatePointsArray();
  13599. };
  13600. // Clone
  13601. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13602. var result = this._sourceMesh.createInstance(name);
  13603. // Deep copy
  13604. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13605. // Bounding info
  13606. this.refreshBoundingInfo();
  13607. // Parent
  13608. if (newParent) {
  13609. result.parent = newParent;
  13610. }
  13611. if (!doNotCloneChildren) {
  13612. // Children
  13613. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13614. var mesh = this.getScene().meshes[index];
  13615. if (mesh.parent === this) {
  13616. mesh.clone(mesh.name, result);
  13617. }
  13618. }
  13619. }
  13620. result.computeWorldMatrix(true);
  13621. return result;
  13622. };
  13623. // Dispoe
  13624. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13625. // Remove from mesh
  13626. var index = this._sourceMesh.instances.indexOf(this);
  13627. this._sourceMesh.instances.splice(index, 1);
  13628. _super.prototype.dispose.call(this, doNotRecurse);
  13629. };
  13630. return InstancedMesh;
  13631. })(BABYLON.AbstractMesh);
  13632. BABYLON.InstancedMesh = InstancedMesh;
  13633. })(BABYLON || (BABYLON = {}));
  13634. var BABYLON;
  13635. (function (BABYLON) {
  13636. var _InstancesBatch = (function () {
  13637. function _InstancesBatch() {
  13638. this.mustReturn = false;
  13639. this.visibleInstances = new Array();
  13640. this.renderSelf = new Array();
  13641. }
  13642. return _InstancesBatch;
  13643. })();
  13644. BABYLON._InstancesBatch = _InstancesBatch;
  13645. var Mesh = (function (_super) {
  13646. __extends(Mesh, _super);
  13647. /**
  13648. * @constructor
  13649. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13650. * @param {Scene} scene - The scene to add this mesh to.
  13651. * @param {Node} parent - The parent of this mesh, if it has one
  13652. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13653. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13654. * When false, achieved by calling a clone(), also passing False.
  13655. * This will make creation of children, recursive.
  13656. */
  13657. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13658. if (parent === void 0) { parent = null; }
  13659. _super.call(this, name, scene);
  13660. // Members
  13661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13662. this.instances = new Array();
  13663. this._LODLevels = new Array();
  13664. this._onBeforeRenderCallbacks = new Array();
  13665. this._onAfterRenderCallbacks = new Array();
  13666. this._visibleInstances = {};
  13667. this._renderIdForInstances = new Array();
  13668. this._batchCache = new _InstancesBatch();
  13669. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13670. this._sideOrientation = Mesh._DEFAULTSIDE;
  13671. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13672. if (source) {
  13673. // Geometry
  13674. if (source._geometry) {
  13675. source._geometry.applyToMesh(this);
  13676. }
  13677. // Deep copy
  13678. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13679. this.id = name + "." + source.id;
  13680. // Material
  13681. this.material = source.material;
  13682. var index;
  13683. if (!doNotCloneChildren) {
  13684. // Children
  13685. for (index = 0; index < scene.meshes.length; index++) {
  13686. var mesh = scene.meshes[index];
  13687. if (mesh.parent === source) {
  13688. // doNotCloneChildren is always going to be False
  13689. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13690. }
  13691. }
  13692. }
  13693. // Particles
  13694. for (index = 0; index < scene.particleSystems.length; index++) {
  13695. var system = scene.particleSystems[index];
  13696. if (system.emitter === source) {
  13697. system.clone(system.name, this);
  13698. }
  13699. }
  13700. this.computeWorldMatrix(true);
  13701. }
  13702. // Parent
  13703. if (parent !== null) {
  13704. this.parent = parent;
  13705. }
  13706. }
  13707. Object.defineProperty(Mesh, "FRONTSIDE", {
  13708. get: function () {
  13709. return Mesh._FRONTSIDE;
  13710. },
  13711. enumerable: true,
  13712. configurable: true
  13713. });
  13714. Object.defineProperty(Mesh, "BACKSIDE", {
  13715. get: function () {
  13716. return Mesh._BACKSIDE;
  13717. },
  13718. enumerable: true,
  13719. configurable: true
  13720. });
  13721. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13722. get: function () {
  13723. return Mesh._DOUBLESIDE;
  13724. },
  13725. enumerable: true,
  13726. configurable: true
  13727. });
  13728. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13729. get: function () {
  13730. return Mesh._DEFAULTSIDE;
  13731. },
  13732. enumerable: true,
  13733. configurable: true
  13734. });
  13735. Object.defineProperty(Mesh, "NO_CAP", {
  13736. get: function () {
  13737. return Mesh._NO_CAP;
  13738. },
  13739. enumerable: true,
  13740. configurable: true
  13741. });
  13742. Object.defineProperty(Mesh, "CAP_START", {
  13743. get: function () {
  13744. return Mesh._CAP_START;
  13745. },
  13746. enumerable: true,
  13747. configurable: true
  13748. });
  13749. Object.defineProperty(Mesh, "CAP_END", {
  13750. get: function () {
  13751. return Mesh._CAP_END;
  13752. },
  13753. enumerable: true,
  13754. configurable: true
  13755. });
  13756. Object.defineProperty(Mesh, "CAP_ALL", {
  13757. get: function () {
  13758. return Mesh._CAP_ALL;
  13759. },
  13760. enumerable: true,
  13761. configurable: true
  13762. });
  13763. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13764. // Methods
  13765. get: function () {
  13766. return this._LODLevels.length > 0;
  13767. },
  13768. enumerable: true,
  13769. configurable: true
  13770. });
  13771. Mesh.prototype._sortLODLevels = function () {
  13772. this._LODLevels.sort(function (a, b) {
  13773. if (a.distance < b.distance) {
  13774. return 1;
  13775. }
  13776. if (a.distance > b.distance) {
  13777. return -1;
  13778. }
  13779. return 0;
  13780. });
  13781. };
  13782. /**
  13783. * Add a mesh as LOD level triggered at the given distance.
  13784. * @param {number} distance - the distance from the center of the object to show this level
  13785. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13786. * @return {BABYLON.Mesh} this mesh (for chaining)
  13787. */
  13788. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13789. if (mesh && mesh._masterMesh) {
  13790. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13791. return this;
  13792. }
  13793. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13794. this._LODLevels.push(level);
  13795. if (mesh) {
  13796. mesh._masterMesh = this;
  13797. }
  13798. this._sortLODLevels();
  13799. return this;
  13800. };
  13801. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13802. for (var index = 0; index < this._LODLevels.length; index++) {
  13803. var level = this._LODLevels[index];
  13804. if (level.distance === distance) {
  13805. return level.mesh;
  13806. }
  13807. }
  13808. return null;
  13809. };
  13810. /**
  13811. * Remove a mesh from the LOD array
  13812. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13813. * @return {BABYLON.Mesh} this mesh (for chaining)
  13814. */
  13815. Mesh.prototype.removeLODLevel = function (mesh) {
  13816. for (var index = 0; index < this._LODLevels.length; index++) {
  13817. if (this._LODLevels[index].mesh === mesh) {
  13818. this._LODLevels.splice(index, 1);
  13819. if (mesh) {
  13820. mesh._masterMesh = null;
  13821. }
  13822. }
  13823. }
  13824. this._sortLODLevels();
  13825. return this;
  13826. };
  13827. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13828. if (!this._LODLevels || this._LODLevels.length === 0) {
  13829. return this;
  13830. }
  13831. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13832. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13833. if (this.onLODLevelSelection) {
  13834. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13835. }
  13836. return this;
  13837. }
  13838. for (var index = 0; index < this._LODLevels.length; index++) {
  13839. var level = this._LODLevels[index];
  13840. if (level.distance < distanceToCamera) {
  13841. if (level.mesh) {
  13842. level.mesh._preActivate();
  13843. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13844. }
  13845. if (this.onLODLevelSelection) {
  13846. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13847. }
  13848. return level.mesh;
  13849. }
  13850. }
  13851. if (this.onLODLevelSelection) {
  13852. this.onLODLevelSelection(distanceToCamera, this, this);
  13853. }
  13854. return this;
  13855. };
  13856. Object.defineProperty(Mesh.prototype, "geometry", {
  13857. get: function () {
  13858. return this._geometry;
  13859. },
  13860. enumerable: true,
  13861. configurable: true
  13862. });
  13863. Mesh.prototype.getTotalVertices = function () {
  13864. if (!this._geometry) {
  13865. return 0;
  13866. }
  13867. return this._geometry.getTotalVertices();
  13868. };
  13869. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13870. if (!this._geometry) {
  13871. return null;
  13872. }
  13873. return this._geometry.getVerticesData(kind, copyWhenShared);
  13874. };
  13875. Mesh.prototype.getVertexBuffer = function (kind) {
  13876. if (!this._geometry) {
  13877. return undefined;
  13878. }
  13879. return this._geometry.getVertexBuffer(kind);
  13880. };
  13881. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13882. if (!this._geometry) {
  13883. if (this._delayInfo) {
  13884. return this._delayInfo.indexOf(kind) !== -1;
  13885. }
  13886. return false;
  13887. }
  13888. return this._geometry.isVerticesDataPresent(kind);
  13889. };
  13890. Mesh.prototype.getVerticesDataKinds = function () {
  13891. if (!this._geometry) {
  13892. var result = [];
  13893. if (this._delayInfo) {
  13894. for (var kind in this._delayInfo) {
  13895. result.push(kind);
  13896. }
  13897. }
  13898. return result;
  13899. }
  13900. return this._geometry.getVerticesDataKinds();
  13901. };
  13902. Mesh.prototype.getTotalIndices = function () {
  13903. if (!this._geometry) {
  13904. return 0;
  13905. }
  13906. return this._geometry.getTotalIndices();
  13907. };
  13908. Mesh.prototype.getIndices = function (copyWhenShared) {
  13909. if (!this._geometry) {
  13910. return [];
  13911. }
  13912. return this._geometry.getIndices(copyWhenShared);
  13913. };
  13914. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13915. get: function () {
  13916. return this._masterMesh !== null && this._masterMesh !== undefined;
  13917. },
  13918. enumerable: true,
  13919. configurable: true
  13920. });
  13921. Mesh.prototype.isReady = function () {
  13922. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13923. return false;
  13924. }
  13925. return _super.prototype.isReady.call(this);
  13926. };
  13927. Mesh.prototype.isDisposed = function () {
  13928. return this._isDisposed;
  13929. };
  13930. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13931. get: function () {
  13932. return this._sideOrientation;
  13933. },
  13934. set: function (sideO) {
  13935. this._sideOrientation = sideO;
  13936. },
  13937. enumerable: true,
  13938. configurable: true
  13939. });
  13940. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13941. get: function () {
  13942. return this._areNormalsFrozen;
  13943. },
  13944. enumerable: true,
  13945. configurable: true
  13946. });
  13947. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13948. Mesh.prototype.freezeNormals = function () {
  13949. this._areNormalsFrozen = true;
  13950. };
  13951. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13952. Mesh.prototype.unfreezeNormals = function () {
  13953. this._areNormalsFrozen = false;
  13954. };
  13955. // Methods
  13956. Mesh.prototype._preActivate = function () {
  13957. var sceneRenderId = this.getScene().getRenderId();
  13958. if (this._preActivateId === sceneRenderId) {
  13959. return;
  13960. }
  13961. this._preActivateId = sceneRenderId;
  13962. this._visibleInstances = null;
  13963. };
  13964. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13965. if (!this._visibleInstances) {
  13966. this._visibleInstances = {};
  13967. this._visibleInstances.defaultRenderId = renderId;
  13968. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13969. }
  13970. if (!this._visibleInstances[renderId]) {
  13971. this._visibleInstances[renderId] = new Array();
  13972. }
  13973. this._visibleInstances[renderId].push(instance);
  13974. };
  13975. Mesh.prototype.refreshBoundingInfo = function () {
  13976. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13977. if (data) {
  13978. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13979. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13980. }
  13981. if (this.subMeshes) {
  13982. for (var index = 0; index < this.subMeshes.length; index++) {
  13983. this.subMeshes[index].refreshBoundingInfo();
  13984. }
  13985. }
  13986. this._updateBoundingInfo();
  13987. };
  13988. Mesh.prototype._createGlobalSubMesh = function () {
  13989. var totalVertices = this.getTotalVertices();
  13990. if (!totalVertices || !this.getIndices()) {
  13991. return null;
  13992. }
  13993. this.releaseSubMeshes();
  13994. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13995. };
  13996. Mesh.prototype.subdivide = function (count) {
  13997. if (count < 1) {
  13998. return;
  13999. }
  14000. var totalIndices = this.getTotalIndices();
  14001. var subdivisionSize = (totalIndices / count) | 0;
  14002. var offset = 0;
  14003. // Ensure that subdivisionSize is a multiple of 3
  14004. while (subdivisionSize % 3 !== 0) {
  14005. subdivisionSize++;
  14006. }
  14007. this.releaseSubMeshes();
  14008. for (var index = 0; index < count; index++) {
  14009. if (offset >= totalIndices) {
  14010. break;
  14011. }
  14012. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14013. offset += subdivisionSize;
  14014. }
  14015. this.synchronizeInstances();
  14016. };
  14017. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14018. if (!this._geometry) {
  14019. var vertexData = new BABYLON.VertexData();
  14020. vertexData.set(data, kind);
  14021. var scene = this.getScene();
  14022. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14023. }
  14024. else {
  14025. this._geometry.setVerticesData(kind, data, updatable, stride);
  14026. }
  14027. };
  14028. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14029. if (!this._geometry) {
  14030. return;
  14031. }
  14032. if (!makeItUnique) {
  14033. this._geometry.updateVerticesData(kind, data, updateExtends);
  14034. }
  14035. else {
  14036. this.makeGeometryUnique();
  14037. this.updateVerticesData(kind, data, updateExtends, false);
  14038. }
  14039. };
  14040. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14041. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14042. if (!this._geometry) {
  14043. return;
  14044. }
  14045. if (!makeItUnique) {
  14046. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14047. }
  14048. else {
  14049. this.makeGeometryUnique();
  14050. this.updateVerticesDataDirectly(kind, data, offset, false);
  14051. }
  14052. };
  14053. // Mesh positions update function :
  14054. // updates the mesh positions according to the positionFunction returned values.
  14055. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14056. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14057. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14058. if (computeNormals === void 0) { computeNormals = true; }
  14059. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14060. positionFunction(positions);
  14061. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14062. if (computeNormals) {
  14063. var indices = this.getIndices();
  14064. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14065. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14066. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14067. }
  14068. };
  14069. Mesh.prototype.makeGeometryUnique = function () {
  14070. if (!this._geometry) {
  14071. return;
  14072. }
  14073. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14074. geometry.applyToMesh(this);
  14075. };
  14076. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14077. if (!this._geometry) {
  14078. var vertexData = new BABYLON.VertexData();
  14079. vertexData.indices = indices;
  14080. var scene = this.getScene();
  14081. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14082. }
  14083. else {
  14084. this._geometry.setIndices(indices, totalVertices);
  14085. }
  14086. };
  14087. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14088. var engine = this.getScene().getEngine();
  14089. // Wireframe
  14090. var indexToBind;
  14091. switch (fillMode) {
  14092. case BABYLON.Material.PointFillMode:
  14093. indexToBind = null;
  14094. break;
  14095. case BABYLON.Material.WireFrameFillMode:
  14096. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14097. break;
  14098. default:
  14099. case BABYLON.Material.TriangleFillMode:
  14100. indexToBind = this._geometry.getIndexBuffer();
  14101. break;
  14102. }
  14103. // VBOs
  14104. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14105. };
  14106. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14107. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14108. return;
  14109. }
  14110. var engine = this.getScene().getEngine();
  14111. // Draw order
  14112. switch (fillMode) {
  14113. case BABYLON.Material.PointFillMode:
  14114. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14115. break;
  14116. case BABYLON.Material.WireFrameFillMode:
  14117. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14118. break;
  14119. default:
  14120. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14121. }
  14122. };
  14123. Mesh.prototype.registerBeforeRender = function (func) {
  14124. this._onBeforeRenderCallbacks.push(func);
  14125. };
  14126. Mesh.prototype.unregisterBeforeRender = function (func) {
  14127. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14128. if (index > -1) {
  14129. this._onBeforeRenderCallbacks.splice(index, 1);
  14130. }
  14131. };
  14132. Mesh.prototype.registerAfterRender = function (func) {
  14133. this._onAfterRenderCallbacks.push(func);
  14134. };
  14135. Mesh.prototype.unregisterAfterRender = function (func) {
  14136. var index = this._onAfterRenderCallbacks.indexOf(func);
  14137. if (index > -1) {
  14138. this._onAfterRenderCallbacks.splice(index, 1);
  14139. }
  14140. };
  14141. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14142. var scene = this.getScene();
  14143. this._batchCache.mustReturn = false;
  14144. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14145. this._batchCache.visibleInstances[subMeshId] = null;
  14146. if (this._visibleInstances) {
  14147. var currentRenderId = scene.getRenderId();
  14148. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14149. var selfRenderId = this._renderId;
  14150. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14151. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14152. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14153. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14154. }
  14155. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14156. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14157. this._batchCache.mustReturn = true;
  14158. return this._batchCache;
  14159. }
  14160. if (currentRenderId !== selfRenderId) {
  14161. this._batchCache.renderSelf[subMeshId] = false;
  14162. }
  14163. }
  14164. this._renderIdForInstances[subMeshId] = currentRenderId;
  14165. }
  14166. return this._batchCache;
  14167. };
  14168. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14169. var visibleInstances = batch.visibleInstances[subMesh._id];
  14170. var matricesCount = visibleInstances.length + 1;
  14171. var bufferSize = matricesCount * 16 * 4;
  14172. while (this._instancesBufferSize < bufferSize) {
  14173. this._instancesBufferSize *= 2;
  14174. }
  14175. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14176. if (this._worldMatricesInstancesBuffer) {
  14177. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14178. }
  14179. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14180. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14181. }
  14182. var offset = 0;
  14183. var instancesCount = 0;
  14184. var world = this.getWorldMatrix();
  14185. if (batch.renderSelf[subMesh._id]) {
  14186. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14187. offset += 16;
  14188. instancesCount++;
  14189. }
  14190. if (visibleInstances) {
  14191. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14192. var instance = visibleInstances[instanceIndex];
  14193. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14194. offset += 16;
  14195. instancesCount++;
  14196. }
  14197. }
  14198. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14199. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14200. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14201. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14202. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14203. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14204. this._draw(subMesh, fillMode, instancesCount);
  14205. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14206. };
  14207. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14208. var scene = this.getScene();
  14209. var engine = scene.getEngine();
  14210. if (hardwareInstancedRendering) {
  14211. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14212. }
  14213. else {
  14214. if (batch.renderSelf[subMesh._id]) {
  14215. // Draw
  14216. if (onBeforeDraw) {
  14217. onBeforeDraw(false, this.getWorldMatrix());
  14218. }
  14219. this._draw(subMesh, fillMode);
  14220. }
  14221. if (batch.visibleInstances[subMesh._id]) {
  14222. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14223. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14224. // World
  14225. var world = instance.getWorldMatrix();
  14226. if (onBeforeDraw) {
  14227. onBeforeDraw(true, world);
  14228. }
  14229. // Draw
  14230. this._draw(subMesh, fillMode);
  14231. }
  14232. }
  14233. }
  14234. };
  14235. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14236. var scene = this.getScene();
  14237. // Managing instances
  14238. var batch = this._getInstancesRenderList(subMesh._id);
  14239. if (batch.mustReturn) {
  14240. return;
  14241. }
  14242. // Checking geometry state
  14243. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14244. return;
  14245. }
  14246. var callbackIndex;
  14247. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14248. this._onBeforeRenderCallbacks[callbackIndex](this);
  14249. }
  14250. var engine = scene.getEngine();
  14251. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14252. // Material
  14253. var effectiveMaterial = subMesh.getMaterial();
  14254. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14255. return;
  14256. }
  14257. // Outline - step 1
  14258. var savedDepthWrite = engine.getDepthWrite();
  14259. if (this.renderOutline) {
  14260. engine.setDepthWrite(false);
  14261. scene.getOutlineRenderer().render(subMesh, batch);
  14262. engine.setDepthWrite(savedDepthWrite);
  14263. }
  14264. effectiveMaterial._preBind();
  14265. var effect = effectiveMaterial.getEffect();
  14266. // Bind
  14267. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14268. this._bind(subMesh, effect, fillMode);
  14269. var world = this.getWorldMatrix();
  14270. effectiveMaterial.bind(world, this);
  14271. // Alpha mode
  14272. if (enableAlphaMode) {
  14273. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14274. }
  14275. // Draw
  14276. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14277. if (isInstance) {
  14278. effectiveMaterial.bindOnlyWorldMatrix(world);
  14279. }
  14280. });
  14281. // Unbind
  14282. effectiveMaterial.unbind();
  14283. // Outline - step 2
  14284. if (this.renderOutline && savedDepthWrite) {
  14285. engine.setDepthWrite(true);
  14286. engine.setColorWrite(false);
  14287. scene.getOutlineRenderer().render(subMesh, batch);
  14288. engine.setColorWrite(true);
  14289. }
  14290. // Overlay
  14291. if (this.renderOverlay) {
  14292. var currentMode = engine.getAlphaMode();
  14293. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14294. scene.getOutlineRenderer().render(subMesh, batch, true);
  14295. engine.setAlphaMode(currentMode);
  14296. }
  14297. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14298. this._onAfterRenderCallbacks[callbackIndex](this);
  14299. }
  14300. };
  14301. Mesh.prototype.getEmittedParticleSystems = function () {
  14302. var results = new Array();
  14303. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14304. var particleSystem = this.getScene().particleSystems[index];
  14305. if (particleSystem.emitter === this) {
  14306. results.push(particleSystem);
  14307. }
  14308. }
  14309. return results;
  14310. };
  14311. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14312. var results = new Array();
  14313. var descendants = this.getDescendants();
  14314. descendants.push(this);
  14315. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14316. var particleSystem = this.getScene().particleSystems[index];
  14317. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14318. results.push(particleSystem);
  14319. }
  14320. }
  14321. return results;
  14322. };
  14323. Mesh.prototype.getChildren = function () {
  14324. var results = [];
  14325. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14326. var mesh = this.getScene().meshes[index];
  14327. if (mesh.parent === this) {
  14328. results.push(mesh);
  14329. }
  14330. }
  14331. return results;
  14332. };
  14333. Mesh.prototype._checkDelayState = function () {
  14334. var _this = this;
  14335. var that = this;
  14336. var scene = this.getScene();
  14337. if (this._geometry) {
  14338. this._geometry.load(scene);
  14339. }
  14340. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14341. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14342. scene._addPendingData(that);
  14343. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14344. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14345. if (data instanceof ArrayBuffer) {
  14346. _this._delayLoadingFunction(data, _this);
  14347. }
  14348. else {
  14349. _this._delayLoadingFunction(JSON.parse(data), _this);
  14350. }
  14351. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14352. scene._removePendingData(_this);
  14353. }, function () { }, scene.database, getBinaryData);
  14354. }
  14355. };
  14356. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14357. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14358. return false;
  14359. }
  14360. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14361. return false;
  14362. }
  14363. this._checkDelayState();
  14364. return true;
  14365. };
  14366. Mesh.prototype.setMaterialByID = function (id) {
  14367. var materials = this.getScene().materials;
  14368. var index;
  14369. for (index = 0; index < materials.length; index++) {
  14370. if (materials[index].id === id) {
  14371. this.material = materials[index];
  14372. return;
  14373. }
  14374. }
  14375. // Multi
  14376. var multiMaterials = this.getScene().multiMaterials;
  14377. for (index = 0; index < multiMaterials.length; index++) {
  14378. if (multiMaterials[index].id === id) {
  14379. this.material = multiMaterials[index];
  14380. return;
  14381. }
  14382. }
  14383. };
  14384. Mesh.prototype.getAnimatables = function () {
  14385. var results = [];
  14386. if (this.material) {
  14387. results.push(this.material);
  14388. }
  14389. if (this.skeleton) {
  14390. results.push(this.skeleton);
  14391. }
  14392. return results;
  14393. };
  14394. // Geometry
  14395. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14396. // Position
  14397. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14398. return;
  14399. }
  14400. this._resetPointsArrayCache();
  14401. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14402. var temp = [];
  14403. var index;
  14404. for (index = 0; index < data.length; index += 3) {
  14405. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14406. }
  14407. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14408. // Normals
  14409. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14410. return;
  14411. }
  14412. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14413. temp = [];
  14414. for (index = 0; index < data.length; index += 3) {
  14415. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14416. }
  14417. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14418. // flip faces?
  14419. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14420. this.flipFaces();
  14421. }
  14422. };
  14423. // Will apply current transform to mesh and reset world matrix
  14424. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14425. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14426. this.scaling.copyFromFloats(1, 1, 1);
  14427. this.position.copyFromFloats(0, 0, 0);
  14428. this.rotation.copyFromFloats(0, 0, 0);
  14429. //only if quaternion is already set
  14430. if (this.rotationQuaternion) {
  14431. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14432. }
  14433. this._worldMatrix = BABYLON.Matrix.Identity();
  14434. };
  14435. // Cache
  14436. Mesh.prototype._resetPointsArrayCache = function () {
  14437. this._positions = null;
  14438. };
  14439. Mesh.prototype._generatePointsArray = function () {
  14440. if (this._positions)
  14441. return true;
  14442. this._positions = [];
  14443. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14444. if (!data) {
  14445. return false;
  14446. }
  14447. for (var index = 0; index < data.length; index += 3) {
  14448. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14449. }
  14450. return true;
  14451. };
  14452. // Clone
  14453. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14454. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14455. };
  14456. // Dispose
  14457. Mesh.prototype.dispose = function (doNotRecurse) {
  14458. if (this._geometry) {
  14459. this._geometry.releaseForMesh(this, true);
  14460. }
  14461. // Instances
  14462. if (this._worldMatricesInstancesBuffer) {
  14463. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14464. this._worldMatricesInstancesBuffer = null;
  14465. }
  14466. while (this.instances.length) {
  14467. this.instances[0].dispose();
  14468. }
  14469. _super.prototype.dispose.call(this, doNotRecurse);
  14470. };
  14471. // Geometric tools
  14472. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14473. var _this = this;
  14474. var scene = this.getScene();
  14475. var onload = function (img) {
  14476. // Getting height map data
  14477. var canvas = document.createElement("canvas");
  14478. var context = canvas.getContext("2d");
  14479. var heightMapWidth = img.width;
  14480. var heightMapHeight = img.height;
  14481. canvas.width = heightMapWidth;
  14482. canvas.height = heightMapHeight;
  14483. context.drawImage(img, 0, 0);
  14484. // Create VertexData from map data
  14485. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14486. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14487. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14488. //execute success callback, if set
  14489. if (onSuccess) {
  14490. onSuccess(_this);
  14491. }
  14492. };
  14493. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14494. };
  14495. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14496. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14497. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14498. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14499. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14500. return;
  14501. }
  14502. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14503. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14504. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14505. var position = BABYLON.Vector3.Zero();
  14506. var normal = BABYLON.Vector3.Zero();
  14507. var uv = BABYLON.Vector2.Zero();
  14508. for (var index = 0; index < positions.length; index += 3) {
  14509. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14510. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14511. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14512. // Compute height
  14513. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14514. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14515. var pos = (u + v * heightMapWidth) * 4;
  14516. var r = buffer[pos] / 255.0;
  14517. var g = buffer[pos + 1] / 255.0;
  14518. var b = buffer[pos + 2] / 255.0;
  14519. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14520. normal.normalize();
  14521. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14522. position = position.add(normal);
  14523. position.toArray(positions, index);
  14524. }
  14525. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14526. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14527. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14528. };
  14529. Mesh.prototype.convertToFlatShadedMesh = function () {
  14530. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14531. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14532. var kinds = this.getVerticesDataKinds();
  14533. var vbs = [];
  14534. var data = [];
  14535. var newdata = [];
  14536. var updatableNormals = false;
  14537. var kindIndex;
  14538. var kind;
  14539. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14540. kind = kinds[kindIndex];
  14541. var vertexBuffer = this.getVertexBuffer(kind);
  14542. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14543. updatableNormals = vertexBuffer.isUpdatable();
  14544. kinds.splice(kindIndex, 1);
  14545. kindIndex--;
  14546. continue;
  14547. }
  14548. vbs[kind] = vertexBuffer;
  14549. data[kind] = vbs[kind].getData();
  14550. newdata[kind] = [];
  14551. }
  14552. // Save previous submeshes
  14553. var previousSubmeshes = this.subMeshes.slice(0);
  14554. var indices = this.getIndices();
  14555. var totalIndices = this.getTotalIndices();
  14556. // Generating unique vertices per face
  14557. var index;
  14558. for (index = 0; index < totalIndices; index++) {
  14559. var vertexIndex = indices[index];
  14560. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14561. kind = kinds[kindIndex];
  14562. var stride = vbs[kind].getStrideSize();
  14563. for (var offset = 0; offset < stride; offset++) {
  14564. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14565. }
  14566. }
  14567. }
  14568. // Updating faces & normal
  14569. var normals = [];
  14570. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14571. for (index = 0; index < totalIndices; index += 3) {
  14572. indices[index] = index;
  14573. indices[index + 1] = index + 1;
  14574. indices[index + 2] = index + 2;
  14575. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14576. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14577. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14578. var p1p2 = p1.subtract(p2);
  14579. var p3p2 = p3.subtract(p2);
  14580. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14581. // Store same normals for every vertex
  14582. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14583. normals.push(normal.x);
  14584. normals.push(normal.y);
  14585. normals.push(normal.z);
  14586. }
  14587. }
  14588. this.setIndices(indices);
  14589. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14590. // Updating vertex buffers
  14591. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14592. kind = kinds[kindIndex];
  14593. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14594. }
  14595. // Updating submeshes
  14596. this.releaseSubMeshes();
  14597. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14598. var previousOne = previousSubmeshes[submeshIndex];
  14599. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14600. }
  14601. this.synchronizeInstances();
  14602. };
  14603. // will inverse faces orientations, and invert normals too if specified
  14604. Mesh.prototype.flipFaces = function (flipNormals) {
  14605. if (flipNormals === void 0) { flipNormals = false; }
  14606. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14607. var i;
  14608. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14609. for (i = 0; i < vertex_data.normals.length; i++) {
  14610. vertex_data.normals[i] *= -1;
  14611. }
  14612. }
  14613. var temp;
  14614. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14615. // reassign indices
  14616. temp = vertex_data.indices[i + 1];
  14617. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14618. vertex_data.indices[i + 2] = temp;
  14619. }
  14620. vertex_data.applyToMesh(this);
  14621. };
  14622. // Instances
  14623. Mesh.prototype.createInstance = function (name) {
  14624. return new BABYLON.InstancedMesh(name, this);
  14625. };
  14626. Mesh.prototype.synchronizeInstances = function () {
  14627. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14628. var instance = this.instances[instanceIndex];
  14629. instance._syncSubMeshes();
  14630. }
  14631. };
  14632. /**
  14633. * Simplify the mesh according to the given array of settings.
  14634. * Function will return immediately and will simplify async.
  14635. * @param settings a collection of simplification settings.
  14636. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14637. * @param type the type of simplification to run.
  14638. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14639. */
  14640. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14641. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14642. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14643. this.getScene().simplificationQueue.addTask({
  14644. settings: settings,
  14645. parallelProcessing: parallelProcessing,
  14646. mesh: this,
  14647. simplificationType: simplificationType,
  14648. successCallback: successCallback
  14649. });
  14650. };
  14651. /**
  14652. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14653. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14654. * This should be used together with the simplification to avoid disappearing triangles.
  14655. * @param successCallback an optional success callback to be called after the optimization finished.
  14656. */
  14657. Mesh.prototype.optimizeIndices = function (successCallback) {
  14658. var _this = this;
  14659. var indices = this.getIndices();
  14660. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14661. var vectorPositions = [];
  14662. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14663. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14664. }
  14665. var dupes = [];
  14666. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14667. var realPos = vectorPositions.length - 1 - iteration;
  14668. var testedPosition = vectorPositions[realPos];
  14669. for (var j = 0; j < realPos; ++j) {
  14670. var againstPosition = vectorPositions[j];
  14671. if (testedPosition.equals(againstPosition)) {
  14672. dupes[realPos] = j;
  14673. break;
  14674. }
  14675. }
  14676. }, function () {
  14677. for (var i = 0; i < indices.length; ++i) {
  14678. indices[i] = dupes[indices[i]] || indices[i];
  14679. }
  14680. //indices are now reordered
  14681. var originalSubMeshes = _this.subMeshes.slice(0);
  14682. _this.setIndices(indices);
  14683. _this.subMeshes = originalSubMeshes;
  14684. if (successCallback) {
  14685. successCallback(_this);
  14686. }
  14687. });
  14688. };
  14689. // Statics
  14690. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14691. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14692. pathArray: pathArray,
  14693. closeArray: closeArray,
  14694. closePath: closePath,
  14695. offset: offset,
  14696. updatable: updatable,
  14697. sideOrientation: sideOrientation,
  14698. instance: instance
  14699. }, scene);
  14700. };
  14701. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14702. var options = {
  14703. radius: radius,
  14704. tessellation: tessellation,
  14705. sideOrientation: sideOrientation,
  14706. updatable: updatable
  14707. };
  14708. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14709. };
  14710. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14711. var options = {
  14712. size: size,
  14713. sideOrientation: sideOrientation,
  14714. updatable: updatable
  14715. };
  14716. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14717. };
  14718. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14719. var options = {
  14720. segments: segments,
  14721. diameterX: diameter,
  14722. diameterY: diameter,
  14723. diameterZ: diameter,
  14724. sideOrientation: sideOrientation,
  14725. updatable: updatable
  14726. };
  14727. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14728. };
  14729. // Cylinder and cone
  14730. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14731. var options = {
  14732. height: height,
  14733. diameterTop: diameterTop,
  14734. diameterBottom: diameterBottom,
  14735. tessellation: tessellation,
  14736. subdivisions: subdivisions,
  14737. sideOrientation: sideOrientation,
  14738. updatable: updatable
  14739. };
  14740. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14741. };
  14742. // Torus (Code from SharpDX.org)
  14743. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14744. var options = {
  14745. diameter: diameter,
  14746. thickness: thickness,
  14747. tessellation: tessellation,
  14748. sideOrientation: sideOrientation,
  14749. updatable: updatable
  14750. };
  14751. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14752. };
  14753. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14754. var options = {
  14755. radius: radius,
  14756. tube: tube,
  14757. radialSegments: radialSegments,
  14758. tubularSegments: tubularSegments,
  14759. p: p,
  14760. q: q,
  14761. sideOrientation: sideOrientation,
  14762. updatable: updatable
  14763. };
  14764. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14765. };
  14766. // Lines
  14767. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14768. var options = {
  14769. points: points,
  14770. updatable: updatable,
  14771. instance: instance
  14772. };
  14773. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14774. };
  14775. // Dashed Lines
  14776. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14777. var options = {
  14778. points: points,
  14779. dashSize: dashSize,
  14780. gapSize: gapSize,
  14781. dashNb: dashNb,
  14782. updatable: updatable
  14783. };
  14784. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14785. };
  14786. // Extrusion
  14787. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14788. var options = {
  14789. shape: shape,
  14790. path: path,
  14791. scale: scale,
  14792. rotation: rotation,
  14793. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14794. sideOrientation: sideOrientation,
  14795. instance: instance,
  14796. updatable: updatable
  14797. };
  14798. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  14799. };
  14800. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  14801. var options = {
  14802. shape: shape,
  14803. path: path,
  14804. scaleFunction: scaleFunction,
  14805. rotationFunction: rotationFunction,
  14806. ribbonCloseArray: ribbonCloseArray,
  14807. ribbonClosePath: ribbonClosePath,
  14808. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14809. sideOrientation: sideOrientation,
  14810. instance: instance,
  14811. updatable: updatable
  14812. };
  14813. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  14814. };
  14815. // Lathe
  14816. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  14817. var options = {
  14818. shape: shape,
  14819. radius: radius,
  14820. tesselation: tessellation,
  14821. sideOrientation: sideOrientation,
  14822. updatable: updatable
  14823. };
  14824. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  14825. };
  14826. // Plane & ground
  14827. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14828. var options = {
  14829. size: size,
  14830. width: size,
  14831. height: size,
  14832. sideOrientation: sideOrientation,
  14833. updatable: updatable
  14834. };
  14835. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  14836. };
  14837. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14838. var options = {
  14839. width: width,
  14840. height: height,
  14841. subdivisions: subdivisions,
  14842. updatable: updatable
  14843. };
  14844. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  14845. };
  14846. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14847. var options = {
  14848. xmin: xmin,
  14849. zmin: zmin,
  14850. xmax: xmax,
  14851. zmax: zmax,
  14852. subdivisions: subdivisions,
  14853. precision: precision,
  14854. updatable: updatable
  14855. };
  14856. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  14857. };
  14858. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14859. var options = {
  14860. width: width,
  14861. height: height,
  14862. subdivisions: subdivisions,
  14863. minHeight: minHeight,
  14864. maxHeight: maxHeight,
  14865. updatable: updatable,
  14866. onReady: onReady
  14867. };
  14868. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  14869. };
  14870. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  14871. var options = {
  14872. path: path,
  14873. radius: radius,
  14874. tessellation: tessellation,
  14875. radiusFunction: radiusFunction,
  14876. arc: 1,
  14877. cap: cap,
  14878. updatable: updatable,
  14879. sideOrientation: sideOrientation,
  14880. instance: instance
  14881. };
  14882. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  14883. };
  14884. Mesh.CreatePolyhedron = function (name, options, scene) {
  14885. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  14886. };
  14887. // Decals
  14888. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14889. var options = {
  14890. position: position,
  14891. normal: normal,
  14892. size: size,
  14893. angle: angle
  14894. };
  14895. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  14896. };
  14897. // Skeletons
  14898. /**
  14899. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  14900. */
  14901. Mesh.prototype.setPositionsForCPUSkinning = function () {
  14902. var source;
  14903. if (!this._sourcePositions) {
  14904. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14905. this._sourcePositions = new Float32Array(source);
  14906. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  14907. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  14908. }
  14909. }
  14910. return this._sourcePositions;
  14911. };
  14912. /**
  14913. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  14914. */
  14915. Mesh.prototype.setNormalsForCPUSkinning = function () {
  14916. var source;
  14917. if (!this._sourceNormals) {
  14918. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14919. this._sourceNormals = new Float32Array(source);
  14920. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  14921. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  14922. }
  14923. }
  14924. return this._sourceNormals;
  14925. };
  14926. /**
  14927. * Update the vertex buffers by applying transformation from the bones
  14928. * @param {skeleton} skeleton to apply
  14929. */
  14930. Mesh.prototype.applySkeleton = function (skeleton) {
  14931. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14932. return this;
  14933. }
  14934. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14935. return this;
  14936. }
  14937. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14938. return this;
  14939. }
  14940. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14941. return this;
  14942. }
  14943. if (!this._sourcePositions) {
  14944. this.setPositionsForCPUSkinning();
  14945. }
  14946. if (!this._sourceNormals) {
  14947. this.setNormalsForCPUSkinning();
  14948. }
  14949. // positionsData checks for not being Float32Array will only pass at most once
  14950. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14951. if (!(positionsData instanceof Float32Array)) {
  14952. positionsData = new Float32Array(positionsData);
  14953. }
  14954. // normalsData checks for not being Float32Array will only pass at most once
  14955. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14956. if (!(normalsData instanceof Float32Array)) {
  14957. normalsData = new Float32Array(normalsData);
  14958. }
  14959. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14960. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14961. var skeletonMatrices = skeleton.getTransformMatrices();
  14962. var tempVector3 = BABYLON.Vector3.Zero();
  14963. var finalMatrix = new BABYLON.Matrix();
  14964. var tempMatrix = new BABYLON.Matrix();
  14965. for (var index = 0; index < positionsData.length; index += 3) {
  14966. var index4 = (index / 3) * 4;
  14967. var matricesWeight0 = matricesWeightsData[index4];
  14968. var matricesWeight1 = matricesWeightsData[index4 + 1];
  14969. var matricesWeight2 = matricesWeightsData[index4 + 2];
  14970. var matricesWeight3 = matricesWeightsData[index4 + 3];
  14971. if (matricesWeight0 > 0) {
  14972. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  14973. finalMatrix.addToSelf(tempMatrix);
  14974. }
  14975. if (matricesWeight1 > 0) {
  14976. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  14977. finalMatrix.addToSelf(tempMatrix);
  14978. }
  14979. if (matricesWeight2 > 0) {
  14980. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  14981. finalMatrix.addToSelf(tempMatrix);
  14982. }
  14983. if (matricesWeight3 > 0) {
  14984. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  14985. finalMatrix.addToSelf(tempMatrix);
  14986. }
  14987. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  14988. tempVector3.toArray(positionsData, index);
  14989. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  14990. tempVector3.toArray(normalsData, index);
  14991. finalMatrix.reset();
  14992. }
  14993. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  14994. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  14995. return this;
  14996. };
  14997. // Tools
  14998. Mesh.MinMax = function (meshes) {
  14999. var minVector = null;
  15000. var maxVector = null;
  15001. for (var i in meshes) {
  15002. var mesh = meshes[i];
  15003. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15004. if (!minVector) {
  15005. minVector = boundingBox.minimumWorld;
  15006. maxVector = boundingBox.maximumWorld;
  15007. continue;
  15008. }
  15009. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15010. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15011. }
  15012. return {
  15013. min: minVector,
  15014. max: maxVector
  15015. };
  15016. };
  15017. Mesh.Center = function (meshesOrMinMaxVector) {
  15018. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15019. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15020. };
  15021. /**
  15022. * Merge the array of meshes into a single mesh for performance reasons.
  15023. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15024. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15025. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15026. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15027. */
  15028. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15029. if (disposeSource === void 0) { disposeSource = true; }
  15030. var index;
  15031. if (!allow32BitsIndices) {
  15032. var totalVertices = 0;
  15033. // Counting vertices
  15034. for (index = 0; index < meshes.length; index++) {
  15035. if (meshes[index]) {
  15036. totalVertices += meshes[index].getTotalVertices();
  15037. if (totalVertices > 65536) {
  15038. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15039. return null;
  15040. }
  15041. }
  15042. }
  15043. }
  15044. // Merge
  15045. var vertexData;
  15046. var otherVertexData;
  15047. var source;
  15048. for (index = 0; index < meshes.length; index++) {
  15049. if (meshes[index]) {
  15050. meshes[index].computeWorldMatrix(true);
  15051. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15052. otherVertexData.transform(meshes[index].getWorldMatrix());
  15053. if (vertexData) {
  15054. vertexData.merge(otherVertexData);
  15055. }
  15056. else {
  15057. vertexData = otherVertexData;
  15058. source = meshes[index];
  15059. }
  15060. }
  15061. }
  15062. if (!meshSubclass) {
  15063. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15064. }
  15065. vertexData.applyToMesh(meshSubclass);
  15066. // Setting properties
  15067. meshSubclass.material = source.material;
  15068. meshSubclass.checkCollisions = source.checkCollisions;
  15069. // Cleaning
  15070. if (disposeSource) {
  15071. for (index = 0; index < meshes.length; index++) {
  15072. if (meshes[index]) {
  15073. meshes[index].dispose();
  15074. }
  15075. }
  15076. }
  15077. return meshSubclass;
  15078. };
  15079. // Consts
  15080. Mesh._FRONTSIDE = 0;
  15081. Mesh._BACKSIDE = 1;
  15082. Mesh._DOUBLESIDE = 2;
  15083. Mesh._DEFAULTSIDE = 0;
  15084. Mesh._NO_CAP = 0;
  15085. Mesh._CAP_START = 1;
  15086. Mesh._CAP_END = 2;
  15087. Mesh._CAP_ALL = 3;
  15088. return Mesh;
  15089. })(BABYLON.AbstractMesh);
  15090. BABYLON.Mesh = Mesh;
  15091. })(BABYLON || (BABYLON = {}));
  15092. var BABYLON;
  15093. (function (BABYLON) {
  15094. var SubMesh = (function () {
  15095. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15096. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15097. this.materialIndex = materialIndex;
  15098. this.verticesStart = verticesStart;
  15099. this.verticesCount = verticesCount;
  15100. this.indexStart = indexStart;
  15101. this.indexCount = indexCount;
  15102. this._renderId = 0;
  15103. this._mesh = mesh;
  15104. this._renderingMesh = renderingMesh || mesh;
  15105. mesh.subMeshes.push(this);
  15106. this._trianglePlanes = [];
  15107. this._id = mesh.subMeshes.length - 1;
  15108. if (createBoundingBox) {
  15109. this.refreshBoundingInfo();
  15110. mesh.computeWorldMatrix(true);
  15111. }
  15112. }
  15113. SubMesh.prototype.getBoundingInfo = function () {
  15114. return this._boundingInfo;
  15115. };
  15116. SubMesh.prototype.getMesh = function () {
  15117. return this._mesh;
  15118. };
  15119. SubMesh.prototype.getRenderingMesh = function () {
  15120. return this._renderingMesh;
  15121. };
  15122. SubMesh.prototype.getMaterial = function () {
  15123. var rootMaterial = this._renderingMesh.material;
  15124. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15125. var multiMaterial = rootMaterial;
  15126. return multiMaterial.getSubMaterial(this.materialIndex);
  15127. }
  15128. if (!rootMaterial) {
  15129. return this._mesh.getScene().defaultMaterial;
  15130. }
  15131. return rootMaterial;
  15132. };
  15133. // Methods
  15134. SubMesh.prototype.refreshBoundingInfo = function () {
  15135. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15136. if (!data) {
  15137. this._boundingInfo = this._mesh._boundingInfo;
  15138. return;
  15139. }
  15140. var indices = this._renderingMesh.getIndices();
  15141. var extend;
  15142. //is this the only submesh?
  15143. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15144. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15145. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15146. }
  15147. else {
  15148. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15149. }
  15150. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15151. };
  15152. SubMesh.prototype._checkCollision = function (collider) {
  15153. return this._boundingInfo._checkCollision(collider);
  15154. };
  15155. SubMesh.prototype.updateBoundingInfo = function (world) {
  15156. if (!this._boundingInfo) {
  15157. this.refreshBoundingInfo();
  15158. }
  15159. this._boundingInfo._update(world);
  15160. };
  15161. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15162. return this._boundingInfo.isInFrustum(frustumPlanes);
  15163. };
  15164. SubMesh.prototype.render = function (enableAlphaMode) {
  15165. this._renderingMesh.render(this, enableAlphaMode);
  15166. };
  15167. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15168. if (!this._linesIndexBuffer) {
  15169. var linesIndices = [];
  15170. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15171. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15172. }
  15173. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15174. this.linesIndexCount = linesIndices.length;
  15175. }
  15176. return this._linesIndexBuffer;
  15177. };
  15178. SubMesh.prototype.canIntersects = function (ray) {
  15179. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15180. };
  15181. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15182. var intersectInfo = null;
  15183. // Triangles test
  15184. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15185. var p0 = positions[indices[index]];
  15186. var p1 = positions[indices[index + 1]];
  15187. var p2 = positions[indices[index + 2]];
  15188. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15189. if (currentIntersectInfo) {
  15190. if (currentIntersectInfo.distance < 0) {
  15191. continue;
  15192. }
  15193. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15194. intersectInfo = currentIntersectInfo;
  15195. intersectInfo.faceId = index / 3;
  15196. if (fastCheck) {
  15197. break;
  15198. }
  15199. }
  15200. }
  15201. }
  15202. return intersectInfo;
  15203. };
  15204. // Clone
  15205. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15206. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15207. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15208. return result;
  15209. };
  15210. // Dispose
  15211. SubMesh.prototype.dispose = function () {
  15212. if (this._linesIndexBuffer) {
  15213. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15214. this._linesIndexBuffer = null;
  15215. }
  15216. // Remove from mesh
  15217. var index = this._mesh.subMeshes.indexOf(this);
  15218. this._mesh.subMeshes.splice(index, 1);
  15219. };
  15220. // Statics
  15221. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15222. var minVertexIndex = Number.MAX_VALUE;
  15223. var maxVertexIndex = -Number.MAX_VALUE;
  15224. renderingMesh = renderingMesh || mesh;
  15225. var indices = renderingMesh.getIndices();
  15226. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15227. var vertexIndex = indices[index];
  15228. if (vertexIndex < minVertexIndex)
  15229. minVertexIndex = vertexIndex;
  15230. if (vertexIndex > maxVertexIndex)
  15231. maxVertexIndex = vertexIndex;
  15232. }
  15233. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15234. };
  15235. return SubMesh;
  15236. })();
  15237. BABYLON.SubMesh = SubMesh;
  15238. })(BABYLON || (BABYLON = {}));
  15239. var BABYLON;
  15240. (function (BABYLON) {
  15241. var MeshBuilder = (function () {
  15242. function MeshBuilder() {
  15243. }
  15244. MeshBuilder.CreateBox = function (name, options, scene) {
  15245. var box = new BABYLON.Mesh(name, scene);
  15246. var vertexData = BABYLON.VertexData.CreateBox(options);
  15247. vertexData.applyToMesh(box, options.updatable);
  15248. return box;
  15249. };
  15250. MeshBuilder.CreateSphere = function (name, options, scene) {
  15251. var sphere = new BABYLON.Mesh(name, scene);
  15252. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15253. vertexData.applyToMesh(sphere, options.updatable);
  15254. return sphere;
  15255. };
  15256. MeshBuilder.CreateDisc = function (name, options, scene) {
  15257. var disc = new BABYLON.Mesh(name, scene);
  15258. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15259. vertexData.applyToMesh(disc, options.updatable);
  15260. return disc;
  15261. };
  15262. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15263. var pathArray = options.pathArray;
  15264. var closeArray = options.closeArray;
  15265. var closePath = options.closePath;
  15266. var offset = options.offset;
  15267. var sideOrientation = options.sideOrientation;
  15268. var instance = options.instance;
  15269. var updatable = options.updatable;
  15270. if (instance) {
  15271. // positionFunction : ribbon case
  15272. // only pathArray and sideOrientation parameters are taken into account for positions update
  15273. var positionFunction = function (positions) {
  15274. var minlg = pathArray[0].length;
  15275. var i = 0;
  15276. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15277. for (var si = 1; si <= ns; si++) {
  15278. for (var p = 0; p < pathArray.length; p++) {
  15279. var path = pathArray[p];
  15280. var l = path.length;
  15281. minlg = (minlg < l) ? minlg : l;
  15282. var j = 0;
  15283. while (j < minlg) {
  15284. positions[i] = path[j].x;
  15285. positions[i + 1] = path[j].y;
  15286. positions[i + 2] = path[j].z;
  15287. j++;
  15288. i += 3;
  15289. }
  15290. if (instance._closePath) {
  15291. positions[i] = path[0].x;
  15292. positions[i + 1] = path[0].y;
  15293. positions[i + 2] = path[0].z;
  15294. i += 3;
  15295. }
  15296. }
  15297. }
  15298. };
  15299. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15300. positionFunction(positions);
  15301. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15302. if (!(instance.areNormalsFrozen)) {
  15303. var indices = instance.getIndices();
  15304. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15305. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15306. if (instance._closePath) {
  15307. var indexFirst = 0;
  15308. var indexLast = 0;
  15309. for (var p = 0; p < pathArray.length; p++) {
  15310. indexFirst = instance._idx[p] * 3;
  15311. if (p + 1 < pathArray.length) {
  15312. indexLast = (instance._idx[p + 1] - 1) * 3;
  15313. }
  15314. else {
  15315. indexLast = normals.length - 3;
  15316. }
  15317. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15318. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15319. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15320. normals[indexLast] = normals[indexFirst];
  15321. normals[indexLast + 1] = normals[indexFirst + 1];
  15322. normals[indexLast + 2] = normals[indexFirst + 2];
  15323. }
  15324. }
  15325. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15326. }
  15327. return instance;
  15328. }
  15329. else {
  15330. var ribbon = new BABYLON.Mesh(name, scene);
  15331. ribbon.sideOrientation = sideOrientation;
  15332. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15333. if (closePath) {
  15334. ribbon._idx = vertexData._idx;
  15335. }
  15336. ribbon._closePath = closePath;
  15337. ribbon._closeArray = closeArray;
  15338. vertexData.applyToMesh(ribbon, updatable);
  15339. return ribbon;
  15340. }
  15341. };
  15342. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15343. var cylinder = new BABYLON.Mesh(name, scene);
  15344. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15345. vertexData.applyToMesh(cylinder, options.updatable);
  15346. return cylinder;
  15347. };
  15348. MeshBuilder.CreateTorus = function (name, options, scene) {
  15349. var torus = new BABYLON.Mesh(name, scene);
  15350. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15351. vertexData.applyToMesh(torus, options.updatable);
  15352. return torus;
  15353. };
  15354. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15355. var torusKnot = new BABYLON.Mesh(name, scene);
  15356. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15357. vertexData.applyToMesh(torusKnot, options.updatable);
  15358. return torusKnot;
  15359. };
  15360. MeshBuilder.CreateLines = function (name, options, scene) {
  15361. var instance = options.instance;
  15362. var points = options.points;
  15363. if (instance) {
  15364. var positionFunction = function (positions) {
  15365. var i = 0;
  15366. for (var p = 0; p < points.length; p++) {
  15367. positions[i] = points[p].x;
  15368. positions[i + 1] = points[p].y;
  15369. positions[i + 2] = points[p].z;
  15370. i += 3;
  15371. }
  15372. };
  15373. instance.updateMeshPositions(positionFunction, false);
  15374. return instance;
  15375. }
  15376. // lines creation
  15377. var lines = new BABYLON.LinesMesh(name, scene);
  15378. var vertexData = BABYLON.VertexData.CreateLines(options);
  15379. vertexData.applyToMesh(lines, options.updatable);
  15380. return lines;
  15381. };
  15382. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15383. var points = options.points;
  15384. var instance = options.instance;
  15385. var gapSize = options.gapSize;
  15386. var dashNb = options.dashNb;
  15387. var dashSize = options.dashSize;
  15388. if (instance) {
  15389. var positionFunction = function (positions) {
  15390. var curvect = BABYLON.Vector3.Zero();
  15391. var nbSeg = positions.length / 6;
  15392. var lg = 0;
  15393. var nb = 0;
  15394. var shft = 0;
  15395. var dashshft = 0;
  15396. var curshft = 0;
  15397. var p = 0;
  15398. var i = 0;
  15399. var j = 0;
  15400. for (i = 0; i < points.length - 1; i++) {
  15401. points[i + 1].subtractToRef(points[i], curvect);
  15402. lg += curvect.length();
  15403. }
  15404. shft = lg / nbSeg;
  15405. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15406. for (i = 0; i < points.length - 1; i++) {
  15407. points[i + 1].subtractToRef(points[i], curvect);
  15408. nb = Math.floor(curvect.length() / shft);
  15409. curvect.normalize();
  15410. j = 0;
  15411. while (j < nb && p < positions.length) {
  15412. curshft = shft * j;
  15413. positions[p] = points[i].x + curshft * curvect.x;
  15414. positions[p + 1] = points[i].y + curshft * curvect.y;
  15415. positions[p + 2] = points[i].z + curshft * curvect.z;
  15416. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15417. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15418. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15419. p += 6;
  15420. j++;
  15421. }
  15422. }
  15423. while (p < positions.length) {
  15424. positions[p] = points[i].x;
  15425. positions[p + 1] = points[i].y;
  15426. positions[p + 2] = points[i].z;
  15427. p += 3;
  15428. }
  15429. };
  15430. instance.updateMeshPositions(positionFunction, false);
  15431. return instance;
  15432. }
  15433. // dashed lines creation
  15434. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15435. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15436. vertexData.applyToMesh(dashedLines, options.updatable);
  15437. dashedLines.dashSize = dashSize;
  15438. dashedLines.gapSize = gapSize;
  15439. return dashedLines;
  15440. };
  15441. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15442. var path = options.path;
  15443. var shape = options.shape;
  15444. var scale = options.scale || 1;
  15445. var rotation = options.rotation || 0;
  15446. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15447. var updatable = options.updatable;
  15448. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15449. var instance = options.instance;
  15450. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15451. };
  15452. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15453. var path = options.path;
  15454. var shape = options.shape;
  15455. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15456. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15457. var ribbonCloseArray = options.ribbonCloseArray || false;
  15458. var ribbonClosePath = options.ribbonClosePath || false;
  15459. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15460. var updatable = options.updatable;
  15461. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15462. var instance = options.instance;
  15463. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15464. };
  15465. MeshBuilder.CreateLathe = function (name, options, scene) {
  15466. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  15467. var closed = (options.closed === undefined) ? true : options.closed;
  15468. var shape = options.shape;
  15469. var radius = options.radius || 1;
  15470. var tessellation = options.tessellation || 64;
  15471. var updatable = options.updatable;
  15472. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15473. var pi2 = Math.PI * 2;
  15474. var shapeLathe = new Array();
  15475. // first rotatable point
  15476. var i = 0;
  15477. while (shape[i].x === 0) {
  15478. i++;
  15479. }
  15480. var pt = shape[i];
  15481. for (i = 0; i < shape.length; i++) {
  15482. shapeLathe.push(shape[i].subtract(pt));
  15483. }
  15484. // circle path
  15485. var step = pi2 / tessellation * arc;
  15486. var rotated;
  15487. var path = new Array();
  15488. ;
  15489. for (i = 0; i <= tessellation; i++) {
  15490. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15491. path.push(rotated);
  15492. }
  15493. if (closed) {
  15494. path.push(path[0]);
  15495. }
  15496. // extrusion
  15497. var scaleFunction = function () { return 1; };
  15498. var rotateFunction = function () { return 0; };
  15499. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15500. return lathe;
  15501. };
  15502. MeshBuilder.CreatePlane = function (name, options, scene) {
  15503. var plane = new BABYLON.Mesh(name, scene);
  15504. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15505. vertexData.applyToMesh(plane, options.updatable);
  15506. return plane;
  15507. };
  15508. MeshBuilder.CreateGround = function (name, options, scene) {
  15509. var ground = new BABYLON.GroundMesh(name, scene);
  15510. ground._setReady(false);
  15511. ground._subdivisions = options.subdivisions || 1;
  15512. var vertexData = BABYLON.VertexData.CreateGround(options);
  15513. vertexData.applyToMesh(ground, options.updatable);
  15514. ground._setReady(true);
  15515. return ground;
  15516. };
  15517. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15518. var tiledGround = new BABYLON.Mesh(name, scene);
  15519. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15520. vertexData.applyToMesh(tiledGround, options.updatable);
  15521. return tiledGround;
  15522. };
  15523. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15524. var width = options.width || 10;
  15525. var height = options.height || 10;
  15526. var subdivisions = options.subdivisions || 1;
  15527. var minHeight = options.minHeight;
  15528. var maxHeight = options.maxHeight || 10;
  15529. var updatable = options.updatable;
  15530. var onReady = options.onReady;
  15531. var ground = new BABYLON.GroundMesh(name, scene);
  15532. ground._subdivisions = subdivisions;
  15533. ground._setReady(false);
  15534. var onload = function (img) {
  15535. // Getting height map data
  15536. var canvas = document.createElement("canvas");
  15537. var context = canvas.getContext("2d");
  15538. var bufferWidth = img.width;
  15539. var bufferHeight = img.height;
  15540. canvas.width = bufferWidth;
  15541. canvas.height = bufferHeight;
  15542. context.drawImage(img, 0, 0);
  15543. // Create VertexData from map data
  15544. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15545. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15546. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15547. width: width, height: height,
  15548. subdivisions: subdivisions,
  15549. minHeight: minHeight, maxHeight: maxHeight,
  15550. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15551. });
  15552. vertexData.applyToMesh(ground, updatable);
  15553. ground._setReady(true);
  15554. //execute ready callback, if set
  15555. if (onReady) {
  15556. onReady(ground);
  15557. }
  15558. };
  15559. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15560. return ground;
  15561. };
  15562. MeshBuilder.CreateTube = function (name, options, scene) {
  15563. var path = options.path;
  15564. var radius = options.radius || 1;
  15565. var tessellation = options.tessellation || 64;
  15566. var radiusFunction = options.radiusFunction;
  15567. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15568. var updatable = options.updatable;
  15569. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15570. var instance = options.instance;
  15571. // tube geometry
  15572. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15573. var tangents = path3D.getTangents();
  15574. var normals = path3D.getNormals();
  15575. var distances = path3D.getDistances();
  15576. var pi2 = Math.PI * 2;
  15577. var step = pi2 / tessellation * arc;
  15578. var returnRadius = function () { return radius; };
  15579. var radiusFunctionFinal = radiusFunction || returnRadius;
  15580. var circlePath;
  15581. var rad;
  15582. var normal;
  15583. var rotated;
  15584. var rotationMatrix = BABYLON.Matrix.Zero();
  15585. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15586. for (var i = 0; i < path.length; i++) {
  15587. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15588. circlePath = Array(); // current circle array
  15589. normal = normals[i]; // current normal
  15590. for (var t = 0; t < tessellation; t++) {
  15591. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15592. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15593. circlePath.push(rotated);
  15594. }
  15595. circlePaths[index] = circlePath;
  15596. index++;
  15597. }
  15598. // cap
  15599. var capPath = function (nbPoints, pathIndex) {
  15600. var pointCap = Array();
  15601. for (var i = 0; i < nbPoints; i++) {
  15602. pointCap.push(path[pathIndex]);
  15603. }
  15604. return pointCap;
  15605. };
  15606. switch (cap) {
  15607. case BABYLON.Mesh.NO_CAP:
  15608. break;
  15609. case BABYLON.Mesh.CAP_START:
  15610. circlePaths[0] = capPath(tessellation, 0);
  15611. circlePaths[1] = circlePaths[2].slice(0);
  15612. break;
  15613. case BABYLON.Mesh.CAP_END:
  15614. circlePaths[index] = circlePaths[index - 1].slice(0);
  15615. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15616. break;
  15617. case BABYLON.Mesh.CAP_ALL:
  15618. circlePaths[0] = capPath(tessellation, 0);
  15619. circlePaths[1] = circlePaths[2].slice(0);
  15620. circlePaths[index] = circlePaths[index - 1].slice(0);
  15621. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15622. break;
  15623. default:
  15624. break;
  15625. }
  15626. return circlePaths;
  15627. };
  15628. var path3D;
  15629. var pathArray;
  15630. if (instance) {
  15631. var arc = options.arc || instance.arc;
  15632. path3D = (instance.path3D).update(path);
  15633. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15634. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15635. instance.path3D = path3D;
  15636. instance.pathArray = pathArray;
  15637. instance.arc = arc;
  15638. return instance;
  15639. }
  15640. // tube creation
  15641. path3D = new BABYLON.Path3D(path);
  15642. var newPathArray = new Array();
  15643. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15644. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15645. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15646. tube.pathArray = pathArray;
  15647. tube.path3D = path3D;
  15648. tube.tessellation = tessellation;
  15649. tube.cap = cap;
  15650. tube.arc = options.arc;
  15651. return tube;
  15652. };
  15653. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15654. var polyhedron = new BABYLON.Mesh(name, scene);
  15655. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15656. vertexData.applyToMesh(polyhedron, options.updatable);
  15657. return polyhedron;
  15658. };
  15659. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15660. var indices = sourceMesh.getIndices();
  15661. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15662. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15663. var position = options.position || BABYLON.Vector3.Zero();
  15664. var normal = options.normal || BABYLON.Vector3.Up();
  15665. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15666. var angle = options.angle || 0;
  15667. // Getting correct rotation
  15668. if (!normal) {
  15669. var target = new BABYLON.Vector3(0, 0, 1);
  15670. var camera = sourceMesh.getScene().activeCamera;
  15671. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15672. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15673. }
  15674. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15675. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15676. var pitch = Math.atan2(normal.y, len);
  15677. // Matrix
  15678. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15679. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15680. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15681. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15682. var vertexData = new BABYLON.VertexData();
  15683. vertexData.indices = [];
  15684. vertexData.positions = [];
  15685. vertexData.normals = [];
  15686. vertexData.uvs = [];
  15687. var currentVertexDataIndex = 0;
  15688. var extractDecalVector3 = function (indexId) {
  15689. var vertexId = indices[indexId];
  15690. var result = new BABYLON.PositionNormalVertex();
  15691. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15692. // Send vector to decal local world
  15693. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15694. // Get normal
  15695. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15696. return result;
  15697. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15698. var clip = function (vertices, axis) {
  15699. if (vertices.length === 0) {
  15700. return vertices;
  15701. }
  15702. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15703. var clipVertices = function (v0, v1) {
  15704. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15705. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15706. };
  15707. var result = new Array();
  15708. for (var index = 0; index < vertices.length; index += 3) {
  15709. var v1Out;
  15710. var v2Out;
  15711. var v3Out;
  15712. var total = 0;
  15713. var nV1, nV2, nV3, nV4;
  15714. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15715. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15716. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15717. v1Out = d1 > 0;
  15718. v2Out = d2 > 0;
  15719. v3Out = d3 > 0;
  15720. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15721. switch (total) {
  15722. case 0:
  15723. result.push(vertices[index]);
  15724. result.push(vertices[index + 1]);
  15725. result.push(vertices[index + 2]);
  15726. break;
  15727. case 1:
  15728. if (v1Out) {
  15729. nV1 = vertices[index + 1];
  15730. nV2 = vertices[index + 2];
  15731. nV3 = clipVertices(vertices[index], nV1);
  15732. nV4 = clipVertices(vertices[index], nV2);
  15733. }
  15734. if (v2Out) {
  15735. nV1 = vertices[index];
  15736. nV2 = vertices[index + 2];
  15737. nV3 = clipVertices(vertices[index + 1], nV1);
  15738. nV4 = clipVertices(vertices[index + 1], nV2);
  15739. result.push(nV3);
  15740. result.push(nV2.clone());
  15741. result.push(nV1.clone());
  15742. result.push(nV2.clone());
  15743. result.push(nV3.clone());
  15744. result.push(nV4);
  15745. break;
  15746. }
  15747. if (v3Out) {
  15748. nV1 = vertices[index];
  15749. nV2 = vertices[index + 1];
  15750. nV3 = clipVertices(vertices[index + 2], nV1);
  15751. nV4 = clipVertices(vertices[index + 2], nV2);
  15752. }
  15753. result.push(nV1.clone());
  15754. result.push(nV2.clone());
  15755. result.push(nV3);
  15756. result.push(nV4);
  15757. result.push(nV3.clone());
  15758. result.push(nV2.clone());
  15759. break;
  15760. case 2:
  15761. if (!v1Out) {
  15762. nV1 = vertices[index].clone();
  15763. nV2 = clipVertices(nV1, vertices[index + 1]);
  15764. nV3 = clipVertices(nV1, vertices[index + 2]);
  15765. result.push(nV1);
  15766. result.push(nV2);
  15767. result.push(nV3);
  15768. }
  15769. if (!v2Out) {
  15770. nV1 = vertices[index + 1].clone();
  15771. nV2 = clipVertices(nV1, vertices[index + 2]);
  15772. nV3 = clipVertices(nV1, vertices[index]);
  15773. result.push(nV1);
  15774. result.push(nV2);
  15775. result.push(nV3);
  15776. }
  15777. if (!v3Out) {
  15778. nV1 = vertices[index + 2].clone();
  15779. nV2 = clipVertices(nV1, vertices[index]);
  15780. nV3 = clipVertices(nV1, vertices[index + 1]);
  15781. result.push(nV1);
  15782. result.push(nV2);
  15783. result.push(nV3);
  15784. }
  15785. break;
  15786. case 3:
  15787. break;
  15788. }
  15789. }
  15790. return result;
  15791. };
  15792. for (var index = 0; index < indices.length; index += 3) {
  15793. var faceVertices = new Array();
  15794. faceVertices.push(extractDecalVector3(index));
  15795. faceVertices.push(extractDecalVector3(index + 1));
  15796. faceVertices.push(extractDecalVector3(index + 2));
  15797. // Clip
  15798. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15799. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15800. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15801. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15802. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15803. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15804. if (faceVertices.length === 0) {
  15805. continue;
  15806. }
  15807. // Add UVs and get back to world
  15808. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15809. var vertex = faceVertices[vIndex];
  15810. vertexData.indices.push(currentVertexDataIndex);
  15811. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15812. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15813. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15814. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15815. currentVertexDataIndex++;
  15816. }
  15817. }
  15818. // Return mesh
  15819. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  15820. vertexData.applyToMesh(decal);
  15821. decal.position = position.clone();
  15822. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15823. return decal;
  15824. };
  15825. // Privates
  15826. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15827. // extrusion geometry
  15828. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15829. var tangents = path3D.getTangents();
  15830. var normals = path3D.getNormals();
  15831. var binormals = path3D.getBinormals();
  15832. var distances = path3D.getDistances();
  15833. var angle = 0;
  15834. var returnScale = function () { return scale; };
  15835. var returnRotation = function () { return rotation; };
  15836. var rotate = custom ? rotateFunction : returnRotation;
  15837. var scl = custom ? scaleFunction : returnScale;
  15838. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15839. var rotationMatrix = BABYLON.Matrix.Zero();
  15840. for (var i = 0; i < curve.length; i++) {
  15841. var shapePath = new Array();
  15842. var angleStep = rotate(i, distances[i]);
  15843. var scaleRatio = scl(i, distances[i]);
  15844. for (var p = 0; p < shape.length; p++) {
  15845. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  15846. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15847. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15848. shapePath.push(rotated);
  15849. }
  15850. shapePaths[index] = shapePath;
  15851. angle += angleStep;
  15852. index++;
  15853. }
  15854. // cap
  15855. var capPath = function (shapePath) {
  15856. var pointCap = Array();
  15857. var barycenter = BABYLON.Vector3.Zero();
  15858. var i;
  15859. for (i = 0; i < shapePath.length; i++) {
  15860. barycenter.addInPlace(shapePath[i]);
  15861. }
  15862. barycenter.scaleInPlace(1 / shapePath.length);
  15863. for (i = 0; i < shapePath.length; i++) {
  15864. pointCap.push(barycenter);
  15865. }
  15866. return pointCap;
  15867. };
  15868. switch (cap) {
  15869. case BABYLON.Mesh.NO_CAP:
  15870. break;
  15871. case BABYLON.Mesh.CAP_START:
  15872. shapePaths[0] = capPath(shapePaths[2]);
  15873. shapePaths[1] = shapePaths[2].slice(0);
  15874. break;
  15875. case BABYLON.Mesh.CAP_END:
  15876. shapePaths[index] = shapePaths[index - 1];
  15877. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15878. break;
  15879. case BABYLON.Mesh.CAP_ALL:
  15880. shapePaths[0] = capPath(shapePaths[2]);
  15881. shapePaths[1] = shapePaths[2].slice(0);
  15882. shapePaths[index] = shapePaths[index - 1];
  15883. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15884. break;
  15885. default:
  15886. break;
  15887. }
  15888. return shapePaths;
  15889. };
  15890. var path3D;
  15891. var pathArray;
  15892. if (instance) {
  15893. path3D = (instance.path3D).update(curve);
  15894. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15895. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15896. return instance;
  15897. }
  15898. // extruded shape creation
  15899. path3D = new BABYLON.Path3D(curve);
  15900. var newShapePaths = new Array();
  15901. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15902. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15903. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15904. extrudedGeneric.pathArray = pathArray;
  15905. extrudedGeneric.path3D = path3D;
  15906. extrudedGeneric.cap = cap;
  15907. return extrudedGeneric;
  15908. };
  15909. return MeshBuilder;
  15910. })();
  15911. BABYLON.MeshBuilder = MeshBuilder;
  15912. })(BABYLON || (BABYLON = {}));
  15913. var BABYLON;
  15914. (function (BABYLON) {
  15915. var BaseTexture = (function () {
  15916. function BaseTexture(scene) {
  15917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15918. this.hasAlpha = false;
  15919. this.getAlphaFromRGB = false;
  15920. this.level = 1;
  15921. this.isCube = false;
  15922. this.isRenderTarget = false;
  15923. this.animations = new Array();
  15924. this.coordinatesIndex = 0;
  15925. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15926. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15927. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15928. this.anisotropicFilteringLevel = 4;
  15929. this._scene = scene;
  15930. this._scene.textures.push(this);
  15931. }
  15932. BaseTexture.prototype.getScene = function () {
  15933. return this._scene;
  15934. };
  15935. BaseTexture.prototype.getTextureMatrix = function () {
  15936. return null;
  15937. };
  15938. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15939. return null;
  15940. };
  15941. BaseTexture.prototype.getInternalTexture = function () {
  15942. return this._texture;
  15943. };
  15944. BaseTexture.prototype.isReady = function () {
  15945. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15946. return true;
  15947. }
  15948. if (this._texture) {
  15949. return this._texture.isReady;
  15950. }
  15951. return false;
  15952. };
  15953. BaseTexture.prototype.getSize = function () {
  15954. if (this._texture._width) {
  15955. return { width: this._texture._width, height: this._texture._height };
  15956. }
  15957. if (this._texture._size) {
  15958. return { width: this._texture._size, height: this._texture._size };
  15959. }
  15960. return { width: 0, height: 0 };
  15961. };
  15962. BaseTexture.prototype.getBaseSize = function () {
  15963. if (!this.isReady())
  15964. return { width: 0, height: 0 };
  15965. if (this._texture._size) {
  15966. return { width: this._texture._size, height: this._texture._size };
  15967. }
  15968. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15969. };
  15970. BaseTexture.prototype.scale = function (ratio) {
  15971. };
  15972. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15973. get: function () {
  15974. return false;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15980. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15981. for (var index = 0; index < texturesCache.length; index++) {
  15982. var texturesCacheEntry = texturesCache[index];
  15983. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15984. texturesCache.splice(index, 1);
  15985. return;
  15986. }
  15987. }
  15988. };
  15989. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15990. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15991. for (var index = 0; index < texturesCache.length; index++) {
  15992. var texturesCacheEntry = texturesCache[index];
  15993. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15994. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15995. texturesCacheEntry.references++;
  15996. return texturesCacheEntry;
  15997. }
  15998. }
  15999. }
  16000. return null;
  16001. };
  16002. BaseTexture.prototype.delayLoad = function () {
  16003. };
  16004. BaseTexture.prototype.clone = function () {
  16005. return null;
  16006. };
  16007. BaseTexture.prototype.releaseInternalTexture = function () {
  16008. if (this._texture) {
  16009. this._scene.getEngine().releaseInternalTexture(this._texture);
  16010. delete this._texture;
  16011. }
  16012. };
  16013. BaseTexture.prototype.dispose = function () {
  16014. // Remove from scene
  16015. var index = this._scene.textures.indexOf(this);
  16016. if (index >= 0) {
  16017. this._scene.textures.splice(index, 1);
  16018. }
  16019. if (this._texture === undefined) {
  16020. return;
  16021. }
  16022. // Callback
  16023. if (this.onDispose) {
  16024. this.onDispose();
  16025. }
  16026. };
  16027. return BaseTexture;
  16028. })();
  16029. BABYLON.BaseTexture = BaseTexture;
  16030. })(BABYLON || (BABYLON = {}));
  16031. var BABYLON;
  16032. (function (BABYLON) {
  16033. var Texture = (function (_super) {
  16034. __extends(Texture, _super);
  16035. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16036. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16037. if (onLoad === void 0) { onLoad = null; }
  16038. if (onError === void 0) { onError = null; }
  16039. if (buffer === void 0) { buffer = null; }
  16040. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16041. _super.call(this, scene);
  16042. this.uOffset = 0;
  16043. this.vOffset = 0;
  16044. this.uScale = 1.0;
  16045. this.vScale = 1.0;
  16046. this.uAng = 0;
  16047. this.vAng = 0;
  16048. this.wAng = 0;
  16049. this.name = url;
  16050. this.url = url;
  16051. this._noMipmap = noMipmap;
  16052. this._invertY = invertY;
  16053. this._samplingMode = samplingMode;
  16054. this._buffer = buffer;
  16055. this._deleteBuffer = deleteBuffer;
  16056. if (!url) {
  16057. return;
  16058. }
  16059. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16060. if (!this._texture) {
  16061. if (!scene.useDelayedTextureLoading) {
  16062. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16063. if (deleteBuffer) {
  16064. delete this._buffer;
  16065. }
  16066. }
  16067. else {
  16068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16069. }
  16070. }
  16071. else {
  16072. BABYLON.Tools.SetImmediate(function () {
  16073. if (onLoad) {
  16074. onLoad();
  16075. }
  16076. });
  16077. }
  16078. }
  16079. Texture.prototype.delayLoad = function () {
  16080. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16081. return;
  16082. }
  16083. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16084. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16085. if (!this._texture) {
  16086. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16087. if (this._deleteBuffer) {
  16088. delete this._buffer;
  16089. }
  16090. }
  16091. };
  16092. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16093. if (!this._texture) {
  16094. return;
  16095. }
  16096. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16097. };
  16098. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16099. x *= this.uScale;
  16100. y *= this.vScale;
  16101. x -= 0.5 * this.uScale;
  16102. y -= 0.5 * this.vScale;
  16103. z -= 0.5;
  16104. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16105. t.x += 0.5 * this.uScale + this.uOffset;
  16106. t.y += 0.5 * this.vScale + this.vOffset;
  16107. t.z += 0.5;
  16108. };
  16109. Texture.prototype.getTextureMatrix = function () {
  16110. if (this.uOffset === this._cachedUOffset &&
  16111. this.vOffset === this._cachedVOffset &&
  16112. this.uScale === this._cachedUScale &&
  16113. this.vScale === this._cachedVScale &&
  16114. this.uAng === this._cachedUAng &&
  16115. this.vAng === this._cachedVAng &&
  16116. this.wAng === this._cachedWAng) {
  16117. return this._cachedTextureMatrix;
  16118. }
  16119. this._cachedUOffset = this.uOffset;
  16120. this._cachedVOffset = this.vOffset;
  16121. this._cachedUScale = this.uScale;
  16122. this._cachedVScale = this.vScale;
  16123. this._cachedUAng = this.uAng;
  16124. this._cachedVAng = this.vAng;
  16125. this._cachedWAng = this.wAng;
  16126. if (!this._cachedTextureMatrix) {
  16127. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16128. this._rowGenerationMatrix = new BABYLON.Matrix();
  16129. this._t0 = BABYLON.Vector3.Zero();
  16130. this._t1 = BABYLON.Vector3.Zero();
  16131. this._t2 = BABYLON.Vector3.Zero();
  16132. }
  16133. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16134. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16135. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16136. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16137. this._t1.subtractInPlace(this._t0);
  16138. this._t2.subtractInPlace(this._t0);
  16139. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16140. this._cachedTextureMatrix.m[0] = this._t1.x;
  16141. this._cachedTextureMatrix.m[1] = this._t1.y;
  16142. this._cachedTextureMatrix.m[2] = this._t1.z;
  16143. this._cachedTextureMatrix.m[4] = this._t2.x;
  16144. this._cachedTextureMatrix.m[5] = this._t2.y;
  16145. this._cachedTextureMatrix.m[6] = this._t2.z;
  16146. this._cachedTextureMatrix.m[8] = this._t0.x;
  16147. this._cachedTextureMatrix.m[9] = this._t0.y;
  16148. this._cachedTextureMatrix.m[10] = this._t0.z;
  16149. return this._cachedTextureMatrix;
  16150. };
  16151. Texture.prototype.getReflectionTextureMatrix = function () {
  16152. if (this.uOffset === this._cachedUOffset &&
  16153. this.vOffset === this._cachedVOffset &&
  16154. this.uScale === this._cachedUScale &&
  16155. this.vScale === this._cachedVScale &&
  16156. this.coordinatesMode === this._cachedCoordinatesMode) {
  16157. return this._cachedTextureMatrix;
  16158. }
  16159. if (!this._cachedTextureMatrix) {
  16160. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16161. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16162. }
  16163. this._cachedCoordinatesMode = this.coordinatesMode;
  16164. switch (this.coordinatesMode) {
  16165. case Texture.SPHERICAL_MODE:
  16166. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16167. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16168. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16169. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16170. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16171. break;
  16172. case Texture.PLANAR_MODE:
  16173. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16174. this._cachedTextureMatrix[0] = this.uScale;
  16175. this._cachedTextureMatrix[5] = this.vScale;
  16176. this._cachedTextureMatrix[12] = this.uOffset;
  16177. this._cachedTextureMatrix[13] = this.vOffset;
  16178. break;
  16179. case Texture.PROJECTION_MODE:
  16180. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16181. this._projectionModeMatrix.m[0] = 0.5;
  16182. this._projectionModeMatrix.m[5] = -0.5;
  16183. this._projectionModeMatrix.m[10] = 0.0;
  16184. this._projectionModeMatrix.m[12] = 0.5;
  16185. this._projectionModeMatrix.m[13] = 0.5;
  16186. this._projectionModeMatrix.m[14] = 1.0;
  16187. this._projectionModeMatrix.m[15] = 1.0;
  16188. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16189. break;
  16190. default:
  16191. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16192. break;
  16193. }
  16194. return this._cachedTextureMatrix;
  16195. };
  16196. Texture.prototype.clone = function () {
  16197. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16198. // Base texture
  16199. newTexture.hasAlpha = this.hasAlpha;
  16200. newTexture.level = this.level;
  16201. newTexture.wrapU = this.wrapU;
  16202. newTexture.wrapV = this.wrapV;
  16203. newTexture.coordinatesIndex = this.coordinatesIndex;
  16204. newTexture.coordinatesMode = this.coordinatesMode;
  16205. // Texture
  16206. newTexture.uOffset = this.uOffset;
  16207. newTexture.vOffset = this.vOffset;
  16208. newTexture.uScale = this.uScale;
  16209. newTexture.vScale = this.vScale;
  16210. newTexture.uAng = this.uAng;
  16211. newTexture.vAng = this.vAng;
  16212. newTexture.wAng = this.wAng;
  16213. return newTexture;
  16214. };
  16215. // Statics
  16216. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16217. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16218. if (onLoad === void 0) { onLoad = null; }
  16219. if (onError === void 0) { onError = null; }
  16220. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16221. };
  16222. // Constants
  16223. Texture.NEAREST_SAMPLINGMODE = 1;
  16224. Texture.BILINEAR_SAMPLINGMODE = 2;
  16225. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16226. Texture.EXPLICIT_MODE = 0;
  16227. Texture.SPHERICAL_MODE = 1;
  16228. Texture.PLANAR_MODE = 2;
  16229. Texture.CUBIC_MODE = 3;
  16230. Texture.PROJECTION_MODE = 4;
  16231. Texture.SKYBOX_MODE = 5;
  16232. Texture.INVCUBIC_MODE = 6;
  16233. Texture.CLAMP_ADDRESSMODE = 0;
  16234. Texture.WRAP_ADDRESSMODE = 1;
  16235. Texture.MIRROR_ADDRESSMODE = 2;
  16236. return Texture;
  16237. })(BABYLON.BaseTexture);
  16238. BABYLON.Texture = Texture;
  16239. })(BABYLON || (BABYLON = {}));
  16240. var BABYLON;
  16241. (function (BABYLON) {
  16242. var CubeTexture = (function (_super) {
  16243. __extends(CubeTexture, _super);
  16244. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16245. _super.call(this, scene);
  16246. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16247. this.name = rootUrl;
  16248. this.url = rootUrl;
  16249. this._noMipmap = noMipmap;
  16250. this.hasAlpha = false;
  16251. if (!rootUrl) {
  16252. return;
  16253. }
  16254. this._texture = this._getFromCache(rootUrl, noMipmap);
  16255. if (!extensions) {
  16256. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16257. }
  16258. this._extensions = extensions;
  16259. if (!this._texture) {
  16260. if (!scene.useDelayedTextureLoading) {
  16261. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16262. }
  16263. else {
  16264. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16265. }
  16266. }
  16267. this.isCube = true;
  16268. this._textureMatrix = BABYLON.Matrix.Identity();
  16269. }
  16270. CubeTexture.prototype.clone = function () {
  16271. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16272. // Base texture
  16273. newTexture.level = this.level;
  16274. newTexture.wrapU = this.wrapU;
  16275. newTexture.wrapV = this.wrapV;
  16276. newTexture.coordinatesIndex = this.coordinatesIndex;
  16277. newTexture.coordinatesMode = this.coordinatesMode;
  16278. return newTexture;
  16279. };
  16280. // Methods
  16281. CubeTexture.prototype.delayLoad = function () {
  16282. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16283. return;
  16284. }
  16285. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16286. this._texture = this._getFromCache(this.url, this._noMipmap);
  16287. if (!this._texture) {
  16288. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16289. }
  16290. };
  16291. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16292. return this._textureMatrix;
  16293. };
  16294. return CubeTexture;
  16295. })(BABYLON.BaseTexture);
  16296. BABYLON.CubeTexture = CubeTexture;
  16297. })(BABYLON || (BABYLON = {}));
  16298. var BABYLON;
  16299. (function (BABYLON) {
  16300. var RenderTargetTexture = (function (_super) {
  16301. __extends(RenderTargetTexture, _super);
  16302. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16303. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16304. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16305. if (isCube === void 0) { isCube = false; }
  16306. _super.call(this, null, scene, !generateMipMaps);
  16307. this.isCube = isCube;
  16308. this.renderList = new Array();
  16309. this.renderParticles = true;
  16310. this.renderSprites = false;
  16311. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16312. this._currentRefreshId = -1;
  16313. this._refreshRate = 1;
  16314. this.name = name;
  16315. this.isRenderTarget = true;
  16316. this._size = size;
  16317. this._generateMipMaps = generateMipMaps;
  16318. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16319. if (isCube) {
  16320. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16321. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16322. this._textureMatrix = BABYLON.Matrix.Identity();
  16323. }
  16324. else {
  16325. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16326. }
  16327. // Rendering groups
  16328. this._renderingManager = new BABYLON.RenderingManager(scene);
  16329. }
  16330. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16331. get: function () {
  16332. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16333. },
  16334. enumerable: true,
  16335. configurable: true
  16336. });
  16337. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16338. get: function () {
  16339. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16340. },
  16341. enumerable: true,
  16342. configurable: true
  16343. });
  16344. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16345. get: function () {
  16346. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16347. },
  16348. enumerable: true,
  16349. configurable: true
  16350. });
  16351. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16352. this._currentRefreshId = -1;
  16353. };
  16354. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16355. get: function () {
  16356. return this._refreshRate;
  16357. },
  16358. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16359. set: function (value) {
  16360. this._refreshRate = value;
  16361. this.resetRefreshCounter();
  16362. },
  16363. enumerable: true,
  16364. configurable: true
  16365. });
  16366. RenderTargetTexture.prototype._shouldRender = function () {
  16367. if (this._currentRefreshId === -1) {
  16368. this._currentRefreshId = 1;
  16369. return true;
  16370. }
  16371. if (this.refreshRate === this._currentRefreshId) {
  16372. this._currentRefreshId = 1;
  16373. return true;
  16374. }
  16375. this._currentRefreshId++;
  16376. return false;
  16377. };
  16378. RenderTargetTexture.prototype.isReady = function () {
  16379. if (!this.getScene().renderTargetsEnabled) {
  16380. return false;
  16381. }
  16382. return _super.prototype.isReady.call(this);
  16383. };
  16384. RenderTargetTexture.prototype.getRenderSize = function () {
  16385. return this._size;
  16386. };
  16387. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16388. get: function () {
  16389. return true;
  16390. },
  16391. enumerable: true,
  16392. configurable: true
  16393. });
  16394. RenderTargetTexture.prototype.scale = function (ratio) {
  16395. var newSize = this._size * ratio;
  16396. this.resize(newSize, this._generateMipMaps);
  16397. };
  16398. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16399. if (this.isCube) {
  16400. return this._textureMatrix;
  16401. }
  16402. return _super.prototype.getReflectionTextureMatrix.call(this);
  16403. };
  16404. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16405. this.releaseInternalTexture();
  16406. if (this.isCube) {
  16407. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16408. }
  16409. else {
  16410. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16411. }
  16412. };
  16413. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16414. var scene = this.getScene();
  16415. if (this._waitingRenderList) {
  16416. this.renderList = [];
  16417. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16418. var id = this._waitingRenderList[index];
  16419. this.renderList.push(scene.getMeshByID(id));
  16420. }
  16421. delete this._waitingRenderList;
  16422. }
  16423. if (this.renderList && this.renderList.length === 0) {
  16424. return;
  16425. }
  16426. // Prepare renderingManager
  16427. this._renderingManager.reset();
  16428. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16429. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16430. var mesh = currentRenderList[meshIndex];
  16431. if (mesh) {
  16432. if (!mesh.isReady()) {
  16433. // Reset _currentRefreshId
  16434. this.resetRefreshCounter();
  16435. continue;
  16436. }
  16437. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16438. mesh._activate(scene.getRenderId());
  16439. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16440. var subMesh = mesh.subMeshes[subIndex];
  16441. scene._activeIndices += subMesh.indexCount;
  16442. this._renderingManager.dispatch(subMesh);
  16443. }
  16444. }
  16445. }
  16446. }
  16447. if (this.isCube) {
  16448. for (var face = 0; face < 6; face++) {
  16449. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16450. }
  16451. }
  16452. else {
  16453. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16454. }
  16455. if (this.onAfterUnbind) {
  16456. this.onAfterUnbind();
  16457. }
  16458. scene.resetCachedMaterial();
  16459. };
  16460. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16461. var scene = this.getScene();
  16462. var engine = scene.getEngine();
  16463. // Bind
  16464. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16465. if (this.isCube) {
  16466. engine.bindFramebuffer(this._texture, faceIndex);
  16467. }
  16468. else {
  16469. engine.bindFramebuffer(this._texture);
  16470. }
  16471. }
  16472. if (this.onBeforeRender) {
  16473. this.onBeforeRender(faceIndex);
  16474. }
  16475. // Clear
  16476. if (this.onClear) {
  16477. this.onClear(engine);
  16478. }
  16479. else {
  16480. engine.clear(scene.clearColor, true, true);
  16481. }
  16482. if (!this._doNotChangeAspectRatio) {
  16483. scene.updateTransformMatrix(true);
  16484. }
  16485. // Render
  16486. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16487. if (useCameraPostProcess) {
  16488. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16489. }
  16490. if (!this._doNotChangeAspectRatio) {
  16491. scene.updateTransformMatrix(true);
  16492. }
  16493. if (this.onAfterRender) {
  16494. this.onAfterRender(faceIndex);
  16495. }
  16496. // Dump ?
  16497. if (dumpForDebug) {
  16498. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16499. }
  16500. // Unbind
  16501. if (!this.isCube || faceIndex === 5) {
  16502. if (this.isCube) {
  16503. if (faceIndex === 5) {
  16504. engine.generateMipMapsForCubemap(this._texture);
  16505. }
  16506. }
  16507. engine.unBindFramebuffer(this._texture, this.isCube);
  16508. }
  16509. };
  16510. RenderTargetTexture.prototype.clone = function () {
  16511. var textureSize = this.getSize();
  16512. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16513. // Base texture
  16514. newTexture.hasAlpha = this.hasAlpha;
  16515. newTexture.level = this.level;
  16516. // RenderTarget Texture
  16517. newTexture.coordinatesMode = this.coordinatesMode;
  16518. newTexture.renderList = this.renderList.slice(0);
  16519. return newTexture;
  16520. };
  16521. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16522. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16523. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16524. return RenderTargetTexture;
  16525. })(BABYLON.Texture);
  16526. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16527. })(BABYLON || (BABYLON = {}));
  16528. var BABYLON;
  16529. (function (BABYLON) {
  16530. var ProceduralTexture = (function (_super) {
  16531. __extends(ProceduralTexture, _super);
  16532. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16533. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16534. _super.call(this, null, scene, !generateMipMaps);
  16535. this.isEnabled = true;
  16536. this._currentRefreshId = -1;
  16537. this._refreshRate = 1;
  16538. this._vertexDeclaration = [2];
  16539. this._vertexStrideSize = 2 * 4;
  16540. this._uniforms = new Array();
  16541. this._samplers = new Array();
  16542. this._textures = new Array();
  16543. this._floats = new Array();
  16544. this._floatsArrays = {};
  16545. this._colors3 = new Array();
  16546. this._colors4 = new Array();
  16547. this._vectors2 = new Array();
  16548. this._vectors3 = new Array();
  16549. this._matrices = new Array();
  16550. this._fallbackTextureUsed = false;
  16551. scene._proceduralTextures.push(this);
  16552. this.name = name;
  16553. this.isRenderTarget = true;
  16554. this._size = size;
  16555. this._generateMipMaps = generateMipMaps;
  16556. this.setFragment(fragment);
  16557. this._fallbackTexture = fallbackTexture;
  16558. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16559. // VBO
  16560. var vertices = [];
  16561. vertices.push(1, 1);
  16562. vertices.push(-1, 1);
  16563. vertices.push(-1, -1);
  16564. vertices.push(1, -1);
  16565. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16566. // Indices
  16567. var indices = [];
  16568. indices.push(0);
  16569. indices.push(1);
  16570. indices.push(2);
  16571. indices.push(0);
  16572. indices.push(2);
  16573. indices.push(3);
  16574. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16575. }
  16576. ProceduralTexture.prototype.reset = function () {
  16577. if (this._effect === undefined) {
  16578. return;
  16579. }
  16580. var engine = this.getScene().getEngine();
  16581. engine._releaseEffect(this._effect);
  16582. };
  16583. ProceduralTexture.prototype.isReady = function () {
  16584. var _this = this;
  16585. var engine = this.getScene().getEngine();
  16586. var shaders;
  16587. if (!this._fragment) {
  16588. return false;
  16589. }
  16590. if (this._fallbackTextureUsed) {
  16591. return true;
  16592. }
  16593. if (this._fragment.fragmentElement !== undefined) {
  16594. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16595. }
  16596. else {
  16597. shaders = { vertex: "procedural", fragment: this._fragment };
  16598. }
  16599. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16600. _this.releaseInternalTexture();
  16601. if (_this._fallbackTexture) {
  16602. _this._texture = _this._fallbackTexture._texture;
  16603. _this._texture.references++;
  16604. }
  16605. _this._fallbackTextureUsed = true;
  16606. });
  16607. return this._effect.isReady();
  16608. };
  16609. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16610. this._currentRefreshId = -1;
  16611. };
  16612. ProceduralTexture.prototype.setFragment = function (fragment) {
  16613. this._fragment = fragment;
  16614. };
  16615. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16616. get: function () {
  16617. return this._refreshRate;
  16618. },
  16619. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16620. set: function (value) {
  16621. this._refreshRate = value;
  16622. this.resetRefreshCounter();
  16623. },
  16624. enumerable: true,
  16625. configurable: true
  16626. });
  16627. ProceduralTexture.prototype._shouldRender = function () {
  16628. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16629. return false;
  16630. }
  16631. if (this._fallbackTextureUsed) {
  16632. return false;
  16633. }
  16634. if (this._currentRefreshId === -1) {
  16635. this._currentRefreshId = 1;
  16636. return true;
  16637. }
  16638. if (this.refreshRate === this._currentRefreshId) {
  16639. this._currentRefreshId = 1;
  16640. return true;
  16641. }
  16642. this._currentRefreshId++;
  16643. return false;
  16644. };
  16645. ProceduralTexture.prototype.getRenderSize = function () {
  16646. return this._size;
  16647. };
  16648. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16649. if (this._fallbackTextureUsed) {
  16650. return;
  16651. }
  16652. this.releaseInternalTexture();
  16653. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16654. };
  16655. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16656. if (this._uniforms.indexOf(uniformName) === -1) {
  16657. this._uniforms.push(uniformName);
  16658. }
  16659. };
  16660. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16661. if (this._samplers.indexOf(name) === -1) {
  16662. this._samplers.push(name);
  16663. }
  16664. this._textures[name] = texture;
  16665. return this;
  16666. };
  16667. ProceduralTexture.prototype.setFloat = function (name, value) {
  16668. this._checkUniform(name);
  16669. this._floats[name] = value;
  16670. return this;
  16671. };
  16672. ProceduralTexture.prototype.setFloats = function (name, value) {
  16673. this._checkUniform(name);
  16674. this._floatsArrays[name] = value;
  16675. return this;
  16676. };
  16677. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16678. this._checkUniform(name);
  16679. this._colors3[name] = value;
  16680. return this;
  16681. };
  16682. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16683. this._checkUniform(name);
  16684. this._colors4[name] = value;
  16685. return this;
  16686. };
  16687. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16688. this._checkUniform(name);
  16689. this._vectors2[name] = value;
  16690. return this;
  16691. };
  16692. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16693. this._checkUniform(name);
  16694. this._vectors3[name] = value;
  16695. return this;
  16696. };
  16697. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16698. this._checkUniform(name);
  16699. this._matrices[name] = value;
  16700. return this;
  16701. };
  16702. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16703. var scene = this.getScene();
  16704. var engine = scene.getEngine();
  16705. engine.bindFramebuffer(this._texture);
  16706. // Clear
  16707. engine.clear(scene.clearColor, true, true);
  16708. // Render
  16709. engine.enableEffect(this._effect);
  16710. engine.setState(false);
  16711. // Texture
  16712. for (var name in this._textures) {
  16713. this._effect.setTexture(name, this._textures[name]);
  16714. }
  16715. // Float
  16716. for (name in this._floats) {
  16717. this._effect.setFloat(name, this._floats[name]);
  16718. }
  16719. // Floats
  16720. for (name in this._floatsArrays) {
  16721. this._effect.setArray(name, this._floatsArrays[name]);
  16722. }
  16723. // Color3
  16724. for (name in this._colors3) {
  16725. this._effect.setColor3(name, this._colors3[name]);
  16726. }
  16727. // Color4
  16728. for (name in this._colors4) {
  16729. var color = this._colors4[name];
  16730. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16731. }
  16732. // Vector2
  16733. for (name in this._vectors2) {
  16734. this._effect.setVector2(name, this._vectors2[name]);
  16735. }
  16736. // Vector3
  16737. for (name in this._vectors3) {
  16738. this._effect.setVector3(name, this._vectors3[name]);
  16739. }
  16740. // Matrix
  16741. for (name in this._matrices) {
  16742. this._effect.setMatrix(name, this._matrices[name]);
  16743. }
  16744. // VBOs
  16745. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16746. // Draw order
  16747. engine.draw(true, 0, 6);
  16748. // Unbind
  16749. engine.unBindFramebuffer(this._texture);
  16750. };
  16751. ProceduralTexture.prototype.clone = function () {
  16752. var textureSize = this.getSize();
  16753. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16754. // Base texture
  16755. newTexture.hasAlpha = this.hasAlpha;
  16756. newTexture.level = this.level;
  16757. // RenderTarget Texture
  16758. newTexture.coordinatesMode = this.coordinatesMode;
  16759. return newTexture;
  16760. };
  16761. ProceduralTexture.prototype.dispose = function () {
  16762. var index = this.getScene()._proceduralTextures.indexOf(this);
  16763. if (index >= 0) {
  16764. this.getScene()._proceduralTextures.splice(index, 1);
  16765. }
  16766. _super.prototype.dispose.call(this);
  16767. };
  16768. return ProceduralTexture;
  16769. })(BABYLON.Texture);
  16770. BABYLON.ProceduralTexture = ProceduralTexture;
  16771. })(BABYLON || (BABYLON = {}));
  16772. var BABYLON;
  16773. (function (BABYLON) {
  16774. var MirrorTexture = (function (_super) {
  16775. __extends(MirrorTexture, _super);
  16776. function MirrorTexture(name, size, scene, generateMipMaps) {
  16777. var _this = this;
  16778. _super.call(this, name, size, scene, generateMipMaps, true);
  16779. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16780. this._transformMatrix = BABYLON.Matrix.Zero();
  16781. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16782. this.onBeforeRender = function () {
  16783. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16784. _this._savedViewMatrix = scene.getViewMatrix();
  16785. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16786. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16787. scene.clipPlane = _this.mirrorPlane;
  16788. scene.getEngine().cullBackFaces = false;
  16789. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  16790. };
  16791. this.onAfterRender = function () {
  16792. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16793. scene.getEngine().cullBackFaces = true;
  16794. scene._mirroredCameraPosition = null;
  16795. delete scene.clipPlane;
  16796. };
  16797. }
  16798. MirrorTexture.prototype.clone = function () {
  16799. var textureSize = this.getSize();
  16800. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16801. // Base texture
  16802. newTexture.hasAlpha = this.hasAlpha;
  16803. newTexture.level = this.level;
  16804. // Mirror Texture
  16805. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16806. newTexture.renderList = this.renderList.slice(0);
  16807. return newTexture;
  16808. };
  16809. return MirrorTexture;
  16810. })(BABYLON.RenderTargetTexture);
  16811. BABYLON.MirrorTexture = MirrorTexture;
  16812. })(BABYLON || (BABYLON = {}));
  16813. var BABYLON;
  16814. (function (BABYLON) {
  16815. var DynamicTexture = (function (_super) {
  16816. __extends(DynamicTexture, _super);
  16817. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16819. _super.call(this, null, scene, !generateMipMaps);
  16820. this.name = name;
  16821. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16822. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16823. this._generateMipMaps = generateMipMaps;
  16824. if (options.getContext) {
  16825. this._canvas = options;
  16826. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16827. }
  16828. else {
  16829. this._canvas = document.createElement("canvas");
  16830. if (options.width) {
  16831. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16832. }
  16833. else {
  16834. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16835. }
  16836. }
  16837. var textureSize = this.getSize();
  16838. this._canvas.width = textureSize.width;
  16839. this._canvas.height = textureSize.height;
  16840. this._context = this._canvas.getContext("2d");
  16841. }
  16842. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16843. get: function () {
  16844. return true;
  16845. },
  16846. enumerable: true,
  16847. configurable: true
  16848. });
  16849. DynamicTexture.prototype.scale = function (ratio) {
  16850. var textureSize = this.getSize();
  16851. textureSize.width *= ratio;
  16852. textureSize.height *= ratio;
  16853. this._canvas.width = textureSize.width;
  16854. this._canvas.height = textureSize.height;
  16855. this.releaseInternalTexture();
  16856. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16857. };
  16858. DynamicTexture.prototype.getContext = function () {
  16859. return this._context;
  16860. };
  16861. DynamicTexture.prototype.clear = function () {
  16862. var size = this.getSize();
  16863. this._context.fillRect(0, 0, size.width, size.height);
  16864. };
  16865. DynamicTexture.prototype.update = function (invertY) {
  16866. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16867. };
  16868. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16869. if (update === void 0) { update = true; }
  16870. var size = this.getSize();
  16871. if (clearColor) {
  16872. this._context.fillStyle = clearColor;
  16873. this._context.fillRect(0, 0, size.width, size.height);
  16874. }
  16875. this._context.font = font;
  16876. if (x === null) {
  16877. var textSize = this._context.measureText(text);
  16878. x = (size.width - textSize.width) / 2;
  16879. }
  16880. this._context.fillStyle = color;
  16881. this._context.fillText(text, x, y);
  16882. if (update) {
  16883. this.update(invertY);
  16884. }
  16885. };
  16886. DynamicTexture.prototype.clone = function () {
  16887. var textureSize = this.getSize();
  16888. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16889. // Base texture
  16890. newTexture.hasAlpha = this.hasAlpha;
  16891. newTexture.level = this.level;
  16892. // Dynamic Texture
  16893. newTexture.wrapU = this.wrapU;
  16894. newTexture.wrapV = this.wrapV;
  16895. return newTexture;
  16896. };
  16897. return DynamicTexture;
  16898. })(BABYLON.Texture);
  16899. BABYLON.DynamicTexture = DynamicTexture;
  16900. })(BABYLON || (BABYLON = {}));
  16901. var BABYLON;
  16902. (function (BABYLON) {
  16903. var VideoTexture = (function (_super) {
  16904. __extends(VideoTexture, _super);
  16905. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16906. var _this = this;
  16907. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16908. if (invertY === void 0) { invertY = false; }
  16909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16910. _super.call(this, null, scene, !generateMipMaps, invertY);
  16911. this._autoLaunch = true;
  16912. this.name = name;
  16913. this.video = document.createElement("video");
  16914. this.video.autoplay = false;
  16915. this.video.loop = true;
  16916. this.video.addEventListener("canplaythrough", function () {
  16917. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  16918. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16919. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16920. }
  16921. else {
  16922. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16923. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16924. generateMipMaps = false;
  16925. }
  16926. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16927. _this._texture.isReady = true;
  16928. });
  16929. urls.forEach(function (url) {
  16930. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16931. var source = document.createElement("source");
  16932. source.src = url;
  16933. _this.video.appendChild(source);
  16934. });
  16935. this._lastUpdate = BABYLON.Tools.Now;
  16936. }
  16937. VideoTexture.prototype.update = function () {
  16938. if (this._autoLaunch) {
  16939. this._autoLaunch = false;
  16940. this.video.play();
  16941. }
  16942. var now = BABYLON.Tools.Now;
  16943. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16944. return false;
  16945. }
  16946. this._lastUpdate = now;
  16947. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16948. return true;
  16949. };
  16950. return VideoTexture;
  16951. })(BABYLON.Texture);
  16952. BABYLON.VideoTexture = VideoTexture;
  16953. })(BABYLON || (BABYLON = {}));
  16954. var BABYLON;
  16955. (function (BABYLON) {
  16956. var CustomProceduralTexture = (function (_super) {
  16957. __extends(CustomProceduralTexture, _super);
  16958. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16959. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16960. this._animate = true;
  16961. this._time = 0;
  16962. this._texturePath = texturePath;
  16963. //Try to load json
  16964. this.loadJson(texturePath);
  16965. this.refreshRate = 1;
  16966. }
  16967. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16968. var _this = this;
  16969. var that = this;
  16970. function noConfigFile() {
  16971. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16972. try {
  16973. that.setFragment(that._texturePath);
  16974. }
  16975. catch (ex) {
  16976. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16977. }
  16978. }
  16979. var configFileUrl = jsonUrl + "/config.json";
  16980. var xhr = new XMLHttpRequest();
  16981. xhr.open("GET", configFileUrl, true);
  16982. xhr.addEventListener("load", function () {
  16983. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16984. try {
  16985. _this._config = JSON.parse(xhr.response);
  16986. _this.updateShaderUniforms();
  16987. _this.updateTextures();
  16988. _this.setFragment(_this._texturePath + "/custom");
  16989. _this._animate = _this._config.animate;
  16990. _this.refreshRate = _this._config.refreshrate;
  16991. }
  16992. catch (ex) {
  16993. noConfigFile();
  16994. }
  16995. }
  16996. else {
  16997. noConfigFile();
  16998. }
  16999. }, false);
  17000. xhr.addEventListener("error", function () {
  17001. noConfigFile();
  17002. }, false);
  17003. try {
  17004. xhr.send();
  17005. }
  17006. catch (ex) {
  17007. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17008. }
  17009. };
  17010. CustomProceduralTexture.prototype.isReady = function () {
  17011. if (!_super.prototype.isReady.call(this)) {
  17012. return false;
  17013. }
  17014. for (var name in this._textures) {
  17015. var texture = this._textures[name];
  17016. if (!texture.isReady()) {
  17017. return false;
  17018. }
  17019. }
  17020. return true;
  17021. };
  17022. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17023. if (this._animate) {
  17024. this._time += this.getScene().getAnimationRatio() * 0.03;
  17025. this.updateShaderUniforms();
  17026. }
  17027. _super.prototype.render.call(this, useCameraPostProcess);
  17028. };
  17029. CustomProceduralTexture.prototype.updateTextures = function () {
  17030. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17031. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17032. }
  17033. };
  17034. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17035. if (this._config) {
  17036. for (var j = 0; j < this._config.uniforms.length; j++) {
  17037. var uniform = this._config.uniforms[j];
  17038. switch (uniform.type) {
  17039. case "float":
  17040. this.setFloat(uniform.name, uniform.value);
  17041. break;
  17042. case "color3":
  17043. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17044. break;
  17045. case "color4":
  17046. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17047. break;
  17048. case "vector2":
  17049. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17050. break;
  17051. case "vector3":
  17052. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17053. break;
  17054. }
  17055. }
  17056. }
  17057. this.setFloat("time", this._time);
  17058. };
  17059. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17060. get: function () {
  17061. return this._animate;
  17062. },
  17063. set: function (value) {
  17064. this._animate = value;
  17065. },
  17066. enumerable: true,
  17067. configurable: true
  17068. });
  17069. return CustomProceduralTexture;
  17070. })(BABYLON.ProceduralTexture);
  17071. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17072. })(BABYLON || (BABYLON = {}));
  17073. var BABYLON;
  17074. (function (BABYLON) {
  17075. var WoodProceduralTexture = (function (_super) {
  17076. __extends(WoodProceduralTexture, _super);
  17077. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17078. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17079. this._ampScale = 100.0;
  17080. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17081. this.updateShaderUniforms();
  17082. this.refreshRate = 0;
  17083. }
  17084. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17085. this.setFloat("ampScale", this._ampScale);
  17086. this.setColor3("woodColor", this._woodColor);
  17087. };
  17088. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17089. get: function () {
  17090. return this._ampScale;
  17091. },
  17092. set: function (value) {
  17093. this._ampScale = value;
  17094. this.updateShaderUniforms();
  17095. },
  17096. enumerable: true,
  17097. configurable: true
  17098. });
  17099. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17100. get: function () {
  17101. return this._woodColor;
  17102. },
  17103. set: function (value) {
  17104. this._woodColor = value;
  17105. this.updateShaderUniforms();
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. return WoodProceduralTexture;
  17111. })(BABYLON.ProceduralTexture);
  17112. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17113. var FireProceduralTexture = (function (_super) {
  17114. __extends(FireProceduralTexture, _super);
  17115. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17116. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17117. this._time = 0.0;
  17118. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17119. this._autoGenerateTime = true;
  17120. this._alphaThreshold = 0.5;
  17121. this._fireColors = FireProceduralTexture.RedFireColors;
  17122. this.updateShaderUniforms();
  17123. this.refreshRate = 1;
  17124. }
  17125. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17126. this.setFloat("time", this._time);
  17127. this.setVector2("speed", this._speed);
  17128. this.setColor3("c1", this._fireColors[0]);
  17129. this.setColor3("c2", this._fireColors[1]);
  17130. this.setColor3("c3", this._fireColors[2]);
  17131. this.setColor3("c4", this._fireColors[3]);
  17132. this.setColor3("c5", this._fireColors[4]);
  17133. this.setColor3("c6", this._fireColors[5]);
  17134. this.setFloat("alphaThreshold", this._alphaThreshold);
  17135. };
  17136. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17137. if (this._autoGenerateTime) {
  17138. this._time += this.getScene().getAnimationRatio() * 0.03;
  17139. this.updateShaderUniforms();
  17140. }
  17141. _super.prototype.render.call(this, useCameraPostProcess);
  17142. };
  17143. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17144. get: function () {
  17145. return [
  17146. new BABYLON.Color3(0.5, 0.0, 1.0),
  17147. new BABYLON.Color3(0.9, 0.0, 1.0),
  17148. new BABYLON.Color3(0.2, 0.0, 1.0),
  17149. new BABYLON.Color3(1.0, 0.9, 1.0),
  17150. new BABYLON.Color3(0.1, 0.1, 1.0),
  17151. new BABYLON.Color3(0.9, 0.9, 1.0)
  17152. ];
  17153. },
  17154. enumerable: true,
  17155. configurable: true
  17156. });
  17157. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17158. get: function () {
  17159. return [
  17160. new BABYLON.Color3(0.5, 1.0, 0.0),
  17161. new BABYLON.Color3(0.5, 1.0, 0.0),
  17162. new BABYLON.Color3(0.3, 0.4, 0.0),
  17163. new BABYLON.Color3(0.5, 1.0, 0.0),
  17164. new BABYLON.Color3(0.2, 0.0, 0.0),
  17165. new BABYLON.Color3(0.5, 1.0, 0.0)
  17166. ];
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17172. get: function () {
  17173. return [
  17174. new BABYLON.Color3(0.5, 0.0, 0.1),
  17175. new BABYLON.Color3(0.9, 0.0, 0.0),
  17176. new BABYLON.Color3(0.2, 0.0, 0.0),
  17177. new BABYLON.Color3(1.0, 0.9, 0.0),
  17178. new BABYLON.Color3(0.1, 0.1, 0.1),
  17179. new BABYLON.Color3(0.9, 0.9, 0.9)
  17180. ];
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17186. get: function () {
  17187. return [
  17188. new BABYLON.Color3(0.1, 0.0, 0.5),
  17189. new BABYLON.Color3(0.0, 0.0, 0.5),
  17190. new BABYLON.Color3(0.1, 0.0, 0.2),
  17191. new BABYLON.Color3(0.0, 0.0, 1.0),
  17192. new BABYLON.Color3(0.1, 0.2, 0.3),
  17193. new BABYLON.Color3(0.0, 0.2, 0.9)
  17194. ];
  17195. },
  17196. enumerable: true,
  17197. configurable: true
  17198. });
  17199. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17200. get: function () {
  17201. return this._fireColors;
  17202. },
  17203. set: function (value) {
  17204. this._fireColors = value;
  17205. this.updateShaderUniforms();
  17206. },
  17207. enumerable: true,
  17208. configurable: true
  17209. });
  17210. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17211. get: function () {
  17212. return this._time;
  17213. },
  17214. set: function (value) {
  17215. this._time = value;
  17216. this.updateShaderUniforms();
  17217. },
  17218. enumerable: true,
  17219. configurable: true
  17220. });
  17221. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17222. get: function () {
  17223. return this._speed;
  17224. },
  17225. set: function (value) {
  17226. this._speed = value;
  17227. this.updateShaderUniforms();
  17228. },
  17229. enumerable: true,
  17230. configurable: true
  17231. });
  17232. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17233. get: function () {
  17234. return this._alphaThreshold;
  17235. },
  17236. set: function (value) {
  17237. this._alphaThreshold = value;
  17238. this.updateShaderUniforms();
  17239. },
  17240. enumerable: true,
  17241. configurable: true
  17242. });
  17243. return FireProceduralTexture;
  17244. })(BABYLON.ProceduralTexture);
  17245. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17246. var CloudProceduralTexture = (function (_super) {
  17247. __extends(CloudProceduralTexture, _super);
  17248. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17249. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17250. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17251. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17252. this.updateShaderUniforms();
  17253. this.refreshRate = 0;
  17254. }
  17255. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17256. this.setColor4("skyColor", this._skyColor);
  17257. this.setColor4("cloudColor", this._cloudColor);
  17258. };
  17259. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17260. get: function () {
  17261. return this._skyColor;
  17262. },
  17263. set: function (value) {
  17264. this._skyColor = value;
  17265. this.updateShaderUniforms();
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17271. get: function () {
  17272. return this._cloudColor;
  17273. },
  17274. set: function (value) {
  17275. this._cloudColor = value;
  17276. this.updateShaderUniforms();
  17277. },
  17278. enumerable: true,
  17279. configurable: true
  17280. });
  17281. return CloudProceduralTexture;
  17282. })(BABYLON.ProceduralTexture);
  17283. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17284. var GrassProceduralTexture = (function (_super) {
  17285. __extends(GrassProceduralTexture, _super);
  17286. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17287. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17288. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17289. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17290. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17291. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17292. this._grassColors = [
  17293. new BABYLON.Color3(0.29, 0.38, 0.02),
  17294. new BABYLON.Color3(0.36, 0.49, 0.09),
  17295. new BABYLON.Color3(0.51, 0.6, 0.28)
  17296. ];
  17297. this.updateShaderUniforms();
  17298. this.refreshRate = 0;
  17299. }
  17300. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17301. this.setColor3("herb1Color", this._grassColors[0]);
  17302. this.setColor3("herb2Color", this._grassColors[1]);
  17303. this.setColor3("herb3Color", this._grassColors[2]);
  17304. this.setColor3("groundColor", this._groundColor);
  17305. };
  17306. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17307. get: function () {
  17308. return this._grassColors;
  17309. },
  17310. set: function (value) {
  17311. this._grassColors = value;
  17312. this.updateShaderUniforms();
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17318. get: function () {
  17319. return this._groundColor;
  17320. },
  17321. set: function (value) {
  17322. this.groundColor = value;
  17323. this.updateShaderUniforms();
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. return GrassProceduralTexture;
  17329. })(BABYLON.ProceduralTexture);
  17330. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17331. var RoadProceduralTexture = (function (_super) {
  17332. __extends(RoadProceduralTexture, _super);
  17333. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17334. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17335. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17336. this.updateShaderUniforms();
  17337. this.refreshRate = 0;
  17338. }
  17339. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17340. this.setColor3("roadColor", this._roadColor);
  17341. };
  17342. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17343. get: function () {
  17344. return this._roadColor;
  17345. },
  17346. set: function (value) {
  17347. this._roadColor = value;
  17348. this.updateShaderUniforms();
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. return RoadProceduralTexture;
  17354. })(BABYLON.ProceduralTexture);
  17355. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17356. var BrickProceduralTexture = (function (_super) {
  17357. __extends(BrickProceduralTexture, _super);
  17358. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17359. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17360. this._numberOfBricksHeight = 15;
  17361. this._numberOfBricksWidth = 5;
  17362. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17363. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17364. this.updateShaderUniforms();
  17365. this.refreshRate = 0;
  17366. }
  17367. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17368. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17369. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17370. this.setColor3("brickColor", this._brickColor);
  17371. this.setColor3("jointColor", this._jointColor);
  17372. };
  17373. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17374. get: function () {
  17375. return this._numberOfBricksHeight;
  17376. },
  17377. set: function (value) {
  17378. this._numberOfBricksHeight = value;
  17379. this.updateShaderUniforms();
  17380. },
  17381. enumerable: true,
  17382. configurable: true
  17383. });
  17384. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17385. get: function () {
  17386. return this._numberOfBricksWidth;
  17387. },
  17388. set: function (value) {
  17389. this._numberOfBricksWidth = value;
  17390. this.updateShaderUniforms();
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17396. get: function () {
  17397. return this._jointColor;
  17398. },
  17399. set: function (value) {
  17400. this._jointColor = value;
  17401. this.updateShaderUniforms();
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17407. get: function () {
  17408. return this._brickColor;
  17409. },
  17410. set: function (value) {
  17411. this._brickColor = value;
  17412. this.updateShaderUniforms();
  17413. },
  17414. enumerable: true,
  17415. configurable: true
  17416. });
  17417. return BrickProceduralTexture;
  17418. })(BABYLON.ProceduralTexture);
  17419. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17420. var MarbleProceduralTexture = (function (_super) {
  17421. __extends(MarbleProceduralTexture, _super);
  17422. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17423. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17424. this._numberOfTilesHeight = 3;
  17425. this._numberOfTilesWidth = 3;
  17426. this._amplitude = 9.0;
  17427. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17428. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17429. this.updateShaderUniforms();
  17430. this.refreshRate = 0;
  17431. }
  17432. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17433. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17434. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17435. this.setFloat("amplitude", this._amplitude);
  17436. this.setColor3("marbleColor", this._marbleColor);
  17437. this.setColor3("jointColor", this._jointColor);
  17438. };
  17439. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17440. get: function () {
  17441. return this._numberOfTilesHeight;
  17442. },
  17443. set: function (value) {
  17444. this._numberOfTilesHeight = value;
  17445. this.updateShaderUniforms();
  17446. },
  17447. enumerable: true,
  17448. configurable: true
  17449. });
  17450. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17451. get: function () {
  17452. return this._numberOfTilesWidth;
  17453. },
  17454. set: function (value) {
  17455. this._numberOfTilesWidth = value;
  17456. this.updateShaderUniforms();
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17462. get: function () {
  17463. return this._jointColor;
  17464. },
  17465. set: function (value) {
  17466. this._jointColor = value;
  17467. this.updateShaderUniforms();
  17468. },
  17469. enumerable: true,
  17470. configurable: true
  17471. });
  17472. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17473. get: function () {
  17474. return this._marbleColor;
  17475. },
  17476. set: function (value) {
  17477. this._marbleColor = value;
  17478. this.updateShaderUniforms();
  17479. },
  17480. enumerable: true,
  17481. configurable: true
  17482. });
  17483. return MarbleProceduralTexture;
  17484. })(BABYLON.ProceduralTexture);
  17485. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17486. })(BABYLON || (BABYLON = {}));
  17487. var BABYLON;
  17488. (function (BABYLON) {
  17489. var EffectFallbacks = (function () {
  17490. function EffectFallbacks() {
  17491. this._defines = {};
  17492. this._currentRank = 32;
  17493. this._maxRank = -1;
  17494. }
  17495. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17496. if (!this._defines[rank]) {
  17497. if (rank < this._currentRank) {
  17498. this._currentRank = rank;
  17499. }
  17500. if (rank > this._maxRank) {
  17501. this._maxRank = rank;
  17502. }
  17503. this._defines[rank] = new Array();
  17504. }
  17505. this._defines[rank].push(define);
  17506. };
  17507. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17508. get: function () {
  17509. return this._currentRank <= this._maxRank;
  17510. },
  17511. enumerable: true,
  17512. configurable: true
  17513. });
  17514. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17515. var currentFallbacks = this._defines[this._currentRank];
  17516. for (var index = 0; index < currentFallbacks.length; index++) {
  17517. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17518. }
  17519. this._currentRank++;
  17520. return currentDefines;
  17521. };
  17522. return EffectFallbacks;
  17523. })();
  17524. BABYLON.EffectFallbacks = EffectFallbacks;
  17525. var Effect = (function () {
  17526. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17527. var _this = this;
  17528. this._isReady = false;
  17529. this._compilationError = "";
  17530. this._valueCache = [];
  17531. this._engine = engine;
  17532. this.name = baseName;
  17533. this.defines = defines;
  17534. this._uniformsNames = uniformsNames.concat(samplers);
  17535. this._samplers = samplers;
  17536. this._attributesNames = attributesNames;
  17537. this.onError = onError;
  17538. this.onCompiled = onCompiled;
  17539. var vertexSource;
  17540. var fragmentSource;
  17541. if (baseName.vertexElement) {
  17542. vertexSource = document.getElementById(baseName.vertexElement);
  17543. if (!vertexSource) {
  17544. vertexSource = baseName.vertexElement;
  17545. }
  17546. }
  17547. else {
  17548. vertexSource = baseName.vertex || baseName;
  17549. }
  17550. if (baseName.fragmentElement) {
  17551. fragmentSource = document.getElementById(baseName.fragmentElement);
  17552. if (!fragmentSource) {
  17553. fragmentSource = baseName.fragmentElement;
  17554. }
  17555. }
  17556. else {
  17557. fragmentSource = baseName.fragment || baseName;
  17558. }
  17559. this._loadVertexShader(vertexSource, function (vertexCode) {
  17560. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17561. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17562. });
  17563. });
  17564. }
  17565. // Properties
  17566. Effect.prototype.isReady = function () {
  17567. return this._isReady;
  17568. };
  17569. Effect.prototype.getProgram = function () {
  17570. return this._program;
  17571. };
  17572. Effect.prototype.getAttributesNames = function () {
  17573. return this._attributesNames;
  17574. };
  17575. Effect.prototype.getAttributeLocation = function (index) {
  17576. return this._attributes[index];
  17577. };
  17578. Effect.prototype.getAttributeLocationByName = function (name) {
  17579. var index = this._attributesNames.indexOf(name);
  17580. return this._attributes[index];
  17581. };
  17582. Effect.prototype.getAttributesCount = function () {
  17583. return this._attributes.length;
  17584. };
  17585. Effect.prototype.getUniformIndex = function (uniformName) {
  17586. return this._uniformsNames.indexOf(uniformName);
  17587. };
  17588. Effect.prototype.getUniform = function (uniformName) {
  17589. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17590. };
  17591. Effect.prototype.getSamplers = function () {
  17592. return this._samplers;
  17593. };
  17594. Effect.prototype.getCompilationError = function () {
  17595. return this._compilationError;
  17596. };
  17597. // Methods
  17598. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17599. // DOM element ?
  17600. if (vertex instanceof HTMLElement) {
  17601. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17602. callback(vertexCode);
  17603. return;
  17604. }
  17605. // Is in local store ?
  17606. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17607. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17608. return;
  17609. }
  17610. var vertexShaderUrl;
  17611. if (vertex[0] === "." || vertex[0] === "/") {
  17612. vertexShaderUrl = vertex;
  17613. }
  17614. else {
  17615. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17616. }
  17617. // Vertex shader
  17618. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17619. };
  17620. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17621. // DOM element ?
  17622. if (fragment instanceof HTMLElement) {
  17623. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17624. callback(fragmentCode);
  17625. return;
  17626. }
  17627. // Is in local store ?
  17628. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17629. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17630. return;
  17631. }
  17632. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17633. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17634. return;
  17635. }
  17636. var fragmentShaderUrl;
  17637. if (fragment[0] === "." || fragment[0] === "/") {
  17638. fragmentShaderUrl = fragment;
  17639. }
  17640. else {
  17641. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17642. }
  17643. // Fragment shader
  17644. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17645. };
  17646. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17647. try {
  17648. var engine = this._engine;
  17649. if (!engine.getCaps().highPrecisionShaderSupported) {
  17650. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17651. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17652. }
  17653. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17654. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17655. this._attributes = engine.getAttributes(this._program, attributesNames);
  17656. for (var index = 0; index < this._samplers.length; index++) {
  17657. var sampler = this.getUniform(this._samplers[index]);
  17658. if (sampler == null) {
  17659. this._samplers.splice(index, 1);
  17660. index--;
  17661. }
  17662. }
  17663. engine.bindSamplers(this);
  17664. this._isReady = true;
  17665. if (this.onCompiled) {
  17666. this.onCompiled(this);
  17667. }
  17668. }
  17669. catch (e) {
  17670. // Is it a problem with precision?
  17671. if (e.message.indexOf("highp") !== -1) {
  17672. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17673. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17674. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17675. return;
  17676. }
  17677. // Let's go through fallbacks then
  17678. if (fallbacks && fallbacks.isMoreFallbacks) {
  17679. defines = fallbacks.reduce(defines);
  17680. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17681. }
  17682. else {
  17683. BABYLON.Tools.Error("Unable to compile effect: ");
  17684. if (this.name.vertexElement) {
  17685. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17686. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17687. }
  17688. else if (this.name.vertex) {
  17689. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17690. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17691. }
  17692. else {
  17693. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17694. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17695. }
  17696. BABYLON.Tools.Error("Defines: " + defines);
  17697. BABYLON.Tools.Error("Error: " + e.message);
  17698. this._compilationError = e.message;
  17699. if (this.onError) {
  17700. this.onError(this, this._compilationError);
  17701. }
  17702. }
  17703. }
  17704. };
  17705. Effect.prototype._bindTexture = function (channel, texture) {
  17706. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17707. };
  17708. Effect.prototype.setTexture = function (channel, texture) {
  17709. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17710. };
  17711. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17712. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17713. };
  17714. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17715. if (!this._valueCache[uniformName]) {
  17716. this._valueCache[uniformName] = new BABYLON.Matrix();
  17717. }
  17718. for (var index = 0; index < 16; index++) {
  17719. this._valueCache[uniformName].m[index] = matrix.m[index];
  17720. }
  17721. };
  17722. ;
  17723. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17724. if (!this._valueCache[uniformName]) {
  17725. this._valueCache[uniformName] = [x, y];
  17726. return;
  17727. }
  17728. this._valueCache[uniformName][0] = x;
  17729. this._valueCache[uniformName][1] = y;
  17730. };
  17731. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17732. if (!this._valueCache[uniformName]) {
  17733. this._valueCache[uniformName] = [x, y, z];
  17734. return;
  17735. }
  17736. this._valueCache[uniformName][0] = x;
  17737. this._valueCache[uniformName][1] = y;
  17738. this._valueCache[uniformName][2] = z;
  17739. };
  17740. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17741. if (!this._valueCache[uniformName]) {
  17742. this._valueCache[uniformName] = [x, y, z, w];
  17743. return;
  17744. }
  17745. this._valueCache[uniformName][0] = x;
  17746. this._valueCache[uniformName][1] = y;
  17747. this._valueCache[uniformName][2] = z;
  17748. this._valueCache[uniformName][3] = w;
  17749. };
  17750. Effect.prototype.setArray = function (uniformName, array) {
  17751. this._engine.setArray(this.getUniform(uniformName), array);
  17752. return this;
  17753. };
  17754. Effect.prototype.setArray2 = function (uniformName, array) {
  17755. this._engine.setArray2(this.getUniform(uniformName), array);
  17756. return this;
  17757. };
  17758. Effect.prototype.setArray3 = function (uniformName, array) {
  17759. this._engine.setArray3(this.getUniform(uniformName), array);
  17760. return this;
  17761. };
  17762. Effect.prototype.setArray4 = function (uniformName, array) {
  17763. this._engine.setArray4(this.getUniform(uniformName), array);
  17764. return this;
  17765. };
  17766. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17767. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17768. return this;
  17769. };
  17770. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17771. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17772. return this;
  17773. this._cacheMatrix(uniformName, matrix);
  17774. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17775. return this;
  17776. };
  17777. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  17778. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  17779. return this;
  17780. };
  17781. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  17782. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  17783. return this;
  17784. };
  17785. Effect.prototype.setFloat = function (uniformName, value) {
  17786. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17787. return this;
  17788. this._valueCache[uniformName] = value;
  17789. this._engine.setFloat(this.getUniform(uniformName), value);
  17790. return this;
  17791. };
  17792. Effect.prototype.setBool = function (uniformName, bool) {
  17793. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17794. return this;
  17795. this._valueCache[uniformName] = bool;
  17796. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17797. return this;
  17798. };
  17799. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17800. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17801. return this;
  17802. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17803. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17804. return this;
  17805. };
  17806. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17807. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17808. return this;
  17809. this._cacheFloat2(uniformName, x, y);
  17810. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17811. return this;
  17812. };
  17813. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17814. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17815. return this;
  17816. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17817. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17818. return this;
  17819. };
  17820. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17821. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17822. return this;
  17823. this._cacheFloat3(uniformName, x, y, z);
  17824. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17825. return this;
  17826. };
  17827. Effect.prototype.setVector4 = function (uniformName, vector4) {
  17828. 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)
  17829. return this;
  17830. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  17831. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  17832. return this;
  17833. };
  17834. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17835. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17836. return this;
  17837. this._cacheFloat4(uniformName, x, y, z, w);
  17838. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17839. return this;
  17840. };
  17841. Effect.prototype.setColor3 = function (uniformName, color3) {
  17842. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17843. return this;
  17844. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17845. this._engine.setColor3(this.getUniform(uniformName), color3);
  17846. return this;
  17847. };
  17848. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17849. 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)
  17850. return this;
  17851. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17852. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17853. return this;
  17854. };
  17855. // Statics
  17856. Effect.ShadersStore = {};
  17857. return Effect;
  17858. })();
  17859. BABYLON.Effect = Effect;
  17860. })(BABYLON || (BABYLON = {}));
  17861. var BABYLON;
  17862. (function (BABYLON) {
  17863. var MaterialDefines = (function () {
  17864. function MaterialDefines() {
  17865. }
  17866. MaterialDefines.prototype.isEqual = function (other) {
  17867. for (var index = 0; index < this._keys.length; index++) {
  17868. var prop = this._keys[index];
  17869. if (this[prop] !== other[prop]) {
  17870. return false;
  17871. }
  17872. }
  17873. return true;
  17874. };
  17875. MaterialDefines.prototype.cloneTo = function (other) {
  17876. for (var index = 0; index < this._keys.length; index++) {
  17877. var prop = this._keys[index];
  17878. other[prop] = this[prop];
  17879. }
  17880. };
  17881. MaterialDefines.prototype.reset = function () {
  17882. for (var index = 0; index < this._keys.length; index++) {
  17883. var prop = this._keys[index];
  17884. if (prop === "BonesPerMesh") {
  17885. this[prop] = 0;
  17886. continue;
  17887. }
  17888. this[prop] = false;
  17889. }
  17890. };
  17891. MaterialDefines.prototype.toString = function () {
  17892. var result = "";
  17893. for (var index = 0; index < this._keys.length; index++) {
  17894. var prop = this._keys[index];
  17895. if (prop === "BonesPerMesh" && this[prop] > 0) {
  17896. result += "#define BonesPerMesh " + this[prop] + "\n";
  17897. continue;
  17898. }
  17899. if (this[prop]) {
  17900. result += "#define " + prop + "\n";
  17901. }
  17902. }
  17903. return result;
  17904. };
  17905. return MaterialDefines;
  17906. })();
  17907. BABYLON.MaterialDefines = MaterialDefines;
  17908. var Material = (function () {
  17909. function Material(name, scene, doNotAdd) {
  17910. this.name = name;
  17911. this.checkReadyOnEveryCall = false;
  17912. this.checkReadyOnlyOnce = false;
  17913. this.state = "";
  17914. this.alpha = 1.0;
  17915. this.backFaceCulling = true;
  17916. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  17917. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  17918. this.disableDepthWrite = false;
  17919. this.fogEnabled = true;
  17920. this._wasPreviouslyReady = false;
  17921. this._fillMode = Material.TriangleFillMode;
  17922. this.pointSize = 1.0;
  17923. this.zOffset = 0;
  17924. this.id = name;
  17925. this._scene = scene;
  17926. if (!doNotAdd) {
  17927. scene.materials.push(this);
  17928. }
  17929. }
  17930. Object.defineProperty(Material, "TriangleFillMode", {
  17931. get: function () {
  17932. return Material._TriangleFillMode;
  17933. },
  17934. enumerable: true,
  17935. configurable: true
  17936. });
  17937. Object.defineProperty(Material, "WireFrameFillMode", {
  17938. get: function () {
  17939. return Material._WireFrameFillMode;
  17940. },
  17941. enumerable: true,
  17942. configurable: true
  17943. });
  17944. Object.defineProperty(Material, "PointFillMode", {
  17945. get: function () {
  17946. return Material._PointFillMode;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  17952. get: function () {
  17953. return Material._ClockWiseSideOrientation;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  17959. get: function () {
  17960. return Material._CounterClockWiseSideOrientation;
  17961. },
  17962. enumerable: true,
  17963. configurable: true
  17964. });
  17965. Object.defineProperty(Material.prototype, "wireframe", {
  17966. get: function () {
  17967. return this._fillMode === Material.WireFrameFillMode;
  17968. },
  17969. set: function (value) {
  17970. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17971. },
  17972. enumerable: true,
  17973. configurable: true
  17974. });
  17975. Object.defineProperty(Material.prototype, "pointsCloud", {
  17976. get: function () {
  17977. return this._fillMode === Material.PointFillMode;
  17978. },
  17979. set: function (value) {
  17980. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. Object.defineProperty(Material.prototype, "fillMode", {
  17986. get: function () {
  17987. return this._fillMode;
  17988. },
  17989. set: function (value) {
  17990. this._fillMode = value;
  17991. },
  17992. enumerable: true,
  17993. configurable: true
  17994. });
  17995. Material.prototype.isReady = function (mesh, useInstances) {
  17996. return true;
  17997. };
  17998. Material.prototype.getEffect = function () {
  17999. return this._effect;
  18000. };
  18001. Material.prototype.getScene = function () {
  18002. return this._scene;
  18003. };
  18004. Material.prototype.needAlphaBlending = function () {
  18005. return (this.alpha < 1.0);
  18006. };
  18007. Material.prototype.needAlphaTesting = function () {
  18008. return false;
  18009. };
  18010. Material.prototype.getAlphaTestTexture = function () {
  18011. return null;
  18012. };
  18013. Material.prototype.trackCreation = function (onCompiled, onError) {
  18014. };
  18015. Material.prototype._preBind = function () {
  18016. var engine = this._scene.getEngine();
  18017. engine.enableEffect(this._effect);
  18018. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18019. };
  18020. Material.prototype.bind = function (world, mesh) {
  18021. this._scene._cachedMaterial = this;
  18022. if (this.onBind) {
  18023. this.onBind(this, mesh);
  18024. }
  18025. if (this.disableDepthWrite) {
  18026. var engine = this._scene.getEngine();
  18027. this._cachedDepthWriteState = engine.getDepthWrite();
  18028. engine.setDepthWrite(false);
  18029. }
  18030. };
  18031. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18032. };
  18033. Material.prototype.unbind = function () {
  18034. if (this.disableDepthWrite) {
  18035. var engine = this._scene.getEngine();
  18036. engine.setDepthWrite(this._cachedDepthWriteState);
  18037. }
  18038. };
  18039. Material.prototype.clone = function (name) {
  18040. return null;
  18041. };
  18042. Material.prototype.getBindedMeshes = function () {
  18043. var result = new Array();
  18044. for (var index = 0; index < this._scene.meshes.length; index++) {
  18045. var mesh = this._scene.meshes[index];
  18046. if (mesh.material === this) {
  18047. result.push(mesh);
  18048. }
  18049. }
  18050. return result;
  18051. };
  18052. Material.prototype.dispose = function (forceDisposeEffect) {
  18053. // Remove from scene
  18054. var index = this._scene.materials.indexOf(this);
  18055. if (index >= 0) {
  18056. this._scene.materials.splice(index, 1);
  18057. }
  18058. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18059. if (forceDisposeEffect && this._effect) {
  18060. this._scene.getEngine()._releaseEffect(this._effect);
  18061. this._effect = null;
  18062. }
  18063. // Remove from meshes
  18064. for (index = 0; index < this._scene.meshes.length; index++) {
  18065. var mesh = this._scene.meshes[index];
  18066. if (mesh.material === this) {
  18067. mesh.material = null;
  18068. }
  18069. }
  18070. // Callback
  18071. if (this.onDispose) {
  18072. this.onDispose();
  18073. }
  18074. };
  18075. Material.prototype.copyTo = function (other) {
  18076. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18077. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18078. other.alpha = this.alpha;
  18079. other.fillMode = this.fillMode;
  18080. other.backFaceCulling = this.backFaceCulling;
  18081. other.wireframe = this.wireframe;
  18082. other.fogEnabled = this.fogEnabled;
  18083. other.wireframe = this.wireframe;
  18084. other.zOffset = this.zOffset;
  18085. other.alphaMode = this.alphaMode;
  18086. other.sideOrientation = this.sideOrientation;
  18087. other.disableDepthWrite = this.disableDepthWrite;
  18088. other.pointSize = this.pointSize;
  18089. other.pointsCloud = this.pointsCloud;
  18090. };
  18091. Material._TriangleFillMode = 0;
  18092. Material._WireFrameFillMode = 1;
  18093. Material._PointFillMode = 2;
  18094. Material._ClockWiseSideOrientation = 0;
  18095. Material._CounterClockWiseSideOrientation = 1;
  18096. return Material;
  18097. })();
  18098. BABYLON.Material = Material;
  18099. })(BABYLON || (BABYLON = {}));
  18100. var BABYLON;
  18101. (function (BABYLON) {
  18102. var maxSimultaneousLights = 4;
  18103. var FresnelParameters = (function () {
  18104. function FresnelParameters() {
  18105. this.isEnabled = true;
  18106. this.leftColor = BABYLON.Color3.White();
  18107. this.rightColor = BABYLON.Color3.Black();
  18108. this.bias = 0;
  18109. this.power = 1;
  18110. }
  18111. FresnelParameters.prototype.clone = function () {
  18112. var newFresnelParameters = new FresnelParameters();
  18113. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18114. return new FresnelParameters;
  18115. };
  18116. return FresnelParameters;
  18117. })();
  18118. BABYLON.FresnelParameters = FresnelParameters;
  18119. var StandardMaterialDefines = (function (_super) {
  18120. __extends(StandardMaterialDefines, _super);
  18121. function StandardMaterialDefines() {
  18122. _super.call(this);
  18123. this.DIFFUSE = false;
  18124. this.AMBIENT = false;
  18125. this.OPACITY = false;
  18126. this.OPACITYRGB = false;
  18127. this.REFLECTION = false;
  18128. this.EMISSIVE = false;
  18129. this.SPECULAR = false;
  18130. this.BUMP = false;
  18131. this.SPECULAROVERALPHA = false;
  18132. this.CLIPPLANE = false;
  18133. this.ALPHATEST = false;
  18134. this.ALPHAFROMDIFFUSE = false;
  18135. this.POINTSIZE = false;
  18136. this.FOG = false;
  18137. this.LIGHT0 = false;
  18138. this.LIGHT1 = false;
  18139. this.LIGHT2 = false;
  18140. this.LIGHT3 = false;
  18141. this.SPOTLIGHT0 = false;
  18142. this.SPOTLIGHT1 = false;
  18143. this.SPOTLIGHT2 = false;
  18144. this.SPOTLIGHT3 = false;
  18145. this.HEMILIGHT0 = false;
  18146. this.HEMILIGHT1 = false;
  18147. this.HEMILIGHT2 = false;
  18148. this.HEMILIGHT3 = false;
  18149. this.POINTDIRLIGHT0 = false;
  18150. this.POINTDIRLIGHT1 = false;
  18151. this.POINTDIRLIGHT2 = false;
  18152. this.POINTDIRLIGHT3 = false;
  18153. this.SPECULARTERM = false;
  18154. this.SHADOW0 = false;
  18155. this.SHADOW1 = false;
  18156. this.SHADOW2 = false;
  18157. this.SHADOW3 = false;
  18158. this.SHADOWS = false;
  18159. this.SHADOWVSM0 = false;
  18160. this.SHADOWVSM1 = false;
  18161. this.SHADOWVSM2 = false;
  18162. this.SHADOWVSM3 = false;
  18163. this.SHADOWPCF0 = false;
  18164. this.SHADOWPCF1 = false;
  18165. this.SHADOWPCF2 = false;
  18166. this.SHADOWPCF3 = false;
  18167. this.DIFFUSEFRESNEL = false;
  18168. this.OPACITYFRESNEL = false;
  18169. this.REFLECTIONFRESNEL = false;
  18170. this.EMISSIVEFRESNEL = false;
  18171. this.FRESNEL = false;
  18172. this.NORMAL = false;
  18173. this.UV1 = false;
  18174. this.UV2 = false;
  18175. this.VERTEXCOLOR = false;
  18176. this.VERTEXALPHA = false;
  18177. this.BONES = false;
  18178. this.BONES4 = false;
  18179. this.BonesPerMesh = 0;
  18180. this.INSTANCES = false;
  18181. this.GLOSSINESS = false;
  18182. this.ROUGHNESS = false;
  18183. this.EMISSIVEASILLUMINATION = false;
  18184. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18185. this.LIGHTMAP = false;
  18186. this.REFLECTIONMAP_3D = false;
  18187. this.REFLECTIONMAP_SPHERICAL = false;
  18188. this.REFLECTIONMAP_PLANAR = false;
  18189. this.REFLECTIONMAP_CUBIC = false;
  18190. this.REFLECTIONMAP_PROJECTION = false;
  18191. this.REFLECTIONMAP_SKYBOX = false;
  18192. this.REFLECTIONMAP_EXPLICIT = false;
  18193. this.INVERTCUBICMAP = false;
  18194. this._keys = Object.keys(this);
  18195. }
  18196. return StandardMaterialDefines;
  18197. })(BABYLON.MaterialDefines);
  18198. var StandardMaterial = (function (_super) {
  18199. __extends(StandardMaterial, _super);
  18200. function StandardMaterial(name, scene) {
  18201. var _this = this;
  18202. _super.call(this, name, scene);
  18203. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18204. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18205. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18206. this.specularPower = 64;
  18207. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18208. this.useAlphaFromDiffuseTexture = false;
  18209. this.useEmissiveAsIllumination = false;
  18210. this.useReflectionFresnelFromSpecular = false;
  18211. this.useSpecularOverAlpha = true;
  18212. this.disableLighting = false;
  18213. this.roughness = 0;
  18214. this.lightmapThreshold = 0;
  18215. this.useGlossinessFromSpecularMapAlpha = false;
  18216. this._renderTargets = new BABYLON.SmartArray(16);
  18217. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18218. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18219. this._scaledDiffuse = new BABYLON.Color3();
  18220. this._scaledSpecular = new BABYLON.Color3();
  18221. this._defines = new StandardMaterialDefines();
  18222. this._cachedDefines = new StandardMaterialDefines();
  18223. this._cachedDefines.BonesPerMesh = -1;
  18224. this.getRenderTargetTextures = function () {
  18225. _this._renderTargets.reset();
  18226. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18227. _this._renderTargets.push(_this.reflectionTexture);
  18228. }
  18229. return _this._renderTargets;
  18230. };
  18231. }
  18232. StandardMaterial.prototype.needAlphaBlending = function () {
  18233. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18234. };
  18235. StandardMaterial.prototype.needAlphaTesting = function () {
  18236. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18237. };
  18238. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18239. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18240. };
  18241. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18242. return this.diffuseTexture;
  18243. };
  18244. // Methods
  18245. StandardMaterial.prototype._checkCache = function (scene, mesh) {
  18246. if (!mesh) {
  18247. return true;
  18248. }
  18249. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18250. return true;
  18251. }
  18252. return false;
  18253. };
  18254. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18255. if (this.checkReadyOnlyOnce) {
  18256. if (this._wasPreviouslyReady) {
  18257. return true;
  18258. }
  18259. }
  18260. var scene = this.getScene();
  18261. if (!this.checkReadyOnEveryCall) {
  18262. if (this._renderId === scene.getRenderId()) {
  18263. if (this._checkCache(scene, mesh)) {
  18264. return true;
  18265. }
  18266. }
  18267. }
  18268. var engine = scene.getEngine();
  18269. var needNormals = false;
  18270. var needUVs = false;
  18271. this._defines.reset();
  18272. // Textures
  18273. if (scene.texturesEnabled) {
  18274. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18275. if (!this.diffuseTexture.isReady()) {
  18276. return false;
  18277. }
  18278. else {
  18279. needUVs = true;
  18280. this._defines.DIFFUSE = true;
  18281. }
  18282. }
  18283. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18284. if (!this.ambientTexture.isReady()) {
  18285. return false;
  18286. }
  18287. else {
  18288. needUVs = true;
  18289. this._defines.AMBIENT = true;
  18290. }
  18291. }
  18292. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18293. if (!this.opacityTexture.isReady()) {
  18294. return false;
  18295. }
  18296. else {
  18297. needUVs = true;
  18298. this._defines.OPACITY = true;
  18299. if (this.opacityTexture.getAlphaFromRGB) {
  18300. this._defines.OPACITYRGB = true;
  18301. }
  18302. }
  18303. }
  18304. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18305. if (!this.reflectionTexture.isReady()) {
  18306. return false;
  18307. }
  18308. else {
  18309. needNormals = true;
  18310. this._defines.REFLECTION = true;
  18311. if (this.roughness > 0) {
  18312. this._defines.ROUGHNESS = true;
  18313. }
  18314. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18315. this._defines.INVERTCUBICMAP = true;
  18316. }
  18317. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18318. switch (this.reflectionTexture.coordinatesMode) {
  18319. case BABYLON.Texture.CUBIC_MODE:
  18320. case BABYLON.Texture.INVCUBIC_MODE:
  18321. this._defines.REFLECTIONMAP_CUBIC = true;
  18322. break;
  18323. case BABYLON.Texture.EXPLICIT_MODE:
  18324. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18325. break;
  18326. case BABYLON.Texture.PLANAR_MODE:
  18327. this._defines.REFLECTIONMAP_PLANAR = true;
  18328. break;
  18329. case BABYLON.Texture.PROJECTION_MODE:
  18330. this._defines.REFLECTIONMAP_PROJECTION = true;
  18331. break;
  18332. case BABYLON.Texture.SKYBOX_MODE:
  18333. this._defines.REFLECTIONMAP_SKYBOX = true;
  18334. break;
  18335. case BABYLON.Texture.SPHERICAL_MODE:
  18336. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18337. break;
  18338. }
  18339. }
  18340. }
  18341. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18342. if (!this.emissiveTexture.isReady()) {
  18343. return false;
  18344. }
  18345. else {
  18346. needUVs = true;
  18347. this._defines.EMISSIVE = true;
  18348. }
  18349. }
  18350. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18351. if (!this.lightmapTexture.isReady()) {
  18352. return false;
  18353. }
  18354. else {
  18355. needUVs = true;
  18356. this._defines.LIGHTMAP = true;
  18357. }
  18358. }
  18359. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18360. if (!this.specularTexture.isReady()) {
  18361. return false;
  18362. }
  18363. else {
  18364. needUVs = true;
  18365. this._defines.SPECULAR = true;
  18366. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18367. }
  18368. }
  18369. }
  18370. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18371. if (!this.bumpTexture.isReady()) {
  18372. return false;
  18373. }
  18374. else {
  18375. needUVs = true;
  18376. this._defines.BUMP = true;
  18377. }
  18378. }
  18379. // Effect
  18380. if (scene.clipPlane) {
  18381. this._defines.CLIPPLANE = true;
  18382. }
  18383. if (engine.getAlphaTesting()) {
  18384. this._defines.ALPHATEST = true;
  18385. }
  18386. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18387. this._defines.ALPHAFROMDIFFUSE = true;
  18388. }
  18389. if (this.useEmissiveAsIllumination) {
  18390. this._defines.EMISSIVEASILLUMINATION = true;
  18391. }
  18392. if (this.useReflectionFresnelFromSpecular) {
  18393. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18394. }
  18395. // Point size
  18396. if (this.pointsCloud || scene.forcePointsCloud) {
  18397. this._defines.POINTSIZE = true;
  18398. }
  18399. // Fog
  18400. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18401. this._defines.FOG = true;
  18402. }
  18403. var lightIndex = 0;
  18404. if (scene.lightsEnabled && !this.disableLighting) {
  18405. for (var index = 0; index < scene.lights.length; index++) {
  18406. var light = scene.lights[index];
  18407. if (!light.isEnabled()) {
  18408. continue;
  18409. }
  18410. // Excluded check
  18411. if (light._excludedMeshesIds.length > 0) {
  18412. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18413. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18414. if (excludedMesh) {
  18415. light.excludedMeshes.push(excludedMesh);
  18416. }
  18417. }
  18418. light._excludedMeshesIds = [];
  18419. }
  18420. // Included check
  18421. if (light._includedOnlyMeshesIds.length > 0) {
  18422. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18423. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18424. if (includedOnlyMesh) {
  18425. light.includedOnlyMeshes.push(includedOnlyMesh);
  18426. }
  18427. }
  18428. light._includedOnlyMeshesIds = [];
  18429. }
  18430. if (!light.canAffectMesh(mesh)) {
  18431. continue;
  18432. }
  18433. needNormals = true;
  18434. this._defines["LIGHT" + lightIndex] = true;
  18435. var type;
  18436. if (light instanceof BABYLON.SpotLight) {
  18437. type = "SPOTLIGHT" + lightIndex;
  18438. }
  18439. else if (light instanceof BABYLON.HemisphericLight) {
  18440. type = "HEMILIGHT" + lightIndex;
  18441. }
  18442. else {
  18443. type = "POINTDIRLIGHT" + lightIndex;
  18444. }
  18445. this._defines[type] = true;
  18446. // Specular
  18447. if (!light.specular.equalsFloats(0, 0, 0)) {
  18448. this._defines.SPECULARTERM = true;
  18449. }
  18450. // Shadows
  18451. if (scene.shadowsEnabled) {
  18452. var shadowGenerator = light.getShadowGenerator();
  18453. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18454. this._defines["SHADOW" + lightIndex] = true;
  18455. this._defines.SHADOWS = true;
  18456. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18457. this._defines["SHADOWVSM" + lightIndex] = true;
  18458. }
  18459. if (shadowGenerator.usePoissonSampling) {
  18460. this._defines["SHADOWPCF" + lightIndex] = true;
  18461. }
  18462. }
  18463. }
  18464. lightIndex++;
  18465. if (lightIndex === maxSimultaneousLights)
  18466. break;
  18467. }
  18468. }
  18469. if (StandardMaterial.FresnelEnabled) {
  18470. // Fresnel
  18471. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18472. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18473. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18474. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18475. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18476. this._defines.DIFFUSEFRESNEL = true;
  18477. }
  18478. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18479. this._defines.OPACITYFRESNEL = true;
  18480. }
  18481. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18482. this._defines.REFLECTIONFRESNEL = true;
  18483. }
  18484. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18485. this._defines.EMISSIVEFRESNEL = true;
  18486. }
  18487. needNormals = true;
  18488. this._defines.FRESNEL = true;
  18489. }
  18490. }
  18491. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18492. this._defines.SPECULAROVERALPHA = true;
  18493. }
  18494. // Attribs
  18495. if (mesh) {
  18496. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18497. this._defines.NORMAL = true;
  18498. }
  18499. if (needUVs) {
  18500. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18501. this._defines.UV1 = true;
  18502. }
  18503. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18504. this._defines.UV2 = true;
  18505. }
  18506. }
  18507. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18508. this._defines.VERTEXCOLOR = true;
  18509. if (mesh.hasVertexAlpha) {
  18510. this._defines.VERTEXALPHA = true;
  18511. }
  18512. }
  18513. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18514. this._defines.BONES = true;
  18515. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18516. this._defines.BONES4 = true;
  18517. }
  18518. // Instances
  18519. if (useInstances) {
  18520. this._defines.INSTANCES = true;
  18521. }
  18522. }
  18523. // Get correct effect
  18524. if (!this._defines.isEqual(this._cachedDefines)) {
  18525. this._defines.cloneTo(this._cachedDefines);
  18526. scene.resetCachedMaterial();
  18527. // Fallbacks
  18528. var fallbacks = new BABYLON.EffectFallbacks();
  18529. if (this._defines.REFLECTION) {
  18530. fallbacks.addFallback(0, "REFLECTION");
  18531. }
  18532. if (this._defines.SPECULAR) {
  18533. fallbacks.addFallback(0, "SPECULAR");
  18534. }
  18535. if (this._defines.BUMP) {
  18536. fallbacks.addFallback(0, "BUMP");
  18537. }
  18538. if (this._defines.SPECULAROVERALPHA) {
  18539. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18540. }
  18541. if (this._defines.FOG) {
  18542. fallbacks.addFallback(1, "FOG");
  18543. }
  18544. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18545. if (!this._defines["LIGHT" + lightIndex]) {
  18546. continue;
  18547. }
  18548. if (lightIndex > 0) {
  18549. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18550. }
  18551. if (this._defines["SHADOW" + lightIndex]) {
  18552. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18553. }
  18554. if (this._defines["SHADOWPCF" + lightIndex]) {
  18555. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18556. }
  18557. if (this._defines["SHADOWVSM" + lightIndex]) {
  18558. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18559. }
  18560. }
  18561. if (this._defines.SPECULARTERM) {
  18562. fallbacks.addFallback(0, "SPECULARTERM");
  18563. }
  18564. if (this._defines.DIFFUSEFRESNEL) {
  18565. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18566. }
  18567. if (this._defines.OPACITYFRESNEL) {
  18568. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18569. }
  18570. if (this._defines.REFLECTIONFRESNEL) {
  18571. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18572. }
  18573. if (this._defines.EMISSIVEFRESNEL) {
  18574. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18575. }
  18576. if (this._defines.FRESNEL) {
  18577. fallbacks.addFallback(4, "FRESNEL");
  18578. }
  18579. if (this._defines.BONES4) {
  18580. fallbacks.addFallback(0, "BONES4");
  18581. }
  18582. //Attributes
  18583. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18584. if (this._defines.NORMAL) {
  18585. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18586. }
  18587. if (this._defines.UV1) {
  18588. attribs.push(BABYLON.VertexBuffer.UVKind);
  18589. }
  18590. if (this._defines.UV2) {
  18591. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18592. }
  18593. if (this._defines.VERTEXCOLOR) {
  18594. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18595. }
  18596. if (this._defines.BONES) {
  18597. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18598. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18599. }
  18600. if (this._defines.INSTANCES) {
  18601. attribs.push("world0");
  18602. attribs.push("world1");
  18603. attribs.push("world2");
  18604. attribs.push("world3");
  18605. }
  18606. // Legacy browser patch
  18607. var shaderName = "default";
  18608. if (!scene.getEngine().getCaps().standardDerivatives) {
  18609. shaderName = "legacydefault";
  18610. }
  18611. var join = this._defines.toString();
  18612. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18613. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18614. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18615. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18616. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18617. "vFogInfos", "vFogColor", "pointSize",
  18618. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18619. "mBones",
  18620. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18621. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18622. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18623. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18624. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18625. ], join, fallbacks, this.onCompiled, this.onError);
  18626. }
  18627. if (!this._effect.isReady()) {
  18628. return false;
  18629. }
  18630. this._renderId = scene.getRenderId();
  18631. this._wasPreviouslyReady = true;
  18632. if (mesh) {
  18633. if (!mesh._materialDefines) {
  18634. mesh._materialDefines = new StandardMaterialDefines();
  18635. }
  18636. this._defines.cloneTo(mesh._materialDefines);
  18637. }
  18638. return true;
  18639. };
  18640. StandardMaterial.prototype.unbind = function () {
  18641. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18642. this._effect.setTexture("reflection2DSampler", null);
  18643. }
  18644. _super.prototype.unbind.call(this);
  18645. };
  18646. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18647. this._effect.setMatrix("world", world);
  18648. };
  18649. StandardMaterial.prototype.bind = function (world, mesh) {
  18650. var scene = this.getScene();
  18651. // Matrices
  18652. this.bindOnlyWorldMatrix(world);
  18653. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18654. // Bones
  18655. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18656. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18657. }
  18658. if (scene.getCachedMaterial() !== this) {
  18659. if (StandardMaterial.FresnelEnabled) {
  18660. // Fresnel
  18661. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18662. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18663. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18664. }
  18665. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18666. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18667. }
  18668. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18669. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18670. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18671. }
  18672. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18673. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18674. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18675. }
  18676. }
  18677. // Textures
  18678. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18679. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18680. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18681. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18682. }
  18683. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18684. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18685. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18686. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18687. }
  18688. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18689. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18690. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18691. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18692. }
  18693. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18694. if (this.reflectionTexture.isCube) {
  18695. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18696. }
  18697. else {
  18698. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18699. }
  18700. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18701. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18702. }
  18703. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18704. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18705. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18706. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18707. }
  18708. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18709. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  18710. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  18711. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  18712. }
  18713. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18714. this._effect.setTexture("specularSampler", this.specularTexture);
  18715. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18716. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18717. }
  18718. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18719. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18720. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18721. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18722. }
  18723. // Clip plane
  18724. if (scene.clipPlane) {
  18725. var clipPlane = scene.clipPlane;
  18726. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18727. }
  18728. // Point size
  18729. if (this.pointsCloud) {
  18730. this._effect.setFloat("pointSize", this.pointSize);
  18731. }
  18732. // Colors
  18733. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18734. // Scaling down color according to emissive
  18735. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18736. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18737. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18738. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  18739. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18740. if (this._defines.SPECULARTERM) {
  18741. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18742. }
  18743. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18744. }
  18745. // Scaling down color according to emissive
  18746. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18747. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18748. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18749. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18750. if (scene.lightsEnabled && !this.disableLighting) {
  18751. var lightIndex = 0;
  18752. for (var index = 0; index < scene.lights.length; index++) {
  18753. var light = scene.lights[index];
  18754. if (!light.isEnabled()) {
  18755. continue;
  18756. }
  18757. if (!light.canAffectMesh(mesh)) {
  18758. continue;
  18759. }
  18760. if (light instanceof BABYLON.PointLight) {
  18761. // Point Light
  18762. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18763. }
  18764. else if (light instanceof BABYLON.DirectionalLight) {
  18765. // Directional Light
  18766. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18767. }
  18768. else if (light instanceof BABYLON.SpotLight) {
  18769. // Spot Light
  18770. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18771. }
  18772. else if (light instanceof BABYLON.HemisphericLight) {
  18773. // Hemispheric Light
  18774. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18775. }
  18776. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18777. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18778. if (this._defines.SPECULARTERM) {
  18779. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18780. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18781. }
  18782. // Shadows
  18783. if (scene.shadowsEnabled) {
  18784. var shadowGenerator = light.getShadowGenerator();
  18785. if (mesh.receiveShadows && shadowGenerator) {
  18786. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18787. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18788. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18789. }
  18790. }
  18791. lightIndex++;
  18792. if (lightIndex === maxSimultaneousLights)
  18793. break;
  18794. }
  18795. }
  18796. // View
  18797. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18798. this._effect.setMatrix("view", scene.getViewMatrix());
  18799. }
  18800. // Fog
  18801. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18802. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18803. this._effect.setColor3("vFogColor", scene.fogColor);
  18804. }
  18805. _super.prototype.bind.call(this, world, mesh);
  18806. };
  18807. StandardMaterial.prototype.getAnimatables = function () {
  18808. var results = [];
  18809. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18810. results.push(this.diffuseTexture);
  18811. }
  18812. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18813. results.push(this.ambientTexture);
  18814. }
  18815. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18816. results.push(this.opacityTexture);
  18817. }
  18818. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18819. results.push(this.reflectionTexture);
  18820. }
  18821. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18822. results.push(this.emissiveTexture);
  18823. }
  18824. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18825. results.push(this.specularTexture);
  18826. }
  18827. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18828. results.push(this.bumpTexture);
  18829. }
  18830. return results;
  18831. };
  18832. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18833. if (this.diffuseTexture) {
  18834. this.diffuseTexture.dispose();
  18835. }
  18836. if (this.ambientTexture) {
  18837. this.ambientTexture.dispose();
  18838. }
  18839. if (this.opacityTexture) {
  18840. this.opacityTexture.dispose();
  18841. }
  18842. if (this.reflectionTexture) {
  18843. this.reflectionTexture.dispose();
  18844. }
  18845. if (this.emissiveTexture) {
  18846. this.emissiveTexture.dispose();
  18847. }
  18848. if (this.specularTexture) {
  18849. this.specularTexture.dispose();
  18850. }
  18851. if (this.bumpTexture) {
  18852. this.bumpTexture.dispose();
  18853. }
  18854. _super.prototype.dispose.call(this, forceDisposeEffect);
  18855. };
  18856. StandardMaterial.prototype.clone = function (name) {
  18857. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18858. // Base material
  18859. this.copyTo(newStandardMaterial);
  18860. // Standard material
  18861. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18862. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18863. }
  18864. if (this.ambientTexture && this.ambientTexture.clone) {
  18865. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18866. }
  18867. if (this.opacityTexture && this.opacityTexture.clone) {
  18868. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18869. }
  18870. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18871. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18872. }
  18873. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18874. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18875. }
  18876. if (this.specularTexture && this.specularTexture.clone) {
  18877. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18878. }
  18879. if (this.bumpTexture && this.bumpTexture.clone) {
  18880. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18881. }
  18882. if (this.lightmapTexture && this.lightmapTexture.clone) {
  18883. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18884. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  18885. newStandardMaterial.lightmapThreshold = this.lightmapThreshold;
  18886. }
  18887. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18888. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18889. newStandardMaterial.specularColor = this.specularColor.clone();
  18890. newStandardMaterial.specularPower = this.specularPower;
  18891. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18892. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  18893. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  18894. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  18895. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  18896. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  18897. newStandardMaterial.roughness = this.roughness;
  18898. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  18899. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  18900. }
  18901. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  18902. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  18903. }
  18904. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  18905. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  18906. }
  18907. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  18908. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  18909. }
  18910. return newStandardMaterial;
  18911. };
  18912. // Statics
  18913. // Flags used to enable or disable a type of texture for all Standard Materials
  18914. StandardMaterial.DiffuseTextureEnabled = true;
  18915. StandardMaterial.AmbientTextureEnabled = true;
  18916. StandardMaterial.OpacityTextureEnabled = true;
  18917. StandardMaterial.ReflectionTextureEnabled = true;
  18918. StandardMaterial.EmissiveTextureEnabled = true;
  18919. StandardMaterial.SpecularTextureEnabled = true;
  18920. StandardMaterial.BumpTextureEnabled = true;
  18921. StandardMaterial.FresnelEnabled = true;
  18922. StandardMaterial.LightmapEnabled = true;
  18923. return StandardMaterial;
  18924. })(BABYLON.Material);
  18925. BABYLON.StandardMaterial = StandardMaterial;
  18926. })(BABYLON || (BABYLON = {}));
  18927. var BABYLON;
  18928. (function (BABYLON) {
  18929. var MultiMaterial = (function (_super) {
  18930. __extends(MultiMaterial, _super);
  18931. function MultiMaterial(name, scene) {
  18932. _super.call(this, name, scene, true);
  18933. this.subMaterials = new Array();
  18934. scene.multiMaterials.push(this);
  18935. }
  18936. // Properties
  18937. MultiMaterial.prototype.getSubMaterial = function (index) {
  18938. if (index < 0 || index >= this.subMaterials.length) {
  18939. return this.getScene().defaultMaterial;
  18940. }
  18941. return this.subMaterials[index];
  18942. };
  18943. // Methods
  18944. MultiMaterial.prototype.isReady = function (mesh) {
  18945. for (var index = 0; index < this.subMaterials.length; index++) {
  18946. var subMaterial = this.subMaterials[index];
  18947. if (subMaterial) {
  18948. if (!this.subMaterials[index].isReady(mesh)) {
  18949. return false;
  18950. }
  18951. }
  18952. }
  18953. return true;
  18954. };
  18955. MultiMaterial.prototype.clone = function (name) {
  18956. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18957. for (var index = 0; index < this.subMaterials.length; index++) {
  18958. var subMaterial = this.subMaterials[index];
  18959. newMultiMaterial.subMaterials.push(subMaterial);
  18960. }
  18961. return newMultiMaterial;
  18962. };
  18963. return MultiMaterial;
  18964. })(BABYLON.Material);
  18965. BABYLON.MultiMaterial = MultiMaterial;
  18966. })(BABYLON || (BABYLON = {}));
  18967. var BABYLON;
  18968. (function (BABYLON) {
  18969. var SceneLoader = (function () {
  18970. function SceneLoader() {
  18971. }
  18972. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18973. get: function () {
  18974. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18975. },
  18976. set: function (value) {
  18977. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18978. },
  18979. enumerable: true,
  18980. configurable: true
  18981. });
  18982. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18983. get: function () {
  18984. return SceneLoader._ShowLoadingScreen;
  18985. },
  18986. set: function (value) {
  18987. SceneLoader._ShowLoadingScreen = value;
  18988. },
  18989. enumerable: true,
  18990. configurable: true
  18991. });
  18992. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18993. var dotPosition = sceneFilename.lastIndexOf(".");
  18994. var queryStringPosition = sceneFilename.indexOf("?");
  18995. if (queryStringPosition === -1) {
  18996. queryStringPosition = sceneFilename.length;
  18997. }
  18998. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18999. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19000. var plugin = this._registeredPlugins[index];
  19001. if (plugin.extensions.indexOf(extension) !== -1) {
  19002. return plugin;
  19003. }
  19004. }
  19005. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19006. };
  19007. // Public functions
  19008. SceneLoader.RegisterPlugin = function (plugin) {
  19009. plugin.extensions = plugin.extensions.toLowerCase();
  19010. SceneLoader._registeredPlugins.push(plugin);
  19011. };
  19012. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19013. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19014. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19015. return;
  19016. }
  19017. var loadingToken = {};
  19018. scene._addPendingData(loadingToken);
  19019. var manifestChecked = function (success) {
  19020. scene.database = database;
  19021. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19022. var importMeshFromData = function (data) {
  19023. var meshes = [];
  19024. var particleSystems = [];
  19025. var skeletons = [];
  19026. try {
  19027. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19028. if (onerror) {
  19029. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19030. }
  19031. scene._removePendingData(loadingToken);
  19032. return;
  19033. }
  19034. }
  19035. catch (e) {
  19036. if (onerror) {
  19037. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19038. }
  19039. scene._removePendingData(loadingToken);
  19040. return;
  19041. }
  19042. if (onsuccess) {
  19043. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19044. onsuccess(meshes, particleSystems, skeletons);
  19045. scene._removePendingData(loadingToken);
  19046. }
  19047. };
  19048. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19049. // Direct load
  19050. importMeshFromData(sceneFilename.substr(5));
  19051. return;
  19052. }
  19053. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19054. importMeshFromData(data);
  19055. }, progressCallBack, database);
  19056. };
  19057. if (scene.getEngine().enableOfflineSupport) {
  19058. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19059. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19060. }
  19061. else {
  19062. manifestChecked(true);
  19063. }
  19064. };
  19065. /**
  19066. * Load a scene
  19067. * @param rootUrl a string that defines the root url for scene and resources
  19068. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19069. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19070. */
  19071. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19072. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19073. };
  19074. /**
  19075. * Append a scene
  19076. * @param rootUrl a string that defines the root url for scene and resources
  19077. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19078. * @param scene is the instance of BABYLON.Scene to append to
  19079. */
  19080. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19081. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19082. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19083. return;
  19084. }
  19085. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19086. var database;
  19087. var loadingToken = {};
  19088. scene._addPendingData(loadingToken);
  19089. if (SceneLoader.ShowLoadingScreen) {
  19090. scene.getEngine().displayLoadingUI();
  19091. }
  19092. var loadSceneFromData = function (data) {
  19093. scene.database = database;
  19094. if (!plugin.load(scene, data, rootUrl)) {
  19095. if (onerror) {
  19096. onerror(scene);
  19097. }
  19098. scene._removePendingData(loadingToken);
  19099. scene.getEngine().hideLoadingUI();
  19100. return;
  19101. }
  19102. if (onsuccess) {
  19103. onsuccess(scene);
  19104. }
  19105. scene._removePendingData(loadingToken);
  19106. if (SceneLoader.ShowLoadingScreen) {
  19107. scene.executeWhenReady(function () {
  19108. scene.getEngine().hideLoadingUI();
  19109. });
  19110. }
  19111. };
  19112. var manifestChecked = function (success) {
  19113. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19114. };
  19115. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19116. // Direct load
  19117. loadSceneFromData(sceneFilename.substr(5));
  19118. return;
  19119. }
  19120. if (rootUrl.indexOf("file:") === -1) {
  19121. if (scene.getEngine().enableOfflineSupport) {
  19122. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19123. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19124. }
  19125. else {
  19126. manifestChecked(true);
  19127. }
  19128. }
  19129. else {
  19130. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19131. }
  19132. };
  19133. // Flags
  19134. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19135. SceneLoader._ShowLoadingScreen = true;
  19136. // Members
  19137. SceneLoader._registeredPlugins = new Array();
  19138. return SceneLoader;
  19139. })();
  19140. BABYLON.SceneLoader = SceneLoader;
  19141. ;
  19142. })(BABYLON || (BABYLON = {}));
  19143. var BABYLON;
  19144. (function (BABYLON) {
  19145. var Internals;
  19146. (function (Internals) {
  19147. var checkColors4 = function (colors, count) {
  19148. // Check if color3 was used
  19149. if (colors.length === count * 3) {
  19150. var colors4 = [];
  19151. for (var index = 0; index < colors.length; index += 3) {
  19152. var newIndex = (index / 3) * 4;
  19153. colors4[newIndex] = colors[index];
  19154. colors4[newIndex + 1] = colors[index + 1];
  19155. colors4[newIndex + 2] = colors[index + 2];
  19156. colors4[newIndex + 3] = 1.0;
  19157. }
  19158. return colors4;
  19159. }
  19160. return colors;
  19161. };
  19162. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19163. var texture = null;
  19164. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19165. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19166. texture.name = parsedTexture.name;
  19167. texture.hasAlpha = parsedTexture.hasAlpha;
  19168. texture.level = parsedTexture.level;
  19169. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19170. }
  19171. return texture;
  19172. };
  19173. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19174. if (parsedTexture.isCube) {
  19175. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19176. }
  19177. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19178. return null;
  19179. }
  19180. var texture;
  19181. if (parsedTexture.mirrorPlane) {
  19182. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19183. texture._waitingRenderList = parsedTexture.renderList;
  19184. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19185. }
  19186. else if (parsedTexture.isRenderTarget) {
  19187. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19188. texture._waitingRenderList = parsedTexture.renderList;
  19189. }
  19190. else {
  19191. if (parsedTexture.base64String) {
  19192. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19193. }
  19194. else {
  19195. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19196. }
  19197. }
  19198. texture.name = parsedTexture.name;
  19199. texture.hasAlpha = parsedTexture.hasAlpha;
  19200. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19201. texture.level = parsedTexture.level;
  19202. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19203. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19204. texture.uOffset = parsedTexture.uOffset;
  19205. texture.vOffset = parsedTexture.vOffset;
  19206. texture.uScale = parsedTexture.uScale;
  19207. texture.vScale = parsedTexture.vScale;
  19208. texture.uAng = parsedTexture.uAng;
  19209. texture.vAng = parsedTexture.vAng;
  19210. texture.wAng = parsedTexture.wAng;
  19211. texture.wrapU = parsedTexture.wrapU;
  19212. texture.wrapV = parsedTexture.wrapV;
  19213. // Animations
  19214. if (parsedTexture.animations) {
  19215. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19216. var parsedAnimation = parsedTexture.animations[animationIndex];
  19217. texture.animations.push(parseAnimation(parsedAnimation));
  19218. }
  19219. }
  19220. return texture;
  19221. };
  19222. var parseSkeleton = function (parsedSkeleton, scene) {
  19223. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19224. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19225. var parsedBone = parsedSkeleton.bones[index];
  19226. var parentBone = null;
  19227. if (parsedBone.parentBoneIndex > -1) {
  19228. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19229. }
  19230. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19231. if (parsedBone.animation) {
  19232. bone.animations.push(parseAnimation(parsedBone.animation));
  19233. }
  19234. }
  19235. return skeleton;
  19236. };
  19237. var parseFresnelParameters = function (parsedFresnelParameters) {
  19238. var fresnelParameters = new BABYLON.FresnelParameters();
  19239. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19240. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19241. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19242. fresnelParameters.bias = parsedFresnelParameters.bias;
  19243. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19244. return fresnelParameters;
  19245. };
  19246. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19247. var material;
  19248. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19249. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19250. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19251. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19252. material.specularPower = parsedMaterial.specularPower;
  19253. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19254. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19255. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19256. material.alpha = parsedMaterial.alpha;
  19257. material.id = parsedMaterial.id;
  19258. if (parsedMaterial.disableDepthWrite) {
  19259. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19260. }
  19261. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19262. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19263. material.wireframe = parsedMaterial.wireframe;
  19264. if (parsedMaterial.diffuseTexture) {
  19265. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19266. }
  19267. if (parsedMaterial.diffuseFresnelParameters) {
  19268. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19269. }
  19270. if (parsedMaterial.ambientTexture) {
  19271. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19272. }
  19273. if (parsedMaterial.opacityTexture) {
  19274. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19275. }
  19276. if (parsedMaterial.opacityFresnelParameters) {
  19277. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19278. }
  19279. if (parsedMaterial.reflectionTexture) {
  19280. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19281. }
  19282. if (parsedMaterial.reflectionFresnelParameters) {
  19283. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19284. }
  19285. if (parsedMaterial.emissiveTexture) {
  19286. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19287. }
  19288. if (parsedMaterial.lightmapTexture) {
  19289. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19290. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19291. }
  19292. if (parsedMaterial.emissiveFresnelParameters) {
  19293. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19294. }
  19295. if (parsedMaterial.specularTexture) {
  19296. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19297. }
  19298. if (parsedMaterial.bumpTexture) {
  19299. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19300. }
  19301. if (parsedMaterial.checkReadyOnlyOnce) {
  19302. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19303. }
  19304. return material;
  19305. };
  19306. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19307. for (var index = 0; index < parsedData.materials.length; index++) {
  19308. var parsedMaterial = parsedData.materials[index];
  19309. if (parsedMaterial.id === id) {
  19310. return parseMaterial(parsedMaterial, scene, rootUrl);
  19311. }
  19312. }
  19313. return null;
  19314. };
  19315. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19316. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19317. multiMaterial.id = parsedMultiMaterial.id;
  19318. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19319. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19320. var subMatId = parsedMultiMaterial.materials[matIndex];
  19321. if (subMatId) {
  19322. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19323. }
  19324. else {
  19325. multiMaterial.subMaterials.push(null);
  19326. }
  19327. }
  19328. return multiMaterial;
  19329. };
  19330. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19331. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19332. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19333. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19334. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19335. var parsedFlare = parsedLensFlareSystem.flares[index];
  19336. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19337. }
  19338. return lensFlareSystem;
  19339. };
  19340. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19341. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19342. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19343. if (parsedParticleSystem.textureName) {
  19344. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19345. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19346. }
  19347. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19348. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19349. particleSystem.minSize = parsedParticleSystem.minSize;
  19350. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19351. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19352. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19353. particleSystem.emitter = emitter;
  19354. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19355. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19356. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19357. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19358. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19359. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19360. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19361. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19362. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19363. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19364. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19365. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19366. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19367. particleSystem.start();
  19368. return particleSystem;
  19369. };
  19370. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19371. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19372. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19373. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19374. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19375. shadowGenerator.getShadowMap().renderList.push(mesh);
  19376. }
  19377. if (parsedShadowGenerator.usePoissonSampling) {
  19378. shadowGenerator.usePoissonSampling = true;
  19379. }
  19380. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19381. shadowGenerator.useVarianceShadowMap = true;
  19382. }
  19383. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19384. shadowGenerator.useBlurVarianceShadowMap = true;
  19385. if (parsedShadowGenerator.blurScale) {
  19386. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19387. }
  19388. if (parsedShadowGenerator.blurBoxOffset) {
  19389. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19390. }
  19391. }
  19392. if (parsedShadowGenerator.bias !== undefined) {
  19393. shadowGenerator.bias = parsedShadowGenerator.bias;
  19394. }
  19395. return shadowGenerator;
  19396. };
  19397. var parseAnimation = function (parsedAnimation) {
  19398. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19399. var dataType = parsedAnimation.dataType;
  19400. var keys = [];
  19401. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19402. var key = parsedAnimation.keys[index];
  19403. var data;
  19404. switch (dataType) {
  19405. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19406. data = key.values[0];
  19407. break;
  19408. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19409. data = BABYLON.Quaternion.FromArray(key.values);
  19410. break;
  19411. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19412. data = BABYLON.Matrix.FromArray(key.values);
  19413. break;
  19414. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19415. default:
  19416. data = BABYLON.Vector3.FromArray(key.values);
  19417. break;
  19418. }
  19419. keys.push({
  19420. frame: key.frame,
  19421. value: data
  19422. });
  19423. }
  19424. animation.setKeys(keys);
  19425. return animation;
  19426. };
  19427. var parseLight = function (parsedLight, scene) {
  19428. var light;
  19429. switch (parsedLight.type) {
  19430. case 0:
  19431. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19432. break;
  19433. case 1:
  19434. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19435. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19436. break;
  19437. case 2:
  19438. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19439. break;
  19440. case 3:
  19441. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19442. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19443. break;
  19444. }
  19445. light.id = parsedLight.id;
  19446. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19447. if (parsedLight.intensity !== undefined) {
  19448. light.intensity = parsedLight.intensity;
  19449. }
  19450. if (parsedLight.range) {
  19451. light.range = parsedLight.range;
  19452. }
  19453. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19454. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19455. if (parsedLight.excludedMeshesIds) {
  19456. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19457. }
  19458. // Parent
  19459. if (parsedLight.parentId) {
  19460. light._waitingParentId = parsedLight.parentId;
  19461. }
  19462. if (parsedLight.includedOnlyMeshesIds) {
  19463. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19464. }
  19465. // Animations
  19466. if (parsedLight.animations) {
  19467. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19468. var parsedAnimation = parsedLight.animations[animationIndex];
  19469. light.animations.push(parseAnimation(parsedAnimation));
  19470. }
  19471. }
  19472. if (parsedLight.autoAnimate) {
  19473. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19474. }
  19475. };
  19476. var parseCamera = function (parsedCamera, scene) {
  19477. var camera;
  19478. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19479. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19480. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19481. var alpha = parsedCamera.alpha;
  19482. var beta = parsedCamera.beta;
  19483. var radius = parsedCamera.radius;
  19484. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19485. var interaxial_distance = parsedCamera.interaxial_distance;
  19486. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19487. }
  19488. else {
  19489. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19490. }
  19491. }
  19492. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19493. interaxial_distance = parsedCamera.interaxial_distance;
  19494. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19495. }
  19496. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19497. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19498. }
  19499. else if (parsedCamera.type === "FollowCamera") {
  19500. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19501. camera.heightOffset = parsedCamera.heightOffset;
  19502. camera.radius = parsedCamera.radius;
  19503. camera.rotationOffset = parsedCamera.rotationOffset;
  19504. if (lockedTargetMesh)
  19505. camera.target = lockedTargetMesh;
  19506. }
  19507. else if (parsedCamera.type === "GamepadCamera") {
  19508. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19509. }
  19510. else if (parsedCamera.type === "TouchCamera") {
  19511. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19512. }
  19513. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19514. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19515. }
  19516. else if (parsedCamera.type === "WebVRFreeCamera") {
  19517. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19518. }
  19519. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19520. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19521. }
  19522. else {
  19523. // Free Camera is the default value
  19524. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19525. }
  19526. // apply 3d rig, when found
  19527. if (parsedCamera.cameraRigMode) {
  19528. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19529. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19530. }
  19531. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19532. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19533. camera.lockedTarget = lockedTargetMesh;
  19534. }
  19535. camera.id = parsedCamera.id;
  19536. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19537. // Parent
  19538. if (parsedCamera.parentId) {
  19539. camera._waitingParentId = parsedCamera.parentId;
  19540. }
  19541. // Target
  19542. if (parsedCamera.target) {
  19543. if (camera.setTarget) {
  19544. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19545. }
  19546. else {
  19547. //For ArcRotate
  19548. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19549. }
  19550. }
  19551. else {
  19552. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19553. }
  19554. camera.fov = parsedCamera.fov;
  19555. camera.minZ = parsedCamera.minZ;
  19556. camera.maxZ = parsedCamera.maxZ;
  19557. camera.speed = parsedCamera.speed;
  19558. camera.inertia = parsedCamera.inertia;
  19559. camera.checkCollisions = parsedCamera.checkCollisions;
  19560. camera.applyGravity = parsedCamera.applyGravity;
  19561. if (parsedCamera.ellipsoid) {
  19562. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19563. }
  19564. // Animations
  19565. if (parsedCamera.animations) {
  19566. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19567. var parsedAnimation = parsedCamera.animations[animationIndex];
  19568. camera.animations.push(parseAnimation(parsedAnimation));
  19569. }
  19570. }
  19571. if (parsedCamera.autoAnimate) {
  19572. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19573. }
  19574. // Layer Mask
  19575. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19576. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19577. }
  19578. else {
  19579. camera.layerMask = 0x0FFFFFFF;
  19580. }
  19581. return camera;
  19582. };
  19583. var parseGeometry = function (parsedGeometry, scene) {
  19584. var id = parsedGeometry.id;
  19585. return scene.getGeometryByID(id);
  19586. };
  19587. var parseBox = function (parsedBox, scene) {
  19588. if (parseGeometry(parsedBox, scene)) {
  19589. return null; // null since geometry could be something else than a box...
  19590. }
  19591. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19592. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19593. scene.pushGeometry(box, true);
  19594. return box;
  19595. };
  19596. var parseSphere = function (parsedSphere, scene) {
  19597. if (parseGeometry(parsedSphere, scene)) {
  19598. return null; // null since geometry could be something else than a sphere...
  19599. }
  19600. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19601. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19602. scene.pushGeometry(sphere, true);
  19603. return sphere;
  19604. };
  19605. var parseCylinder = function (parsedCylinder, scene) {
  19606. if (parseGeometry(parsedCylinder, scene)) {
  19607. return null; // null since geometry could be something else than a cylinder...
  19608. }
  19609. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19610. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19611. scene.pushGeometry(cylinder, true);
  19612. return cylinder;
  19613. };
  19614. var parseTorus = function (parsedTorus, scene) {
  19615. if (parseGeometry(parsedTorus, scene)) {
  19616. return null; // null since geometry could be something else than a torus...
  19617. }
  19618. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19619. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19620. scene.pushGeometry(torus, true);
  19621. return torus;
  19622. };
  19623. var parseGround = function (parsedGround, scene) {
  19624. if (parseGeometry(parsedGround, scene)) {
  19625. return null; // null since geometry could be something else than a ground...
  19626. }
  19627. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19628. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19629. scene.pushGeometry(ground, true);
  19630. return ground;
  19631. };
  19632. var parsePlane = function (parsedPlane, scene) {
  19633. if (parseGeometry(parsedPlane, scene)) {
  19634. return null; // null since geometry could be something else than a plane...
  19635. }
  19636. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19637. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19638. scene.pushGeometry(plane, true);
  19639. return plane;
  19640. };
  19641. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19642. if (parseGeometry(parsedTorusKnot, scene)) {
  19643. return null; // null since geometry could be something else than a torusKnot...
  19644. }
  19645. 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);
  19646. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19647. scene.pushGeometry(torusKnot, true);
  19648. return torusKnot;
  19649. };
  19650. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19651. if (parseGeometry(parsedVertexData, scene)) {
  19652. return null; // null since geometry could be a primitive
  19653. }
  19654. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19655. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19656. if (parsedVertexData.delayLoadingFile) {
  19657. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19658. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19659. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19660. geometry._delayInfo = [];
  19661. if (parsedVertexData.hasUVs) {
  19662. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19663. }
  19664. if (parsedVertexData.hasUVs2) {
  19665. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19666. }
  19667. if (parsedVertexData.hasUVs3) {
  19668. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19669. }
  19670. if (parsedVertexData.hasUVs4) {
  19671. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19672. }
  19673. if (parsedVertexData.hasUVs5) {
  19674. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19675. }
  19676. if (parsedVertexData.hasUVs6) {
  19677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19678. }
  19679. if (parsedVertexData.hasColors) {
  19680. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19681. }
  19682. if (parsedVertexData.hasMatricesIndices) {
  19683. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19684. }
  19685. if (parsedVertexData.hasMatricesWeights) {
  19686. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19687. }
  19688. geometry._delayLoadingFunction = importVertexData;
  19689. }
  19690. else {
  19691. importVertexData(parsedVertexData, geometry);
  19692. }
  19693. scene.pushGeometry(geometry, true);
  19694. return geometry;
  19695. };
  19696. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19697. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19698. mesh.id = parsedMesh.id;
  19699. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19700. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19701. if (parsedMesh.rotationQuaternion) {
  19702. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19703. }
  19704. else if (parsedMesh.rotation) {
  19705. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19706. }
  19707. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19708. if (parsedMesh.localMatrix) {
  19709. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19710. }
  19711. else if (parsedMesh.pivotMatrix) {
  19712. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19713. }
  19714. mesh.setEnabled(parsedMesh.isEnabled);
  19715. mesh.isVisible = parsedMesh.isVisible;
  19716. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19717. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19718. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19719. if (parsedMesh.applyFog !== undefined) {
  19720. mesh.applyFog = parsedMesh.applyFog;
  19721. }
  19722. if (parsedMesh.pickable !== undefined) {
  19723. mesh.isPickable = parsedMesh.pickable;
  19724. }
  19725. if (parsedMesh.alphaIndex !== undefined) {
  19726. mesh.alphaIndex = parsedMesh.alphaIndex;
  19727. }
  19728. mesh.receiveShadows = parsedMesh.receiveShadows;
  19729. mesh.billboardMode = parsedMesh.billboardMode;
  19730. if (parsedMesh.visibility !== undefined) {
  19731. mesh.visibility = parsedMesh.visibility;
  19732. }
  19733. mesh.checkCollisions = parsedMesh.checkCollisions;
  19734. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19735. // freezeWorldMatrix
  19736. if (parsedMesh.freezeWorldMatrix) {
  19737. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19738. }
  19739. // Parent
  19740. if (parsedMesh.parentId) {
  19741. mesh._waitingParentId = parsedMesh.parentId;
  19742. }
  19743. // Actions
  19744. if (parsedMesh.actions !== undefined) {
  19745. mesh._waitingActions = parsedMesh.actions;
  19746. }
  19747. // Geometry
  19748. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19749. if (parsedMesh.delayLoadingFile) {
  19750. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19751. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19752. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19753. if (parsedMesh._binaryInfo) {
  19754. mesh._binaryInfo = parsedMesh._binaryInfo;
  19755. }
  19756. mesh._delayInfo = [];
  19757. if (parsedMesh.hasUVs) {
  19758. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19759. }
  19760. if (parsedMesh.hasUVs2) {
  19761. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19762. }
  19763. if (parsedMesh.hasUVs3) {
  19764. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19765. }
  19766. if (parsedMesh.hasUVs4) {
  19767. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19768. }
  19769. if (parsedMesh.hasUVs5) {
  19770. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19771. }
  19772. if (parsedMesh.hasUVs6) {
  19773. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19774. }
  19775. if (parsedMesh.hasColors) {
  19776. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19777. }
  19778. if (parsedMesh.hasMatricesIndices) {
  19779. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19780. }
  19781. if (parsedMesh.hasMatricesWeights) {
  19782. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19783. }
  19784. mesh._delayLoadingFunction = importGeometry;
  19785. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19786. mesh._checkDelayState();
  19787. }
  19788. }
  19789. else {
  19790. importGeometry(parsedMesh, mesh);
  19791. }
  19792. // Material
  19793. if (parsedMesh.materialId) {
  19794. mesh.setMaterialByID(parsedMesh.materialId);
  19795. }
  19796. else {
  19797. mesh.material = null;
  19798. }
  19799. // Skeleton
  19800. if (parsedMesh.skeletonId > -1) {
  19801. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19802. }
  19803. // Physics
  19804. if (parsedMesh.physicsImpostor) {
  19805. if (!scene.isPhysicsEnabled()) {
  19806. scene.enablePhysics();
  19807. }
  19808. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19809. }
  19810. // Animations
  19811. if (parsedMesh.animations) {
  19812. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19813. var parsedAnimation = parsedMesh.animations[animationIndex];
  19814. mesh.animations.push(parseAnimation(parsedAnimation));
  19815. }
  19816. }
  19817. if (parsedMesh.autoAnimate) {
  19818. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19819. }
  19820. // Layer Mask
  19821. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19822. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19823. }
  19824. else {
  19825. mesh.layerMask = 0x0FFFFFFF;
  19826. }
  19827. // Instances
  19828. if (parsedMesh.instances) {
  19829. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19830. var parsedInstance = parsedMesh.instances[index];
  19831. var instance = mesh.createInstance(parsedInstance.name);
  19832. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19833. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19834. if (parsedInstance.rotationQuaternion) {
  19835. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19836. }
  19837. else if (parsedInstance.rotation) {
  19838. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19839. }
  19840. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19841. instance.checkCollisions = mesh.checkCollisions;
  19842. if (parsedMesh.animations) {
  19843. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19844. parsedAnimation = parsedMesh.animations[animationIndex];
  19845. instance.animations.push(parseAnimation(parsedAnimation));
  19846. }
  19847. }
  19848. }
  19849. }
  19850. return mesh;
  19851. };
  19852. var parseActions = function (parsedActions, object, scene) {
  19853. var actionManager = new BABYLON.ActionManager(scene);
  19854. if (object === null)
  19855. scene.actionManager = actionManager;
  19856. else
  19857. object.actionManager = actionManager;
  19858. // instanciate a new object
  19859. var instanciate = function (name, params) {
  19860. var newInstance = Object.create(BABYLON[name].prototype);
  19861. newInstance.constructor.apply(newInstance, params);
  19862. return newInstance;
  19863. };
  19864. var parseParameter = function (name, value, target, propertyPath) {
  19865. if (propertyPath === null) {
  19866. // String, boolean or float
  19867. var floatValue = parseFloat(value);
  19868. if (value === "true" || value === "false")
  19869. return value === "true";
  19870. else
  19871. return isNaN(floatValue) ? value : floatValue;
  19872. }
  19873. var effectiveTarget = propertyPath.split(".");
  19874. var values = value.split(",");
  19875. // Get effective Target
  19876. for (var i = 0; i < effectiveTarget.length; i++) {
  19877. target = target[effectiveTarget[i]];
  19878. }
  19879. // Return appropriate value with its type
  19880. if (typeof (target) === "boolean")
  19881. return values[0] === "true";
  19882. if (typeof (target) === "string")
  19883. return values[0];
  19884. // Parameters with multiple values such as Vector3 etc.
  19885. var split = new Array();
  19886. for (var i = 0; i < values.length; i++)
  19887. split.push(parseFloat(values[i]));
  19888. if (target instanceof BABYLON.Vector3)
  19889. return BABYLON.Vector3.FromArray(split);
  19890. if (target instanceof BABYLON.Vector4)
  19891. return BABYLON.Vector4.FromArray(split);
  19892. if (target instanceof BABYLON.Color3)
  19893. return BABYLON.Color3.FromArray(split);
  19894. if (target instanceof BABYLON.Color4)
  19895. return BABYLON.Color4.FromArray(split);
  19896. return parseFloat(values[0]);
  19897. };
  19898. // traverse graph per trigger
  19899. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19900. if (combineArray === void 0) { combineArray = null; }
  19901. if (parsedAction.detached)
  19902. return;
  19903. var parameters = new Array();
  19904. var target = null;
  19905. var propertyPath = null;
  19906. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19907. // Parameters
  19908. if (parsedAction.type === 2)
  19909. parameters.push(actionManager);
  19910. else
  19911. parameters.push(trigger);
  19912. if (combine) {
  19913. var actions = new Array();
  19914. for (var j = 0; j < parsedAction.combine.length; j++) {
  19915. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19916. }
  19917. parameters.push(actions);
  19918. }
  19919. else {
  19920. for (var i = 0; i < parsedAction.properties.length; i++) {
  19921. var value = parsedAction.properties[i].value;
  19922. var name = parsedAction.properties[i].name;
  19923. var targetType = parsedAction.properties[i].targetType;
  19924. if (name === "target")
  19925. if (targetType !== null && targetType === "SceneProperties")
  19926. value = target = scene;
  19927. else
  19928. value = target = scene.getNodeByName(value);
  19929. else if (name === "parent")
  19930. value = scene.getNodeByName(value);
  19931. else if (name === "sound")
  19932. value = scene.getSoundByName(value);
  19933. else if (name !== "propertyPath") {
  19934. if (parsedAction.type === 2 && name === "operator")
  19935. value = BABYLON.ValueCondition[value];
  19936. else
  19937. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19938. }
  19939. else {
  19940. propertyPath = value;
  19941. }
  19942. parameters.push(value);
  19943. }
  19944. }
  19945. if (combineArray === null) {
  19946. parameters.push(condition);
  19947. }
  19948. else {
  19949. parameters.push(null);
  19950. }
  19951. // If interpolate value action
  19952. if (parsedAction.name === "InterpolateValueAction") {
  19953. var param = parameters[parameters.length - 2];
  19954. parameters[parameters.length - 1] = param;
  19955. parameters[parameters.length - 2] = condition;
  19956. }
  19957. // Action or condition(s) and not CombineAction
  19958. var newAction = instanciate(parsedAction.name, parameters);
  19959. if (newAction instanceof BABYLON.Condition && condition !== null) {
  19960. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  19961. if (action)
  19962. action.then(nothing);
  19963. else
  19964. actionManager.registerAction(nothing);
  19965. action = nothing;
  19966. }
  19967. if (combineArray === null) {
  19968. if (newAction instanceof BABYLON.Condition) {
  19969. condition = newAction;
  19970. newAction = action;
  19971. }
  19972. else {
  19973. condition = null;
  19974. if (action)
  19975. action.then(newAction);
  19976. else
  19977. actionManager.registerAction(newAction);
  19978. }
  19979. }
  19980. else {
  19981. combineArray.push(newAction);
  19982. }
  19983. for (var i = 0; i < parsedAction.children.length; i++)
  19984. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19985. };
  19986. // triggers
  19987. for (var i = 0; i < parsedActions.children.length; i++) {
  19988. var triggerParams;
  19989. var trigger = parsedActions.children[i];
  19990. if (trigger.properties.length > 0) {
  19991. var param = trigger.properties[0].value;
  19992. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19993. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19994. }
  19995. else
  19996. triggerParams = BABYLON.ActionManager[trigger.name];
  19997. for (var j = 0; j < trigger.children.length; j++) {
  19998. if (!trigger.detached)
  19999. traverse(trigger.children[j], triggerParams, null, null);
  20000. }
  20001. }
  20002. };
  20003. var parseSound = function (parsedSound, scene, rootUrl) {
  20004. var soundName = parsedSound.name;
  20005. var soundUrl = rootUrl + soundName;
  20006. var options = {
  20007. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20008. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20009. rolloffFactor: parsedSound.rolloffFactor,
  20010. refDistance: parsedSound.refDistance,
  20011. distanceModel: parsedSound.distanceModel,
  20012. playbackRate: parsedSound.playbackRate
  20013. };
  20014. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20015. scene._addPendingData(newSound);
  20016. if (parsedSound.position) {
  20017. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20018. newSound.setPosition(soundPosition);
  20019. }
  20020. if (parsedSound.isDirectional) {
  20021. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20022. if (parsedSound.localDirectionToMesh) {
  20023. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20024. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20025. }
  20026. }
  20027. if (parsedSound.connectedMeshId) {
  20028. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20029. if (connectedMesh) {
  20030. newSound.attachToMesh(connectedMesh);
  20031. }
  20032. }
  20033. };
  20034. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20035. names = (names instanceof Array) ? names : [names];
  20036. for (var i in names) {
  20037. if (mesh.name === names[i]) {
  20038. hierarchyIds.push(mesh.id);
  20039. return true;
  20040. }
  20041. }
  20042. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20043. hierarchyIds.push(mesh.id);
  20044. return true;
  20045. }
  20046. return false;
  20047. };
  20048. var importVertexData = function (parsedVertexData, geometry) {
  20049. var vertexData = new BABYLON.VertexData();
  20050. // positions
  20051. var positions = parsedVertexData.positions;
  20052. if (positions) {
  20053. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20054. }
  20055. // normals
  20056. var normals = parsedVertexData.normals;
  20057. if (normals) {
  20058. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20059. }
  20060. // uvs
  20061. var uvs = parsedVertexData.uvs;
  20062. if (uvs) {
  20063. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20064. }
  20065. // uv2s
  20066. var uv2s = parsedVertexData.uv2s;
  20067. if (uv2s) {
  20068. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20069. }
  20070. // uv3s
  20071. var uv3s = parsedVertexData.uv3s;
  20072. if (uv3s) {
  20073. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20074. }
  20075. // uv4s
  20076. var uv4s = parsedVertexData.uv4s;
  20077. if (uv4s) {
  20078. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20079. }
  20080. // uv5s
  20081. var uv5s = parsedVertexData.uv5s;
  20082. if (uv5s) {
  20083. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20084. }
  20085. // uv6s
  20086. var uv6s = parsedVertexData.uv6s;
  20087. if (uv6s) {
  20088. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20089. }
  20090. // colors
  20091. var colors = parsedVertexData.colors;
  20092. if (colors) {
  20093. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20094. }
  20095. // matricesIndices
  20096. var matricesIndices = parsedVertexData.matricesIndices;
  20097. if (matricesIndices) {
  20098. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20099. }
  20100. // matricesWeights
  20101. var matricesWeights = parsedVertexData.matricesWeights;
  20102. if (matricesWeights) {
  20103. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20104. }
  20105. // indices
  20106. var indices = parsedVertexData.indices;
  20107. if (indices) {
  20108. vertexData.indices = indices;
  20109. }
  20110. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20111. };
  20112. var importGeometry = function (parsedGeometry, mesh) {
  20113. var scene = mesh.getScene();
  20114. // Geometry
  20115. var geometryId = parsedGeometry.geometryId;
  20116. if (geometryId) {
  20117. var geometry = scene.getGeometryByID(geometryId);
  20118. if (geometry) {
  20119. geometry.applyToMesh(mesh);
  20120. }
  20121. }
  20122. else if (parsedGeometry instanceof ArrayBuffer) {
  20123. var binaryInfo = mesh._binaryInfo;
  20124. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20125. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20126. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20127. }
  20128. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20129. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20130. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20131. }
  20132. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20133. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20134. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20135. }
  20136. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20137. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20138. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20139. }
  20140. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20141. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20142. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20143. }
  20144. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20145. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20146. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20147. }
  20148. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20149. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20150. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20151. }
  20152. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20153. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20154. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20155. }
  20156. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20157. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20158. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20159. }
  20160. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20161. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20162. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20163. }
  20164. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20165. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20166. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20167. }
  20168. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20169. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20170. mesh.setIndices(indicesData);
  20171. }
  20172. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20173. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20174. mesh.subMeshes = [];
  20175. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20176. var materialIndex = subMeshesData[(i * 5) + 0];
  20177. var verticesStart = subMeshesData[(i * 5) + 1];
  20178. var verticesCount = subMeshesData[(i * 5) + 2];
  20179. var indexStart = subMeshesData[(i * 5) + 3];
  20180. var indexCount = subMeshesData[(i * 5) + 4];
  20181. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20182. }
  20183. }
  20184. }
  20185. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20186. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20187. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20188. if (parsedGeometry.uvs) {
  20189. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20190. }
  20191. if (parsedGeometry.uvs2) {
  20192. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20193. }
  20194. if (parsedGeometry.uvs3) {
  20195. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20196. }
  20197. if (parsedGeometry.uvs4) {
  20198. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20199. }
  20200. if (parsedGeometry.uvs5) {
  20201. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20202. }
  20203. if (parsedGeometry.uvs6) {
  20204. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20205. }
  20206. if (parsedGeometry.colors) {
  20207. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20208. }
  20209. if (parsedGeometry.matricesIndices) {
  20210. if (!parsedGeometry.matricesIndices._isExpanded) {
  20211. var floatIndices = [];
  20212. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20213. var matricesIndex = parsedGeometry.matricesIndices[i];
  20214. floatIndices.push(matricesIndex & 0x000000FF);
  20215. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20216. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20217. floatIndices.push(matricesIndex >> 24);
  20218. }
  20219. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20220. }
  20221. else {
  20222. delete parsedGeometry.matricesIndices._isExpanded;
  20223. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20224. }
  20225. }
  20226. if (parsedGeometry.matricesWeights) {
  20227. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20228. }
  20229. mesh.setIndices(parsedGeometry.indices);
  20230. }
  20231. // SubMeshes
  20232. if (parsedGeometry.subMeshes) {
  20233. mesh.subMeshes = [];
  20234. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20235. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20236. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20237. }
  20238. }
  20239. // Flat shading
  20240. if (mesh._shouldGenerateFlatShading) {
  20241. mesh.convertToFlatShadedMesh();
  20242. delete mesh._shouldGenerateFlatShading;
  20243. }
  20244. // Update
  20245. mesh.computeWorldMatrix(true);
  20246. // Octree
  20247. if (scene._selectionOctree) {
  20248. scene._selectionOctree.addMesh(mesh);
  20249. }
  20250. };
  20251. BABYLON.SceneLoader.RegisterPlugin({
  20252. extensions: ".babylon",
  20253. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20254. var parsedData = JSON.parse(data);
  20255. var loadedSkeletonsIds = [];
  20256. var loadedMaterialsIds = [];
  20257. var hierarchyIds = [];
  20258. for (var index = 0; index < parsedData.meshes.length; index++) {
  20259. var parsedMesh = parsedData.meshes[index];
  20260. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20261. if (meshesNames instanceof Array) {
  20262. // Remove found mesh name from list.
  20263. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20264. }
  20265. //Geometry?
  20266. if (parsedMesh.geometryId) {
  20267. //does the file contain geometries?
  20268. if (parsedData.geometries) {
  20269. //find the correct geometry and add it to the scene
  20270. var found = false;
  20271. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20272. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20273. return;
  20274. }
  20275. else {
  20276. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20277. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20278. switch (geometryType) {
  20279. case "boxes":
  20280. parseBox(parsedGeometryData, scene);
  20281. break;
  20282. case "spheres":
  20283. parseSphere(parsedGeometryData, scene);
  20284. break;
  20285. case "cylinders":
  20286. parseCylinder(parsedGeometryData, scene);
  20287. break;
  20288. case "toruses":
  20289. parseTorus(parsedGeometryData, scene);
  20290. break;
  20291. case "grounds":
  20292. parseGround(parsedGeometryData, scene);
  20293. break;
  20294. case "planes":
  20295. parsePlane(parsedGeometryData, scene);
  20296. break;
  20297. case "torusKnots":
  20298. parseTorusKnot(parsedGeometryData, scene);
  20299. break;
  20300. case "vertexData":
  20301. parseVertexData(parsedGeometryData, scene, rootUrl);
  20302. break;
  20303. }
  20304. found = true;
  20305. }
  20306. });
  20307. }
  20308. });
  20309. if (!found) {
  20310. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20311. }
  20312. }
  20313. }
  20314. // Material ?
  20315. if (parsedMesh.materialId) {
  20316. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20317. if (!materialFound && parsedData.multiMaterials) {
  20318. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20319. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20320. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20321. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20322. var subMatId = parsedMultiMaterial.materials[matIndex];
  20323. loadedMaterialsIds.push(subMatId);
  20324. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20325. }
  20326. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20327. parseMultiMaterial(parsedMultiMaterial, scene);
  20328. materialFound = true;
  20329. break;
  20330. }
  20331. }
  20332. }
  20333. if (!materialFound) {
  20334. loadedMaterialsIds.push(parsedMesh.materialId);
  20335. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20336. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20337. }
  20338. }
  20339. }
  20340. // Skeleton ?
  20341. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20342. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20343. if (!skeletonAlreadyLoaded) {
  20344. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20345. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20346. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20347. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20348. loadedSkeletonsIds.push(parsedSkeleton.id);
  20349. }
  20350. }
  20351. }
  20352. }
  20353. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20354. meshes.push(mesh);
  20355. }
  20356. }
  20357. // Connecting parents
  20358. for (index = 0; index < scene.meshes.length; index++) {
  20359. var currentMesh = scene.meshes[index];
  20360. if (currentMesh._waitingParentId) {
  20361. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20362. currentMesh._waitingParentId = undefined;
  20363. }
  20364. }
  20365. // freeze world matrix application
  20366. for (index = 0; index < scene.meshes.length; index++) {
  20367. var currentMesh = scene.meshes[index];
  20368. if (currentMesh._waitingFreezeWorldMatrix) {
  20369. currentMesh.freezeWorldMatrix();
  20370. currentMesh._waitingFreezeWorldMatrix = undefined;
  20371. }
  20372. }
  20373. // Particles
  20374. if (parsedData.particleSystems) {
  20375. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20376. var parsedParticleSystem = parsedData.particleSystems[index];
  20377. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20378. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20379. }
  20380. }
  20381. }
  20382. return true;
  20383. },
  20384. load: function (scene, data, rootUrl) {
  20385. var parsedData = JSON.parse(data);
  20386. // Scene
  20387. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20388. scene.autoClear = parsedData.autoClear;
  20389. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20390. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20391. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20392. // Fog
  20393. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20394. scene.fogMode = parsedData.fogMode;
  20395. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20396. scene.fogStart = parsedData.fogStart;
  20397. scene.fogEnd = parsedData.fogEnd;
  20398. scene.fogDensity = parsedData.fogDensity;
  20399. }
  20400. // Lights
  20401. for (var index = 0; index < parsedData.lights.length; index++) {
  20402. var parsedLight = parsedData.lights[index];
  20403. parseLight(parsedLight, scene);
  20404. }
  20405. // Materials
  20406. if (parsedData.materials) {
  20407. for (index = 0; index < parsedData.materials.length; index++) {
  20408. var parsedMaterial = parsedData.materials[index];
  20409. parseMaterial(parsedMaterial, scene, rootUrl);
  20410. }
  20411. }
  20412. if (parsedData.multiMaterials) {
  20413. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20414. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20415. parseMultiMaterial(parsedMultiMaterial, scene);
  20416. }
  20417. }
  20418. // Skeletons
  20419. if (parsedData.skeletons) {
  20420. for (index = 0; index < parsedData.skeletons.length; index++) {
  20421. var parsedSkeleton = parsedData.skeletons[index];
  20422. parseSkeleton(parsedSkeleton, scene);
  20423. }
  20424. }
  20425. // Geometries
  20426. var geometries = parsedData.geometries;
  20427. if (geometries) {
  20428. // Boxes
  20429. var boxes = geometries.boxes;
  20430. if (boxes) {
  20431. for (index = 0; index < boxes.length; index++) {
  20432. var parsedBox = boxes[index];
  20433. parseBox(parsedBox, scene);
  20434. }
  20435. }
  20436. // Spheres
  20437. var spheres = geometries.spheres;
  20438. if (spheres) {
  20439. for (index = 0; index < spheres.length; index++) {
  20440. var parsedSphere = spheres[index];
  20441. parseSphere(parsedSphere, scene);
  20442. }
  20443. }
  20444. // Cylinders
  20445. var cylinders = geometries.cylinders;
  20446. if (cylinders) {
  20447. for (index = 0; index < cylinders.length; index++) {
  20448. var parsedCylinder = cylinders[index];
  20449. parseCylinder(parsedCylinder, scene);
  20450. }
  20451. }
  20452. // Toruses
  20453. var toruses = geometries.toruses;
  20454. if (toruses) {
  20455. for (index = 0; index < toruses.length; index++) {
  20456. var parsedTorus = toruses[index];
  20457. parseTorus(parsedTorus, scene);
  20458. }
  20459. }
  20460. // Grounds
  20461. var grounds = geometries.grounds;
  20462. if (grounds) {
  20463. for (index = 0; index < grounds.length; index++) {
  20464. var parsedGround = grounds[index];
  20465. parseGround(parsedGround, scene);
  20466. }
  20467. }
  20468. // Planes
  20469. var planes = geometries.planes;
  20470. if (planes) {
  20471. for (index = 0; index < planes.length; index++) {
  20472. var parsedPlane = planes[index];
  20473. parsePlane(parsedPlane, scene);
  20474. }
  20475. }
  20476. // TorusKnots
  20477. var torusKnots = geometries.torusKnots;
  20478. if (torusKnots) {
  20479. for (index = 0; index < torusKnots.length; index++) {
  20480. var parsedTorusKnot = torusKnots[index];
  20481. parseTorusKnot(parsedTorusKnot, scene);
  20482. }
  20483. }
  20484. // VertexData
  20485. var vertexData = geometries.vertexData;
  20486. if (vertexData) {
  20487. for (index = 0; index < vertexData.length; index++) {
  20488. var parsedVertexData = vertexData[index];
  20489. parseVertexData(parsedVertexData, scene, rootUrl);
  20490. }
  20491. }
  20492. }
  20493. // Meshes
  20494. for (index = 0; index < parsedData.meshes.length; index++) {
  20495. var parsedMesh = parsedData.meshes[index];
  20496. parseMesh(parsedMesh, scene, rootUrl);
  20497. }
  20498. // Cameras
  20499. for (index = 0; index < parsedData.cameras.length; index++) {
  20500. var parsedCamera = parsedData.cameras[index];
  20501. parseCamera(parsedCamera, scene);
  20502. }
  20503. if (parsedData.activeCameraID) {
  20504. scene.setActiveCameraByID(parsedData.activeCameraID);
  20505. }
  20506. // Browsing all the graph to connect the dots
  20507. for (index = 0; index < scene.cameras.length; index++) {
  20508. var camera = scene.cameras[index];
  20509. if (camera._waitingParentId) {
  20510. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20511. camera._waitingParentId = undefined;
  20512. }
  20513. }
  20514. for (index = 0; index < scene.lights.length; index++) {
  20515. var light = scene.lights[index];
  20516. if (light._waitingParentId) {
  20517. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20518. light._waitingParentId = undefined;
  20519. }
  20520. }
  20521. // Sounds
  20522. if (BABYLON.AudioEngine && parsedData.sounds) {
  20523. for (index = 0; index < parsedData.sounds.length; index++) {
  20524. var parsedSound = parsedData.sounds[index];
  20525. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20526. parseSound(parsedSound, scene, rootUrl);
  20527. }
  20528. else {
  20529. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20530. }
  20531. }
  20532. }
  20533. // Connect parents & children and parse actions
  20534. for (index = 0; index < scene.meshes.length; index++) {
  20535. var mesh = scene.meshes[index];
  20536. if (mesh._waitingParentId) {
  20537. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20538. mesh._waitingParentId = undefined;
  20539. }
  20540. if (mesh._waitingActions) {
  20541. parseActions(mesh._waitingActions, mesh, scene);
  20542. mesh._waitingActions = undefined;
  20543. }
  20544. }
  20545. // freeze world matrix application
  20546. for (index = 0; index < scene.meshes.length; index++) {
  20547. var currentMesh = scene.meshes[index];
  20548. if (currentMesh._waitingFreezeWorldMatrix) {
  20549. currentMesh.freezeWorldMatrix();
  20550. currentMesh._waitingFreezeWorldMatrix = undefined;
  20551. }
  20552. }
  20553. // Particles Systems
  20554. if (parsedData.particleSystems) {
  20555. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20556. var parsedParticleSystem = parsedData.particleSystems[index];
  20557. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20558. }
  20559. }
  20560. // Lens flares
  20561. if (parsedData.lensFlareSystems) {
  20562. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20563. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20564. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20565. }
  20566. }
  20567. // Shadows
  20568. if (parsedData.shadowGenerators) {
  20569. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20570. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20571. parseShadowGenerator(parsedShadowGenerator, scene);
  20572. }
  20573. }
  20574. // Actions (scene)
  20575. if (parsedData.actions) {
  20576. parseActions(parsedData.actions, null, scene);
  20577. }
  20578. // Finish
  20579. return true;
  20580. }
  20581. });
  20582. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20583. })(BABYLON || (BABYLON = {}));
  20584. var BABYLON;
  20585. (function (BABYLON) {
  20586. var SpriteManager = (function () {
  20587. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20589. this.name = name;
  20590. this.cellSize = cellSize;
  20591. this.sprites = new Array();
  20592. this.renderingGroupId = 0;
  20593. this.layerMask = 0x0FFFFFFF;
  20594. this.fogEnabled = true;
  20595. this.isPickable = false;
  20596. this._vertexDeclaration = [4, 4, 4, 4];
  20597. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20598. this._capacity = capacity;
  20599. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20600. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20601. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20602. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20603. this._scene = scene;
  20604. this._scene.spriteManagers.push(this);
  20605. // VBO
  20606. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20607. var indices = [];
  20608. var index = 0;
  20609. for (var count = 0; count < capacity; count++) {
  20610. indices.push(index);
  20611. indices.push(index + 1);
  20612. indices.push(index + 2);
  20613. indices.push(index);
  20614. indices.push(index + 2);
  20615. indices.push(index + 3);
  20616. index += 4;
  20617. }
  20618. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20619. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20620. // Effects
  20621. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20622. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20623. }
  20624. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20625. var arrayOffset = index * 16;
  20626. if (offsetX === 0)
  20627. offsetX = this._epsilon;
  20628. else if (offsetX === 1)
  20629. offsetX = 1 - this._epsilon;
  20630. if (offsetY === 0)
  20631. offsetY = this._epsilon;
  20632. else if (offsetY === 1)
  20633. offsetY = 1 - this._epsilon;
  20634. this._vertices[arrayOffset] = sprite.position.x;
  20635. this._vertices[arrayOffset + 1] = sprite.position.y;
  20636. this._vertices[arrayOffset + 2] = sprite.position.z;
  20637. this._vertices[arrayOffset + 3] = sprite.angle;
  20638. this._vertices[arrayOffset + 4] = sprite.width;
  20639. this._vertices[arrayOffset + 5] = sprite.height;
  20640. this._vertices[arrayOffset + 6] = offsetX;
  20641. this._vertices[arrayOffset + 7] = offsetY;
  20642. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20643. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20644. var offset = (sprite.cellIndex / rowSize) >> 0;
  20645. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20646. this._vertices[arrayOffset + 11] = offset;
  20647. // Color
  20648. this._vertices[arrayOffset + 12] = sprite.color.r;
  20649. this._vertices[arrayOffset + 13] = sprite.color.g;
  20650. this._vertices[arrayOffset + 14] = sprite.color.b;
  20651. this._vertices[arrayOffset + 15] = sprite.color.a;
  20652. };
  20653. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20654. var count = Math.min(this._capacity, this.sprites.length);
  20655. var min = BABYLON.Vector3.Zero();
  20656. var max = BABYLON.Vector3.Zero();
  20657. var distance = Number.MAX_VALUE;
  20658. var currentSprite;
  20659. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20660. var cameraView = camera.getViewMatrix();
  20661. for (var index = 0; index < count; index++) {
  20662. var sprite = this.sprites[index];
  20663. if (!sprite) {
  20664. continue;
  20665. }
  20666. if (predicate) {
  20667. if (!predicate(sprite)) {
  20668. continue;
  20669. }
  20670. }
  20671. else if (!sprite.isPickable) {
  20672. continue;
  20673. }
  20674. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20675. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20676. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20677. if (ray.intersectsBoxMinMax(min, max)) {
  20678. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20679. if (distance > currentDistance) {
  20680. distance = currentDistance;
  20681. currentSprite = sprite;
  20682. if (fastCheck) {
  20683. break;
  20684. }
  20685. }
  20686. }
  20687. }
  20688. if (currentSprite) {
  20689. var result = new BABYLON.PickingInfo();
  20690. result.hit = true;
  20691. result.pickedSprite = currentSprite;
  20692. result.distance = distance;
  20693. return result;
  20694. }
  20695. return null;
  20696. };
  20697. SpriteManager.prototype.render = function () {
  20698. // Check
  20699. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20700. return;
  20701. var engine = this._scene.getEngine();
  20702. var baseSize = this._spriteTexture.getBaseSize();
  20703. // Sprites
  20704. var deltaTime = engine.getDeltaTime();
  20705. var max = Math.min(this._capacity, this.sprites.length);
  20706. var rowSize = baseSize.width / this.cellSize;
  20707. var offset = 0;
  20708. for (var index = 0; index < max; index++) {
  20709. var sprite = this.sprites[index];
  20710. if (!sprite) {
  20711. continue;
  20712. }
  20713. sprite._animate(deltaTime);
  20714. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20715. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20716. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20717. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20718. }
  20719. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20720. // Render
  20721. var effect = this._effectBase;
  20722. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20723. effect = this._effectFog;
  20724. }
  20725. engine.enableEffect(effect);
  20726. var viewMatrix = this._scene.getViewMatrix();
  20727. effect.setTexture("diffuseSampler", this._spriteTexture);
  20728. effect.setMatrix("view", viewMatrix);
  20729. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20730. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20731. // Fog
  20732. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20733. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20734. effect.setColor3("vFogColor", this._scene.fogColor);
  20735. }
  20736. // VBOs
  20737. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20738. // Draw order
  20739. engine.setDepthFunctionToLessOrEqual();
  20740. effect.setBool("alphaTest", true);
  20741. engine.setColorWrite(false);
  20742. engine.draw(true, 0, max * 6);
  20743. engine.setColorWrite(true);
  20744. effect.setBool("alphaTest", false);
  20745. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20746. engine.draw(true, 0, max * 6);
  20747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20748. };
  20749. SpriteManager.prototype.dispose = function () {
  20750. if (this._vertexBuffer) {
  20751. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20752. this._vertexBuffer = null;
  20753. }
  20754. if (this._indexBuffer) {
  20755. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20756. this._indexBuffer = null;
  20757. }
  20758. if (this._spriteTexture) {
  20759. this._spriteTexture.dispose();
  20760. this._spriteTexture = null;
  20761. }
  20762. // Remove from scene
  20763. var index = this._scene.spriteManagers.indexOf(this);
  20764. this._scene.spriteManagers.splice(index, 1);
  20765. // Callback
  20766. if (this.onDispose) {
  20767. this.onDispose();
  20768. }
  20769. };
  20770. return SpriteManager;
  20771. })();
  20772. BABYLON.SpriteManager = SpriteManager;
  20773. })(BABYLON || (BABYLON = {}));
  20774. var BABYLON;
  20775. (function (BABYLON) {
  20776. var Sprite = (function () {
  20777. function Sprite(name, manager) {
  20778. this.name = name;
  20779. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20780. this.width = 1.0;
  20781. this.height = 1.0;
  20782. this.angle = 0;
  20783. this.cellIndex = 0;
  20784. this.invertU = 0;
  20785. this.invertV = 0;
  20786. this.animations = new Array();
  20787. this.isPickable = false;
  20788. this._animationStarted = false;
  20789. this._loopAnimation = false;
  20790. this._fromIndex = 0;
  20791. this._toIndex = 0;
  20792. this._delay = 0;
  20793. this._direction = 1;
  20794. this._frameCount = 0;
  20795. this._time = 0;
  20796. this._manager = manager;
  20797. this._manager.sprites.push(this);
  20798. this.position = BABYLON.Vector3.Zero();
  20799. }
  20800. Object.defineProperty(Sprite.prototype, "size", {
  20801. get: function () {
  20802. return this.width;
  20803. },
  20804. set: function (value) {
  20805. this.width = value;
  20806. this.height = value;
  20807. },
  20808. enumerable: true,
  20809. configurable: true
  20810. });
  20811. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20812. this._fromIndex = from;
  20813. this._toIndex = to;
  20814. this._loopAnimation = loop;
  20815. this._delay = delay;
  20816. this._animationStarted = true;
  20817. this._direction = from < to ? 1 : -1;
  20818. this.cellIndex = from;
  20819. this._time = 0;
  20820. };
  20821. Sprite.prototype.stopAnimation = function () {
  20822. this._animationStarted = false;
  20823. };
  20824. Sprite.prototype._animate = function (deltaTime) {
  20825. if (!this._animationStarted)
  20826. return;
  20827. this._time += deltaTime;
  20828. if (this._time > this._delay) {
  20829. this._time = this._time % this._delay;
  20830. this.cellIndex += this._direction;
  20831. if (this.cellIndex == this._toIndex) {
  20832. if (this._loopAnimation) {
  20833. this.cellIndex = this._fromIndex;
  20834. }
  20835. else {
  20836. this._animationStarted = false;
  20837. if (this.disposeWhenFinishedAnimating) {
  20838. this.dispose();
  20839. }
  20840. }
  20841. }
  20842. }
  20843. };
  20844. Sprite.prototype.dispose = function () {
  20845. for (var i = 0; i < this._manager.sprites.length; i++) {
  20846. if (this._manager.sprites[i] == this) {
  20847. this._manager.sprites.splice(i, 1);
  20848. }
  20849. }
  20850. };
  20851. return Sprite;
  20852. })();
  20853. BABYLON.Sprite = Sprite;
  20854. })(BABYLON || (BABYLON = {}));
  20855. var BABYLON;
  20856. (function (BABYLON) {
  20857. var Layer = (function () {
  20858. function Layer(name, imgUrl, scene, isBackground, color) {
  20859. this.name = name;
  20860. this._vertexDeclaration = [2];
  20861. this._vertexStrideSize = 2 * 4;
  20862. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20863. this.isBackground = isBackground === undefined ? true : isBackground;
  20864. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20865. this._scene = scene;
  20866. this._scene.layers.push(this);
  20867. // VBO
  20868. var vertices = [];
  20869. vertices.push(1, 1);
  20870. vertices.push(-1, 1);
  20871. vertices.push(-1, -1);
  20872. vertices.push(1, -1);
  20873. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20874. // Indices
  20875. var indices = [];
  20876. indices.push(0);
  20877. indices.push(1);
  20878. indices.push(2);
  20879. indices.push(0);
  20880. indices.push(2);
  20881. indices.push(3);
  20882. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20883. // Effects
  20884. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20885. }
  20886. Layer.prototype.render = function () {
  20887. // Check
  20888. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20889. return;
  20890. var engine = this._scene.getEngine();
  20891. // Render
  20892. engine.enableEffect(this._effect);
  20893. engine.setState(false);
  20894. // Texture
  20895. this._effect.setTexture("textureSampler", this.texture);
  20896. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20897. // Color
  20898. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20899. // VBOs
  20900. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20901. // Draw order
  20902. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20903. engine.draw(true, 0, 6);
  20904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20905. };
  20906. Layer.prototype.dispose = function () {
  20907. if (this._vertexBuffer) {
  20908. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20909. this._vertexBuffer = null;
  20910. }
  20911. if (this._indexBuffer) {
  20912. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20913. this._indexBuffer = null;
  20914. }
  20915. if (this.texture) {
  20916. this.texture.dispose();
  20917. this.texture = null;
  20918. }
  20919. // Remove from scene
  20920. var index = this._scene.layers.indexOf(this);
  20921. this._scene.layers.splice(index, 1);
  20922. // Callback
  20923. if (this.onDispose) {
  20924. this.onDispose();
  20925. }
  20926. };
  20927. return Layer;
  20928. })();
  20929. BABYLON.Layer = Layer;
  20930. })(BABYLON || (BABYLON = {}));
  20931. var BABYLON;
  20932. (function (BABYLON) {
  20933. var Particle = (function () {
  20934. function Particle() {
  20935. this.position = BABYLON.Vector3.Zero();
  20936. this.direction = BABYLON.Vector3.Zero();
  20937. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20938. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20939. this.lifeTime = 1.0;
  20940. this.age = 0;
  20941. this.size = 0;
  20942. this.angle = 0;
  20943. this.angularSpeed = 0;
  20944. }
  20945. Particle.prototype.copyTo = function (other) {
  20946. other.position.copyFrom(this.position);
  20947. other.direction.copyFrom(this.direction);
  20948. other.color.copyFrom(this.color);
  20949. other.colorStep.copyFrom(this.colorStep);
  20950. other.lifeTime = this.lifeTime;
  20951. other.age = this.age;
  20952. other.size = this.size;
  20953. other.angle = this.angle;
  20954. other.angularSpeed = this.angularSpeed;
  20955. };
  20956. return Particle;
  20957. })();
  20958. BABYLON.Particle = Particle;
  20959. })(BABYLON || (BABYLON = {}));
  20960. var BABYLON;
  20961. (function (BABYLON) {
  20962. var randomNumber = function (min, max) {
  20963. if (min === max) {
  20964. return (min);
  20965. }
  20966. var random = Math.random();
  20967. return ((random * (max - min)) + min);
  20968. };
  20969. var ParticleSystem = (function () {
  20970. function ParticleSystem(name, capacity, scene, customEffect) {
  20971. var _this = this;
  20972. this.name = name;
  20973. this.renderingGroupId = 0;
  20974. this.emitter = null;
  20975. this.emitRate = 10;
  20976. this.manualEmitCount = -1;
  20977. this.updateSpeed = 0.01;
  20978. this.targetStopDuration = 0;
  20979. this.disposeOnStop = false;
  20980. this.minEmitPower = 1;
  20981. this.maxEmitPower = 1;
  20982. this.minLifeTime = 1;
  20983. this.maxLifeTime = 1;
  20984. this.minSize = 1;
  20985. this.maxSize = 1;
  20986. this.minAngularSpeed = 0;
  20987. this.maxAngularSpeed = 0;
  20988. this.layerMask = 0x0FFFFFFF;
  20989. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20990. this.forceDepthWrite = false;
  20991. this.gravity = BABYLON.Vector3.Zero();
  20992. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20993. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20994. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20995. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20996. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20997. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20998. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20999. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21000. this.particles = new Array();
  21001. this._vertexDeclaration = [3, 4, 4];
  21002. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21003. this._stockParticles = new Array();
  21004. this._newPartsExcess = 0;
  21005. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21006. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21007. this._scaledDirection = BABYLON.Vector3.Zero();
  21008. this._scaledGravity = BABYLON.Vector3.Zero();
  21009. this._currentRenderId = -1;
  21010. this._started = false;
  21011. this._stopped = false;
  21012. this._actualFrame = 0;
  21013. this.id = name;
  21014. this._capacity = capacity;
  21015. this._scene = scene;
  21016. this._customEffect = customEffect;
  21017. scene.particleSystems.push(this);
  21018. // VBO
  21019. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21020. var indices = [];
  21021. var index = 0;
  21022. for (var count = 0; count < capacity; count++) {
  21023. indices.push(index);
  21024. indices.push(index + 1);
  21025. indices.push(index + 2);
  21026. indices.push(index);
  21027. indices.push(index + 2);
  21028. indices.push(index + 3);
  21029. index += 4;
  21030. }
  21031. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21032. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21033. // Default behaviors
  21034. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21035. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21036. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21037. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21038. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21039. };
  21040. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21041. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21042. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21043. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21044. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21045. };
  21046. this.updateFunction = function (particles) {
  21047. for (var index = 0; index < particles.length; index++) {
  21048. var particle = particles[index];
  21049. particle.age += _this._scaledUpdateSpeed;
  21050. if (particle.age >= particle.lifeTime) {
  21051. _this.recycleParticle(particle);
  21052. index--;
  21053. continue;
  21054. }
  21055. else {
  21056. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21057. particle.color.addInPlace(_this._scaledColorStep);
  21058. if (particle.color.a < 0)
  21059. particle.color.a = 0;
  21060. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21061. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21062. particle.position.addInPlace(_this._scaledDirection);
  21063. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21064. particle.direction.addInPlace(_this._scaledGravity);
  21065. }
  21066. }
  21067. };
  21068. }
  21069. ParticleSystem.prototype.recycleParticle = function (particle) {
  21070. var lastParticle = this.particles.pop();
  21071. if (lastParticle !== particle) {
  21072. lastParticle.copyTo(particle);
  21073. this._stockParticles.push(lastParticle);
  21074. }
  21075. };
  21076. ParticleSystem.prototype.getCapacity = function () {
  21077. return this._capacity;
  21078. };
  21079. ParticleSystem.prototype.isAlive = function () {
  21080. return this._alive;
  21081. };
  21082. ParticleSystem.prototype.isStarted = function () {
  21083. return this._started;
  21084. };
  21085. ParticleSystem.prototype.start = function () {
  21086. this._started = true;
  21087. this._stopped = false;
  21088. this._actualFrame = 0;
  21089. };
  21090. ParticleSystem.prototype.stop = function () {
  21091. this._stopped = true;
  21092. };
  21093. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21094. var offset = index * 11;
  21095. this._vertices[offset] = particle.position.x;
  21096. this._vertices[offset + 1] = particle.position.y;
  21097. this._vertices[offset + 2] = particle.position.z;
  21098. this._vertices[offset + 3] = particle.color.r;
  21099. this._vertices[offset + 4] = particle.color.g;
  21100. this._vertices[offset + 5] = particle.color.b;
  21101. this._vertices[offset + 6] = particle.color.a;
  21102. this._vertices[offset + 7] = particle.angle;
  21103. this._vertices[offset + 8] = particle.size;
  21104. this._vertices[offset + 9] = offsetX;
  21105. this._vertices[offset + 10] = offsetY;
  21106. };
  21107. ParticleSystem.prototype._update = function (newParticles) {
  21108. // Update current
  21109. this._alive = this.particles.length > 0;
  21110. this.updateFunction(this.particles);
  21111. // Add new ones
  21112. var worldMatrix;
  21113. if (this.emitter.position) {
  21114. worldMatrix = this.emitter.getWorldMatrix();
  21115. }
  21116. else {
  21117. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21118. }
  21119. for (var index = 0; index < newParticles; index++) {
  21120. if (this.particles.length === this._capacity) {
  21121. break;
  21122. }
  21123. if (this._stockParticles.length !== 0) {
  21124. var particle = this._stockParticles.pop();
  21125. particle.age = 0;
  21126. }
  21127. else {
  21128. particle = new BABYLON.Particle();
  21129. }
  21130. this.particles.push(particle);
  21131. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21132. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21133. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21134. particle.size = randomNumber(this.minSize, this.maxSize);
  21135. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21136. this.startPositionFunction(worldMatrix, particle.position);
  21137. var step = randomNumber(0, 1.0);
  21138. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21139. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21140. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21141. }
  21142. };
  21143. ParticleSystem.prototype._getEffect = function () {
  21144. if (this._customEffect) {
  21145. return this._customEffect;
  21146. }
  21147. ;
  21148. var defines = [];
  21149. if (this._scene.clipPlane) {
  21150. defines.push("#define CLIPPLANE");
  21151. }
  21152. // Effect
  21153. var join = defines.join("\n");
  21154. if (this._cachedDefines !== join) {
  21155. this._cachedDefines = join;
  21156. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21157. }
  21158. return this._effect;
  21159. };
  21160. ParticleSystem.prototype.animate = function () {
  21161. if (!this._started)
  21162. return;
  21163. var effect = this._getEffect();
  21164. // Check
  21165. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21166. return;
  21167. if (this._currentRenderId === this._scene.getRenderId()) {
  21168. return;
  21169. }
  21170. this._currentRenderId = this._scene.getRenderId();
  21171. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21172. // determine the number of particles we need to create
  21173. var emitCout;
  21174. if (this.manualEmitCount > -1) {
  21175. emitCout = this.manualEmitCount;
  21176. this.manualEmitCount = 0;
  21177. }
  21178. else {
  21179. emitCout = this.emitRate;
  21180. }
  21181. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21182. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21183. if (this._newPartsExcess > 1.0) {
  21184. newParticles += this._newPartsExcess >> 0;
  21185. this._newPartsExcess -= this._newPartsExcess >> 0;
  21186. }
  21187. this._alive = false;
  21188. if (!this._stopped) {
  21189. this._actualFrame += this._scaledUpdateSpeed;
  21190. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21191. this.stop();
  21192. }
  21193. else {
  21194. newParticles = 0;
  21195. }
  21196. this._update(newParticles);
  21197. // Stopped?
  21198. if (this._stopped) {
  21199. if (!this._alive) {
  21200. this._started = false;
  21201. if (this.disposeOnStop) {
  21202. this._scene._toBeDisposed.push(this);
  21203. }
  21204. }
  21205. }
  21206. // Update VBO
  21207. var offset = 0;
  21208. for (var index = 0; index < this.particles.length; index++) {
  21209. var particle = this.particles[index];
  21210. this._appendParticleVertex(offset++, particle, 0, 0);
  21211. this._appendParticleVertex(offset++, particle, 1, 0);
  21212. this._appendParticleVertex(offset++, particle, 1, 1);
  21213. this._appendParticleVertex(offset++, particle, 0, 1);
  21214. }
  21215. var engine = this._scene.getEngine();
  21216. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21217. };
  21218. ParticleSystem.prototype.render = function () {
  21219. var effect = this._getEffect();
  21220. // Check
  21221. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21222. return 0;
  21223. var engine = this._scene.getEngine();
  21224. // Render
  21225. engine.enableEffect(effect);
  21226. engine.setState(false);
  21227. var viewMatrix = this._scene.getViewMatrix();
  21228. effect.setTexture("diffuseSampler", this.particleTexture);
  21229. effect.setMatrix("view", viewMatrix);
  21230. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21231. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21232. if (this._scene.clipPlane) {
  21233. var clipPlane = this._scene.clipPlane;
  21234. var invView = viewMatrix.clone();
  21235. invView.invert();
  21236. effect.setMatrix("invView", invView);
  21237. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21238. }
  21239. // VBOs
  21240. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21241. // Draw order
  21242. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21243. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21244. }
  21245. else {
  21246. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21247. }
  21248. if (this.forceDepthWrite) {
  21249. engine.setDepthWrite(true);
  21250. }
  21251. engine.draw(true, 0, this.particles.length * 6);
  21252. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21253. return this.particles.length;
  21254. };
  21255. ParticleSystem.prototype.dispose = function () {
  21256. if (this._vertexBuffer) {
  21257. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21258. this._vertexBuffer = null;
  21259. }
  21260. if (this._indexBuffer) {
  21261. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21262. this._indexBuffer = null;
  21263. }
  21264. if (this.particleTexture) {
  21265. this.particleTexture.dispose();
  21266. this.particleTexture = null;
  21267. }
  21268. // Remove from scene
  21269. var index = this._scene.particleSystems.indexOf(this);
  21270. this._scene.particleSystems.splice(index, 1);
  21271. // Callback
  21272. if (this.onDispose) {
  21273. this.onDispose();
  21274. }
  21275. };
  21276. // Clone
  21277. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21278. var result = new ParticleSystem(name, this._capacity, this._scene);
  21279. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21280. if (newEmitter === undefined) {
  21281. newEmitter = this.emitter;
  21282. }
  21283. result.emitter = newEmitter;
  21284. if (this.particleTexture) {
  21285. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21286. }
  21287. result.start();
  21288. return result;
  21289. };
  21290. // Statics
  21291. ParticleSystem.BLENDMODE_ONEONE = 0;
  21292. ParticleSystem.BLENDMODE_STANDARD = 1;
  21293. return ParticleSystem;
  21294. })();
  21295. BABYLON.ParticleSystem = ParticleSystem;
  21296. })(BABYLON || (BABYLON = {}));
  21297. var BABYLON;
  21298. (function (BABYLON) {
  21299. var AnimationRange = (function () {
  21300. function AnimationRange(name, from, to) {
  21301. this.name = name;
  21302. this.from = from;
  21303. this.to = to;
  21304. }
  21305. return AnimationRange;
  21306. })();
  21307. BABYLON.AnimationRange = AnimationRange;
  21308. var Animation = (function () {
  21309. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21310. this.name = name;
  21311. this.targetProperty = targetProperty;
  21312. this.framePerSecond = framePerSecond;
  21313. this.dataType = dataType;
  21314. this.loopMode = loopMode;
  21315. this._offsetsCache = {};
  21316. this._highLimitsCache = {};
  21317. this._stopped = false;
  21318. this.allowMatricesInterpolation = false;
  21319. this._ranges = new Array();
  21320. this.targetPropertyPath = targetProperty.split(".");
  21321. this.dataType = dataType;
  21322. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21323. }
  21324. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21325. var dataType = undefined;
  21326. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21327. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21328. }
  21329. else if (from instanceof BABYLON.Quaternion) {
  21330. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21331. }
  21332. else if (from instanceof BABYLON.Vector3) {
  21333. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21334. }
  21335. else if (from instanceof BABYLON.Vector2) {
  21336. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21337. }
  21338. else if (from instanceof BABYLON.Color3) {
  21339. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21340. }
  21341. if (dataType == undefined) {
  21342. return null;
  21343. }
  21344. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21345. var keys = [];
  21346. keys.push({ frame: 0, value: from });
  21347. keys.push({ frame: totalFrame, value: to });
  21348. animation.setKeys(keys);
  21349. if (easingFunction !== undefined) {
  21350. animation.setEasingFunction(easingFunction);
  21351. }
  21352. mesh.animations.push(animation);
  21353. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21354. };
  21355. // Methods
  21356. Animation.prototype.createRange = function (name, from, to) {
  21357. this._ranges.push(new AnimationRange(name, from, to));
  21358. };
  21359. Animation.prototype.deleteRange = function (name) {
  21360. for (var index = 0; index < this._ranges.length; index++) {
  21361. if (this._ranges[index].name === name) {
  21362. this._ranges.splice(index, 1);
  21363. return;
  21364. }
  21365. }
  21366. };
  21367. Animation.prototype.getRange = function (name) {
  21368. for (var index = 0; index < this._ranges.length; index++) {
  21369. if (this._ranges[index].name === name) {
  21370. return this._ranges[index];
  21371. }
  21372. }
  21373. return null;
  21374. };
  21375. Animation.prototype.reset = function () {
  21376. this._offsetsCache = {};
  21377. this._highLimitsCache = {};
  21378. this.currentFrame = 0;
  21379. };
  21380. Animation.prototype.isStopped = function () {
  21381. return this._stopped;
  21382. };
  21383. Animation.prototype.getKeys = function () {
  21384. return this._keys;
  21385. };
  21386. Animation.prototype.getEasingFunction = function () {
  21387. return this._easingFunction;
  21388. };
  21389. Animation.prototype.setEasingFunction = function (easingFunction) {
  21390. this._easingFunction = easingFunction;
  21391. };
  21392. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21393. return startValue + (endValue - startValue) * gradient;
  21394. };
  21395. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21396. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21397. };
  21398. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21399. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21400. };
  21401. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21402. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21403. };
  21404. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21405. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21406. };
  21407. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21408. var startScale = new BABYLON.Vector3(0, 0, 0);
  21409. var startRotation = new BABYLON.Quaternion();
  21410. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21411. startValue.decompose(startScale, startRotation, startTranslation);
  21412. var endScale = new BABYLON.Vector3(0, 0, 0);
  21413. var endRotation = new BABYLON.Quaternion();
  21414. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21415. endValue.decompose(endScale, endRotation, endTranslation);
  21416. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21417. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21418. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21419. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21420. return result;
  21421. };
  21422. Animation.prototype.clone = function () {
  21423. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21424. if (this._keys) {
  21425. clone.setKeys(this._keys);
  21426. }
  21427. return clone;
  21428. };
  21429. Animation.prototype.setKeys = function (values) {
  21430. this._keys = values.slice(0);
  21431. this._offsetsCache = {};
  21432. this._highLimitsCache = {};
  21433. };
  21434. Animation.prototype._getKeyValue = function (value) {
  21435. if (typeof value === "function") {
  21436. return value();
  21437. }
  21438. return value;
  21439. };
  21440. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21441. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21442. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21443. }
  21444. this.currentFrame = currentFrame;
  21445. // Try to get a hash to find the right key
  21446. 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));
  21447. if (this._keys[startKey].frame >= currentFrame) {
  21448. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21449. startKey--;
  21450. }
  21451. }
  21452. for (var key = startKey; key < this._keys.length; key++) {
  21453. if (this._keys[key + 1].frame >= currentFrame) {
  21454. var startValue = this._getKeyValue(this._keys[key].value);
  21455. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21456. // gradient : percent of currentFrame between the frame inf and the frame sup
  21457. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21458. // check for easingFunction and correction of gradient
  21459. if (this._easingFunction != null) {
  21460. gradient = this._easingFunction.ease(gradient);
  21461. }
  21462. switch (this.dataType) {
  21463. // Float
  21464. case Animation.ANIMATIONTYPE_FLOAT:
  21465. switch (loopMode) {
  21466. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21467. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21468. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21469. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21470. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21471. }
  21472. break;
  21473. // Quaternion
  21474. case Animation.ANIMATIONTYPE_QUATERNION:
  21475. var quaternion = null;
  21476. switch (loopMode) {
  21477. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21478. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21479. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21480. break;
  21481. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21482. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21483. break;
  21484. }
  21485. return quaternion;
  21486. // Vector3
  21487. case Animation.ANIMATIONTYPE_VECTOR3:
  21488. switch (loopMode) {
  21489. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21490. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21491. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21492. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21493. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21494. }
  21495. // Vector2
  21496. case Animation.ANIMATIONTYPE_VECTOR2:
  21497. switch (loopMode) {
  21498. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21499. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21500. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21501. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21502. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21503. }
  21504. // Color3
  21505. case Animation.ANIMATIONTYPE_COLOR3:
  21506. switch (loopMode) {
  21507. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21508. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21509. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21511. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21512. }
  21513. // Matrix
  21514. case Animation.ANIMATIONTYPE_MATRIX:
  21515. switch (loopMode) {
  21516. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21517. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21518. if (this.allowMatricesInterpolation) {
  21519. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21520. }
  21521. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21522. return startValue;
  21523. }
  21524. default:
  21525. break;
  21526. }
  21527. break;
  21528. }
  21529. }
  21530. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21531. };
  21532. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21533. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21534. this._stopped = true;
  21535. return false;
  21536. }
  21537. var returnValue = true;
  21538. // Adding a start key at frame 0 if missing
  21539. if (this._keys[0].frame !== 0) {
  21540. var newKey = { frame: 0, value: this._keys[0].value };
  21541. this._keys.splice(0, 0, newKey);
  21542. }
  21543. // Check limits
  21544. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21545. from = this._keys[0].frame;
  21546. }
  21547. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21548. to = this._keys[this._keys.length - 1].frame;
  21549. }
  21550. // Compute ratio
  21551. var range = to - from;
  21552. var offsetValue;
  21553. // ratio represents the frame delta between from and to
  21554. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21555. var highLimitValue = 0;
  21556. if (ratio > range && !loop) {
  21557. returnValue = false;
  21558. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21559. }
  21560. else {
  21561. // Get max value if required
  21562. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21563. var keyOffset = to.toString() + from.toString();
  21564. if (!this._offsetsCache[keyOffset]) {
  21565. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21566. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21567. switch (this.dataType) {
  21568. // Float
  21569. case Animation.ANIMATIONTYPE_FLOAT:
  21570. this._offsetsCache[keyOffset] = toValue - fromValue;
  21571. break;
  21572. // Quaternion
  21573. case Animation.ANIMATIONTYPE_QUATERNION:
  21574. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21575. break;
  21576. // Vector3
  21577. case Animation.ANIMATIONTYPE_VECTOR3:
  21578. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21579. // Vector2
  21580. case Animation.ANIMATIONTYPE_VECTOR2:
  21581. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21582. // Color3
  21583. case Animation.ANIMATIONTYPE_COLOR3:
  21584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21585. default:
  21586. break;
  21587. }
  21588. this._highLimitsCache[keyOffset] = toValue;
  21589. }
  21590. highLimitValue = this._highLimitsCache[keyOffset];
  21591. offsetValue = this._offsetsCache[keyOffset];
  21592. }
  21593. }
  21594. if (offsetValue === undefined) {
  21595. switch (this.dataType) {
  21596. // Float
  21597. case Animation.ANIMATIONTYPE_FLOAT:
  21598. offsetValue = 0;
  21599. break;
  21600. // Quaternion
  21601. case Animation.ANIMATIONTYPE_QUATERNION:
  21602. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21603. break;
  21604. // Vector3
  21605. case Animation.ANIMATIONTYPE_VECTOR3:
  21606. offsetValue = BABYLON.Vector3.Zero();
  21607. break;
  21608. // Vector2
  21609. case Animation.ANIMATIONTYPE_VECTOR2:
  21610. offsetValue = BABYLON.Vector2.Zero();
  21611. break;
  21612. // Color3
  21613. case Animation.ANIMATIONTYPE_COLOR3:
  21614. offsetValue = BABYLON.Color3.Black();
  21615. }
  21616. }
  21617. // Compute value
  21618. var repeatCount = (ratio / range) >> 0;
  21619. var currentFrame = returnValue ? from + ratio % range : to;
  21620. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21621. // Set value
  21622. if (this.targetPropertyPath.length > 1) {
  21623. var property = this._target[this.targetPropertyPath[0]];
  21624. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21625. property = property[this.targetPropertyPath[index]];
  21626. }
  21627. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21628. }
  21629. else {
  21630. this._target[this.targetPropertyPath[0]] = currentValue;
  21631. }
  21632. if (this._target.markAsDirty) {
  21633. this._target.markAsDirty(this.targetProperty);
  21634. }
  21635. if (!returnValue) {
  21636. this._stopped = true;
  21637. }
  21638. return returnValue;
  21639. };
  21640. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21641. get: function () {
  21642. return Animation._ANIMATIONTYPE_FLOAT;
  21643. },
  21644. enumerable: true,
  21645. configurable: true
  21646. });
  21647. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21648. get: function () {
  21649. return Animation._ANIMATIONTYPE_VECTOR3;
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21655. get: function () {
  21656. return Animation._ANIMATIONTYPE_VECTOR2;
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21662. get: function () {
  21663. return Animation._ANIMATIONTYPE_QUATERNION;
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21669. get: function () {
  21670. return Animation._ANIMATIONTYPE_MATRIX;
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21676. get: function () {
  21677. return Animation._ANIMATIONTYPE_COLOR3;
  21678. },
  21679. enumerable: true,
  21680. configurable: true
  21681. });
  21682. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21683. get: function () {
  21684. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21690. get: function () {
  21691. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21692. },
  21693. enumerable: true,
  21694. configurable: true
  21695. });
  21696. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21697. get: function () {
  21698. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21699. },
  21700. enumerable: true,
  21701. configurable: true
  21702. });
  21703. // Statics
  21704. Animation._ANIMATIONTYPE_FLOAT = 0;
  21705. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21706. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21707. Animation._ANIMATIONTYPE_MATRIX = 3;
  21708. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21709. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21710. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21711. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21712. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21713. return Animation;
  21714. })();
  21715. BABYLON.Animation = Animation;
  21716. })(BABYLON || (BABYLON = {}));
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var Animatable = (function () {
  21720. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21721. if (fromFrame === void 0) { fromFrame = 0; }
  21722. if (toFrame === void 0) { toFrame = 100; }
  21723. if (loopAnimation === void 0) { loopAnimation = false; }
  21724. if (speedRatio === void 0) { speedRatio = 1.0; }
  21725. this.target = target;
  21726. this.fromFrame = fromFrame;
  21727. this.toFrame = toFrame;
  21728. this.loopAnimation = loopAnimation;
  21729. this.speedRatio = speedRatio;
  21730. this.onAnimationEnd = onAnimationEnd;
  21731. this._animations = new Array();
  21732. this._paused = false;
  21733. this.animationStarted = false;
  21734. if (animations) {
  21735. this.appendAnimations(target, animations);
  21736. }
  21737. this._scene = scene;
  21738. scene._activeAnimatables.push(this);
  21739. }
  21740. // Methods
  21741. Animatable.prototype.getAnimations = function () {
  21742. return this._animations;
  21743. };
  21744. Animatable.prototype.appendAnimations = function (target, animations) {
  21745. for (var index = 0; index < animations.length; index++) {
  21746. var animation = animations[index];
  21747. animation._target = target;
  21748. this._animations.push(animation);
  21749. }
  21750. };
  21751. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21752. var animations = this._animations;
  21753. for (var index = 0; index < animations.length; index++) {
  21754. if (animations[index].targetProperty === property) {
  21755. return animations[index];
  21756. }
  21757. }
  21758. return null;
  21759. };
  21760. Animatable.prototype.reset = function () {
  21761. var animations = this._animations;
  21762. for (var index = 0; index < animations.length; index++) {
  21763. animations[index].reset();
  21764. }
  21765. this._localDelayOffset = null;
  21766. this._pausedDelay = null;
  21767. };
  21768. Animatable.prototype.pause = function () {
  21769. if (this._paused) {
  21770. return;
  21771. }
  21772. this._paused = true;
  21773. };
  21774. Animatable.prototype.restart = function () {
  21775. this._paused = false;
  21776. };
  21777. Animatable.prototype.stop = function () {
  21778. var index = this._scene._activeAnimatables.indexOf(this);
  21779. if (index > -1) {
  21780. this._scene._activeAnimatables.splice(index, 1);
  21781. }
  21782. if (this.onAnimationEnd) {
  21783. this.onAnimationEnd();
  21784. }
  21785. };
  21786. Animatable.prototype._animate = function (delay) {
  21787. if (this._paused) {
  21788. if (!this._pausedDelay) {
  21789. this._pausedDelay = delay;
  21790. }
  21791. return true;
  21792. }
  21793. if (!this._localDelayOffset) {
  21794. this._localDelayOffset = delay;
  21795. }
  21796. else if (this._pausedDelay) {
  21797. this._localDelayOffset += delay - this._pausedDelay;
  21798. this._pausedDelay = null;
  21799. }
  21800. // Animating
  21801. var running = false;
  21802. var animations = this._animations;
  21803. for (var index = 0; index < animations.length; index++) {
  21804. var animation = animations[index];
  21805. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21806. running = running || isRunning;
  21807. }
  21808. if (!running) {
  21809. // Remove from active animatables
  21810. index = this._scene._activeAnimatables.indexOf(this);
  21811. this._scene._activeAnimatables.splice(index, 1);
  21812. }
  21813. if (!running && this.onAnimationEnd) {
  21814. this.onAnimationEnd();
  21815. }
  21816. return running;
  21817. };
  21818. return Animatable;
  21819. })();
  21820. BABYLON.Animatable = Animatable;
  21821. })(BABYLON || (BABYLON = {}));
  21822. var BABYLON;
  21823. (function (BABYLON) {
  21824. var EasingFunction = (function () {
  21825. function EasingFunction() {
  21826. // Properties
  21827. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21828. }
  21829. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21830. get: function () {
  21831. return EasingFunction._EASINGMODE_EASEIN;
  21832. },
  21833. enumerable: true,
  21834. configurable: true
  21835. });
  21836. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21837. get: function () {
  21838. return EasingFunction._EASINGMODE_EASEOUT;
  21839. },
  21840. enumerable: true,
  21841. configurable: true
  21842. });
  21843. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21844. get: function () {
  21845. return EasingFunction._EASINGMODE_EASEINOUT;
  21846. },
  21847. enumerable: true,
  21848. configurable: true
  21849. });
  21850. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21851. var n = Math.min(Math.max(easingMode, 0), 2);
  21852. this._easingMode = n;
  21853. };
  21854. EasingFunction.prototype.getEasingMode = function () {
  21855. return this._easingMode;
  21856. };
  21857. EasingFunction.prototype.easeInCore = function (gradient) {
  21858. throw new Error('You must implement this method');
  21859. };
  21860. EasingFunction.prototype.ease = function (gradient) {
  21861. switch (this._easingMode) {
  21862. case EasingFunction.EASINGMODE_EASEIN:
  21863. return this.easeInCore(gradient);
  21864. case EasingFunction.EASINGMODE_EASEOUT:
  21865. return (1 - this.easeInCore(1 - gradient));
  21866. }
  21867. if (gradient >= 0.5) {
  21868. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21869. }
  21870. return (this.easeInCore(gradient * 2) * 0.5);
  21871. };
  21872. //Statics
  21873. EasingFunction._EASINGMODE_EASEIN = 0;
  21874. EasingFunction._EASINGMODE_EASEOUT = 1;
  21875. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21876. return EasingFunction;
  21877. })();
  21878. BABYLON.EasingFunction = EasingFunction;
  21879. var CircleEase = (function (_super) {
  21880. __extends(CircleEase, _super);
  21881. function CircleEase() {
  21882. _super.apply(this, arguments);
  21883. }
  21884. CircleEase.prototype.easeInCore = function (gradient) {
  21885. gradient = Math.max(0, Math.min(1, gradient));
  21886. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21887. };
  21888. return CircleEase;
  21889. })(EasingFunction);
  21890. BABYLON.CircleEase = CircleEase;
  21891. var BackEase = (function (_super) {
  21892. __extends(BackEase, _super);
  21893. function BackEase(amplitude) {
  21894. if (amplitude === void 0) { amplitude = 1; }
  21895. _super.call(this);
  21896. this.amplitude = amplitude;
  21897. }
  21898. BackEase.prototype.easeInCore = function (gradient) {
  21899. var num = Math.max(0, this.amplitude);
  21900. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21901. };
  21902. return BackEase;
  21903. })(EasingFunction);
  21904. BABYLON.BackEase = BackEase;
  21905. var BounceEase = (function (_super) {
  21906. __extends(BounceEase, _super);
  21907. function BounceEase(bounces, bounciness) {
  21908. if (bounces === void 0) { bounces = 3; }
  21909. if (bounciness === void 0) { bounciness = 2; }
  21910. _super.call(this);
  21911. this.bounces = bounces;
  21912. this.bounciness = bounciness;
  21913. }
  21914. BounceEase.prototype.easeInCore = function (gradient) {
  21915. var y = Math.max(0.0, this.bounces);
  21916. var bounciness = this.bounciness;
  21917. if (bounciness <= 1.0) {
  21918. bounciness = 1.001;
  21919. }
  21920. var num9 = Math.pow(bounciness, y);
  21921. var num5 = 1.0 - bounciness;
  21922. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21923. var num15 = gradient * num4;
  21924. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21925. var num3 = Math.floor(num65);
  21926. var num13 = num3 + 1.0;
  21927. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21928. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21929. var num7 = (num8 + num12) * 0.5;
  21930. var num6 = gradient - num7;
  21931. var num2 = num7 - num8;
  21932. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21933. };
  21934. return BounceEase;
  21935. })(EasingFunction);
  21936. BABYLON.BounceEase = BounceEase;
  21937. var CubicEase = (function (_super) {
  21938. __extends(CubicEase, _super);
  21939. function CubicEase() {
  21940. _super.apply(this, arguments);
  21941. }
  21942. CubicEase.prototype.easeInCore = function (gradient) {
  21943. return (gradient * gradient * gradient);
  21944. };
  21945. return CubicEase;
  21946. })(EasingFunction);
  21947. BABYLON.CubicEase = CubicEase;
  21948. var ElasticEase = (function (_super) {
  21949. __extends(ElasticEase, _super);
  21950. function ElasticEase(oscillations, springiness) {
  21951. if (oscillations === void 0) { oscillations = 3; }
  21952. if (springiness === void 0) { springiness = 3; }
  21953. _super.call(this);
  21954. this.oscillations = oscillations;
  21955. this.springiness = springiness;
  21956. }
  21957. ElasticEase.prototype.easeInCore = function (gradient) {
  21958. var num2;
  21959. var num3 = Math.max(0.0, this.oscillations);
  21960. var num = Math.max(0.0, this.springiness);
  21961. if (num == 0) {
  21962. num2 = gradient;
  21963. }
  21964. else {
  21965. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21966. }
  21967. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21968. };
  21969. return ElasticEase;
  21970. })(EasingFunction);
  21971. BABYLON.ElasticEase = ElasticEase;
  21972. var ExponentialEase = (function (_super) {
  21973. __extends(ExponentialEase, _super);
  21974. function ExponentialEase(exponent) {
  21975. if (exponent === void 0) { exponent = 2; }
  21976. _super.call(this);
  21977. this.exponent = exponent;
  21978. }
  21979. ExponentialEase.prototype.easeInCore = function (gradient) {
  21980. if (this.exponent <= 0) {
  21981. return gradient;
  21982. }
  21983. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21984. };
  21985. return ExponentialEase;
  21986. })(EasingFunction);
  21987. BABYLON.ExponentialEase = ExponentialEase;
  21988. var PowerEase = (function (_super) {
  21989. __extends(PowerEase, _super);
  21990. function PowerEase(power) {
  21991. if (power === void 0) { power = 2; }
  21992. _super.call(this);
  21993. this.power = power;
  21994. }
  21995. PowerEase.prototype.easeInCore = function (gradient) {
  21996. var y = Math.max(0.0, this.power);
  21997. return Math.pow(gradient, y);
  21998. };
  21999. return PowerEase;
  22000. })(EasingFunction);
  22001. BABYLON.PowerEase = PowerEase;
  22002. var QuadraticEase = (function (_super) {
  22003. __extends(QuadraticEase, _super);
  22004. function QuadraticEase() {
  22005. _super.apply(this, arguments);
  22006. }
  22007. QuadraticEase.prototype.easeInCore = function (gradient) {
  22008. return (gradient * gradient);
  22009. };
  22010. return QuadraticEase;
  22011. })(EasingFunction);
  22012. BABYLON.QuadraticEase = QuadraticEase;
  22013. var QuarticEase = (function (_super) {
  22014. __extends(QuarticEase, _super);
  22015. function QuarticEase() {
  22016. _super.apply(this, arguments);
  22017. }
  22018. QuarticEase.prototype.easeInCore = function (gradient) {
  22019. return (gradient * gradient * gradient * gradient);
  22020. };
  22021. return QuarticEase;
  22022. })(EasingFunction);
  22023. BABYLON.QuarticEase = QuarticEase;
  22024. var QuinticEase = (function (_super) {
  22025. __extends(QuinticEase, _super);
  22026. function QuinticEase() {
  22027. _super.apply(this, arguments);
  22028. }
  22029. QuinticEase.prototype.easeInCore = function (gradient) {
  22030. return (gradient * gradient * gradient * gradient * gradient);
  22031. };
  22032. return QuinticEase;
  22033. })(EasingFunction);
  22034. BABYLON.QuinticEase = QuinticEase;
  22035. var SineEase = (function (_super) {
  22036. __extends(SineEase, _super);
  22037. function SineEase() {
  22038. _super.apply(this, arguments);
  22039. }
  22040. SineEase.prototype.easeInCore = function (gradient) {
  22041. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22042. };
  22043. return SineEase;
  22044. })(EasingFunction);
  22045. BABYLON.SineEase = SineEase;
  22046. var BezierCurveEase = (function (_super) {
  22047. __extends(BezierCurveEase, _super);
  22048. function BezierCurveEase(x1, y1, x2, y2) {
  22049. if (x1 === void 0) { x1 = 0; }
  22050. if (y1 === void 0) { y1 = 0; }
  22051. if (x2 === void 0) { x2 = 1; }
  22052. if (y2 === void 0) { y2 = 1; }
  22053. _super.call(this);
  22054. this.x1 = x1;
  22055. this.y1 = y1;
  22056. this.x2 = x2;
  22057. this.y2 = y2;
  22058. }
  22059. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22060. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22061. };
  22062. return BezierCurveEase;
  22063. })(EasingFunction);
  22064. BABYLON.BezierCurveEase = BezierCurveEase;
  22065. })(BABYLON || (BABYLON = {}));
  22066. var BABYLON;
  22067. (function (BABYLON) {
  22068. var Bone = (function (_super) {
  22069. __extends(Bone, _super);
  22070. function Bone(name, skeleton, parentBone, matrix) {
  22071. _super.call(this, name, skeleton.getScene());
  22072. this.name = name;
  22073. this.children = new Array();
  22074. this.animations = new Array();
  22075. this._worldTransform = new BABYLON.Matrix();
  22076. this._absoluteTransform = new BABYLON.Matrix();
  22077. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22078. this._skeleton = skeleton;
  22079. this._matrix = matrix;
  22080. this._baseMatrix = matrix;
  22081. skeleton.bones.push(this);
  22082. if (parentBone) {
  22083. this._parent = parentBone;
  22084. parentBone.children.push(this);
  22085. }
  22086. else {
  22087. this._parent = null;
  22088. }
  22089. this._updateDifferenceMatrix();
  22090. }
  22091. // Members
  22092. Bone.prototype.getParent = function () {
  22093. return this._parent;
  22094. };
  22095. Bone.prototype.getLocalMatrix = function () {
  22096. return this._matrix;
  22097. };
  22098. Bone.prototype.getBaseMatrix = function () {
  22099. return this._baseMatrix;
  22100. };
  22101. Bone.prototype.getWorldMatrix = function () {
  22102. return this._worldTransform;
  22103. };
  22104. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22105. return this._invertedAbsoluteTransform;
  22106. };
  22107. Bone.prototype.getAbsoluteMatrix = function () {
  22108. var matrix = this._matrix.clone();
  22109. var parent = this._parent;
  22110. while (parent) {
  22111. matrix = matrix.multiply(parent.getLocalMatrix());
  22112. parent = parent.getParent();
  22113. }
  22114. return matrix;
  22115. };
  22116. // Methods
  22117. Bone.prototype.updateMatrix = function (matrix) {
  22118. this._matrix = matrix;
  22119. this._skeleton._markAsDirty();
  22120. this._updateDifferenceMatrix();
  22121. };
  22122. Bone.prototype._updateDifferenceMatrix = function () {
  22123. if (this._parent) {
  22124. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22125. }
  22126. else {
  22127. this._absoluteTransform.copyFrom(this._matrix);
  22128. }
  22129. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22130. for (var index = 0; index < this.children.length; index++) {
  22131. this.children[index]._updateDifferenceMatrix();
  22132. }
  22133. };
  22134. Bone.prototype.markAsDirty = function () {
  22135. this._currentRenderId++;
  22136. this._skeleton._markAsDirty();
  22137. };
  22138. return Bone;
  22139. })(BABYLON.Node);
  22140. BABYLON.Bone = Bone;
  22141. })(BABYLON || (BABYLON = {}));
  22142. var BABYLON;
  22143. (function (BABYLON) {
  22144. var Skeleton = (function () {
  22145. function Skeleton(name, id, scene) {
  22146. this.name = name;
  22147. this.id = id;
  22148. this.bones = new Array();
  22149. this._isDirty = true;
  22150. this._identity = BABYLON.Matrix.Identity();
  22151. this._ranges = new Array();
  22152. this.bones = [];
  22153. this._scene = scene;
  22154. scene.skeletons.push(this);
  22155. this.prepare();
  22156. //make sure it will recalculate the matrix next time prepare is called.
  22157. this._isDirty = true;
  22158. }
  22159. // Members
  22160. Skeleton.prototype.getTransformMatrices = function () {
  22161. return this._transformMatrices;
  22162. };
  22163. Skeleton.prototype.getScene = function () {
  22164. return this._scene;
  22165. };
  22166. // Methods
  22167. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22168. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22169. };
  22170. Skeleton.prototype.deleteAnimationRange = function (name) {
  22171. for (var index = 0; index < this._ranges.length; index++) {
  22172. if (this._ranges[index].name === name) {
  22173. this._ranges.splice(index, 1);
  22174. return;
  22175. }
  22176. }
  22177. };
  22178. Skeleton.prototype.getAnimationRange = function (name) {
  22179. for (var index = 0; index < this._ranges.length; index++) {
  22180. if (this._ranges[index].name === name) {
  22181. return this._ranges[index];
  22182. }
  22183. }
  22184. return null;
  22185. };
  22186. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22187. var range = this.getAnimationRange(name);
  22188. if (!range) {
  22189. return null;
  22190. }
  22191. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22192. };
  22193. Skeleton.prototype._markAsDirty = function () {
  22194. this._isDirty = true;
  22195. };
  22196. Skeleton.prototype.prepare = function () {
  22197. if (!this._isDirty) {
  22198. return;
  22199. }
  22200. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22201. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22202. }
  22203. for (var index = 0; index < this.bones.length; index++) {
  22204. var bone = this.bones[index];
  22205. var parentBone = bone.getParent();
  22206. if (parentBone) {
  22207. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22208. }
  22209. else {
  22210. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22211. }
  22212. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22213. }
  22214. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22215. this._isDirty = false;
  22216. this._scene._activeBones += this.bones.length;
  22217. };
  22218. Skeleton.prototype.getAnimatables = function () {
  22219. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22220. this._animatables = [];
  22221. for (var index = 0; index < this.bones.length; index++) {
  22222. this._animatables.push(this.bones[index]);
  22223. }
  22224. }
  22225. return this._animatables;
  22226. };
  22227. Skeleton.prototype.clone = function (name, id) {
  22228. var result = new Skeleton(name, id || name, this._scene);
  22229. for (var index = 0; index < this.bones.length; index++) {
  22230. var source = this.bones[index];
  22231. var parentBone = null;
  22232. if (source.getParent()) {
  22233. var parentIndex = this.bones.indexOf(source.getParent());
  22234. parentBone = result.bones[parentIndex];
  22235. }
  22236. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22237. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22238. }
  22239. return result;
  22240. };
  22241. return Skeleton;
  22242. })();
  22243. BABYLON.Skeleton = Skeleton;
  22244. })(BABYLON || (BABYLON = {}));
  22245. var BABYLON;
  22246. (function (BABYLON) {
  22247. var PostProcess = (function () {
  22248. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22250. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22251. this.name = name;
  22252. this.width = -1;
  22253. this.height = -1;
  22254. this._reusable = false;
  22255. this._textures = new BABYLON.SmartArray(2);
  22256. this._currentRenderTextureInd = 0;
  22257. if (camera != null) {
  22258. this._camera = camera;
  22259. this._scene = camera.getScene();
  22260. camera.attachPostProcess(this);
  22261. this._engine = this._scene.getEngine();
  22262. }
  22263. else {
  22264. this._engine = engine;
  22265. }
  22266. this._renderRatio = ratio;
  22267. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22268. this._reusable = reusable || false;
  22269. this._textureType = textureType;
  22270. samplers = samplers || [];
  22271. samplers.push("textureSampler");
  22272. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22273. }
  22274. PostProcess.prototype.isReusable = function () {
  22275. return this._reusable;
  22276. };
  22277. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22278. camera = camera || this._camera;
  22279. var scene = camera.getScene();
  22280. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22281. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22282. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22283. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22284. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22285. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22286. if (this._textures.length > 0) {
  22287. for (var i = 0; i < this._textures.length; i++) {
  22288. this._engine._releaseTexture(this._textures.data[i]);
  22289. }
  22290. this._textures.reset();
  22291. }
  22292. this.width = desiredWidth;
  22293. this.height = desiredHeight;
  22294. 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 }));
  22295. if (this._reusable) {
  22296. 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 }));
  22297. }
  22298. if (this.onSizeChanged) {
  22299. this.onSizeChanged();
  22300. }
  22301. }
  22302. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22303. if (this.onActivate) {
  22304. this.onActivate(camera);
  22305. }
  22306. // Clear
  22307. if (this.clearColor) {
  22308. this._engine.clear(this.clearColor, true, true);
  22309. }
  22310. else {
  22311. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22312. }
  22313. if (this._reusable) {
  22314. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22315. }
  22316. };
  22317. PostProcess.prototype.apply = function () {
  22318. // Check
  22319. if (!this._effect.isReady())
  22320. return null;
  22321. // States
  22322. this._engine.enableEffect(this._effect);
  22323. this._engine.setState(false);
  22324. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22325. this._engine.setDepthBuffer(false);
  22326. this._engine.setDepthWrite(false);
  22327. // Texture
  22328. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22329. // Parameters
  22330. if (this.onApply) {
  22331. this.onApply(this._effect);
  22332. }
  22333. return this._effect;
  22334. };
  22335. PostProcess.prototype.dispose = function (camera) {
  22336. camera = camera || this._camera;
  22337. if (this._textures.length > 0) {
  22338. for (var i = 0; i < this._textures.length; i++) {
  22339. this._engine._releaseTexture(this._textures.data[i]);
  22340. }
  22341. this._textures.reset();
  22342. }
  22343. if (!camera) {
  22344. return;
  22345. }
  22346. camera.detachPostProcess(this);
  22347. var index = camera._postProcesses.indexOf(this);
  22348. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22349. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22350. }
  22351. };
  22352. return PostProcess;
  22353. })();
  22354. BABYLON.PostProcess = PostProcess;
  22355. })(BABYLON || (BABYLON = {}));
  22356. var BABYLON;
  22357. (function (BABYLON) {
  22358. var PostProcessManager = (function () {
  22359. function PostProcessManager(scene) {
  22360. this._vertexDeclaration = [2];
  22361. this._vertexStrideSize = 2 * 4;
  22362. this._scene = scene;
  22363. }
  22364. PostProcessManager.prototype._prepareBuffers = function () {
  22365. if (this._vertexBuffer) {
  22366. return;
  22367. }
  22368. // VBO
  22369. var vertices = [];
  22370. vertices.push(1, 1);
  22371. vertices.push(-1, 1);
  22372. vertices.push(-1, -1);
  22373. vertices.push(1, -1);
  22374. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22375. // Indices
  22376. var indices = [];
  22377. indices.push(0);
  22378. indices.push(1);
  22379. indices.push(2);
  22380. indices.push(0);
  22381. indices.push(2);
  22382. indices.push(3);
  22383. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22384. };
  22385. // Methods
  22386. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22387. var postProcesses = this._scene.activeCamera._postProcesses;
  22388. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22389. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22390. return false;
  22391. }
  22392. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22393. return true;
  22394. };
  22395. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22396. var engine = this._scene.getEngine();
  22397. for (var index = 0; index < postProcesses.length; index++) {
  22398. if (index < postProcesses.length - 1) {
  22399. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22400. }
  22401. else {
  22402. if (targetTexture) {
  22403. engine.bindFramebuffer(targetTexture);
  22404. }
  22405. else {
  22406. engine.restoreDefaultFramebuffer();
  22407. }
  22408. }
  22409. var pp = postProcesses[index];
  22410. var effect = pp.apply();
  22411. if (effect) {
  22412. if (pp.onBeforeRender) {
  22413. pp.onBeforeRender(effect);
  22414. }
  22415. // VBOs
  22416. this._prepareBuffers();
  22417. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22418. // Draw order
  22419. engine.draw(true, 0, 6);
  22420. if (pp.onAfterRender) {
  22421. pp.onAfterRender(effect);
  22422. }
  22423. }
  22424. }
  22425. // Restore depth buffer
  22426. engine.setDepthBuffer(true);
  22427. engine.setDepthWrite(true);
  22428. };
  22429. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22430. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22431. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22432. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22433. return;
  22434. }
  22435. var engine = this._scene.getEngine();
  22436. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22437. if (index < postProcessesTakenIndices.length - 1) {
  22438. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22439. }
  22440. else {
  22441. if (targetTexture) {
  22442. engine.bindFramebuffer(targetTexture, faceIndex);
  22443. }
  22444. else {
  22445. engine.restoreDefaultFramebuffer();
  22446. }
  22447. }
  22448. if (doNotPresent) {
  22449. break;
  22450. }
  22451. var pp = postProcesses[postProcessesTakenIndices[index]];
  22452. var effect = pp.apply();
  22453. if (effect) {
  22454. if (pp.onBeforeRender) {
  22455. pp.onBeforeRender(effect);
  22456. }
  22457. // VBOs
  22458. this._prepareBuffers();
  22459. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22460. // Draw order
  22461. engine.draw(true, 0, 6);
  22462. if (pp.onAfterRender) {
  22463. pp.onAfterRender(effect);
  22464. }
  22465. }
  22466. }
  22467. // Restore depth buffer
  22468. engine.setDepthBuffer(true);
  22469. engine.setDepthWrite(true);
  22470. };
  22471. PostProcessManager.prototype.dispose = function () {
  22472. if (this._vertexBuffer) {
  22473. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22474. this._vertexBuffer = null;
  22475. }
  22476. if (this._indexBuffer) {
  22477. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22478. this._indexBuffer = null;
  22479. }
  22480. };
  22481. return PostProcessManager;
  22482. })();
  22483. BABYLON.PostProcessManager = PostProcessManager;
  22484. })(BABYLON || (BABYLON = {}));
  22485. var BABYLON;
  22486. (function (BABYLON) {
  22487. var PassPostProcess = (function (_super) {
  22488. __extends(PassPostProcess, _super);
  22489. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22490. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22491. }
  22492. return PassPostProcess;
  22493. })(BABYLON.PostProcess);
  22494. BABYLON.PassPostProcess = PassPostProcess;
  22495. })(BABYLON || (BABYLON = {}));
  22496. var BABYLON;
  22497. (function (BABYLON) {
  22498. var PhysicsEngine = (function () {
  22499. function PhysicsEngine(plugin) {
  22500. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22501. }
  22502. PhysicsEngine.prototype._initialize = function (gravity) {
  22503. this._currentPlugin.initialize();
  22504. this._setGravity(gravity);
  22505. };
  22506. PhysicsEngine.prototype._runOneStep = function (delta) {
  22507. if (delta > 0.1) {
  22508. delta = 0.1;
  22509. }
  22510. else if (delta <= 0) {
  22511. delta = 1.0 / 60.0;
  22512. }
  22513. this._currentPlugin.runOneStep(delta);
  22514. };
  22515. PhysicsEngine.prototype._setGravity = function (gravity) {
  22516. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22517. this._currentPlugin.setGravity(this.gravity);
  22518. };
  22519. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22520. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22521. };
  22522. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22523. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22524. };
  22525. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22526. this._currentPlugin.unregisterMesh(mesh);
  22527. };
  22528. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22529. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22530. };
  22531. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22532. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22533. };
  22534. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22535. this._currentPlugin.updateBodyPosition(mesh);
  22536. };
  22537. PhysicsEngine.prototype.dispose = function () {
  22538. this._currentPlugin.dispose();
  22539. };
  22540. PhysicsEngine.prototype.isSupported = function () {
  22541. return this._currentPlugin.isSupported();
  22542. };
  22543. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22544. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22545. };
  22546. // Statics
  22547. PhysicsEngine.NoImpostor = 0;
  22548. PhysicsEngine.SphereImpostor = 1;
  22549. PhysicsEngine.BoxImpostor = 2;
  22550. PhysicsEngine.PlaneImpostor = 3;
  22551. PhysicsEngine.MeshImpostor = 4;
  22552. PhysicsEngine.CapsuleImpostor = 5;
  22553. PhysicsEngine.ConeImpostor = 6;
  22554. PhysicsEngine.CylinderImpostor = 7;
  22555. PhysicsEngine.ConvexHullImpostor = 8;
  22556. PhysicsEngine.Epsilon = 0.001;
  22557. return PhysicsEngine;
  22558. })();
  22559. BABYLON.PhysicsEngine = PhysicsEngine;
  22560. })(BABYLON || (BABYLON = {}));
  22561. var BABYLON;
  22562. (function (BABYLON) {
  22563. var VertexData = (function () {
  22564. function VertexData() {
  22565. }
  22566. VertexData.prototype.set = function (data, kind) {
  22567. switch (kind) {
  22568. case BABYLON.VertexBuffer.PositionKind:
  22569. this.positions = data;
  22570. break;
  22571. case BABYLON.VertexBuffer.NormalKind:
  22572. this.normals = data;
  22573. break;
  22574. case BABYLON.VertexBuffer.UVKind:
  22575. this.uvs = data;
  22576. break;
  22577. case BABYLON.VertexBuffer.UV2Kind:
  22578. this.uvs2 = data;
  22579. break;
  22580. case BABYLON.VertexBuffer.UV3Kind:
  22581. this.uvs3 = data;
  22582. break;
  22583. case BABYLON.VertexBuffer.UV4Kind:
  22584. this.uvs4 = data;
  22585. break;
  22586. case BABYLON.VertexBuffer.UV5Kind:
  22587. this.uvs5 = data;
  22588. break;
  22589. case BABYLON.VertexBuffer.UV6Kind:
  22590. this.uvs6 = data;
  22591. break;
  22592. case BABYLON.VertexBuffer.ColorKind:
  22593. this.colors = data;
  22594. break;
  22595. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22596. this.matricesIndices = data;
  22597. break;
  22598. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22599. this.matricesWeights = data;
  22600. break;
  22601. }
  22602. };
  22603. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22604. this._applyTo(mesh, updatable);
  22605. };
  22606. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22607. this._applyTo(geometry, updatable);
  22608. };
  22609. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22610. this._update(mesh);
  22611. };
  22612. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22613. this._update(geometry);
  22614. };
  22615. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22616. if (this.positions) {
  22617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22618. }
  22619. if (this.normals) {
  22620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22621. }
  22622. if (this.uvs) {
  22623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22624. }
  22625. if (this.uvs2) {
  22626. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22627. }
  22628. if (this.uvs3) {
  22629. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22630. }
  22631. if (this.uvs4) {
  22632. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22633. }
  22634. if (this.uvs5) {
  22635. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22636. }
  22637. if (this.uvs6) {
  22638. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22639. }
  22640. if (this.colors) {
  22641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22642. }
  22643. if (this.matricesIndices) {
  22644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22645. }
  22646. if (this.matricesWeights) {
  22647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22648. }
  22649. if (this.indices) {
  22650. meshOrGeometry.setIndices(this.indices);
  22651. }
  22652. };
  22653. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22654. if (this.positions) {
  22655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22656. }
  22657. if (this.normals) {
  22658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22659. }
  22660. if (this.uvs) {
  22661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22662. }
  22663. if (this.uvs2) {
  22664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22665. }
  22666. if (this.uvs3) {
  22667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22668. }
  22669. if (this.uvs4) {
  22670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22671. }
  22672. if (this.uvs5) {
  22673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22674. }
  22675. if (this.uvs6) {
  22676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22677. }
  22678. if (this.colors) {
  22679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22680. }
  22681. if (this.matricesIndices) {
  22682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22683. }
  22684. if (this.matricesWeights) {
  22685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22686. }
  22687. if (this.indices) {
  22688. meshOrGeometry.setIndices(this.indices);
  22689. }
  22690. };
  22691. VertexData.prototype.transform = function (matrix) {
  22692. var transformed = BABYLON.Vector3.Zero();
  22693. var index;
  22694. if (this.positions) {
  22695. var position = BABYLON.Vector3.Zero();
  22696. for (index = 0; index < this.positions.length; index += 3) {
  22697. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22698. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22699. this.positions[index] = transformed.x;
  22700. this.positions[index + 1] = transformed.y;
  22701. this.positions[index + 2] = transformed.z;
  22702. }
  22703. }
  22704. if (this.normals) {
  22705. var normal = BABYLON.Vector3.Zero();
  22706. for (index = 0; index < this.normals.length; index += 3) {
  22707. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22708. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22709. this.normals[index] = transformed.x;
  22710. this.normals[index + 1] = transformed.y;
  22711. this.normals[index + 2] = transformed.z;
  22712. }
  22713. }
  22714. };
  22715. VertexData.prototype.merge = function (other) {
  22716. var index;
  22717. if (other.indices) {
  22718. if (!this.indices) {
  22719. this.indices = [];
  22720. }
  22721. var offset = this.positions ? this.positions.length / 3 : 0;
  22722. for (index = 0; index < other.indices.length; index++) {
  22723. this.indices.push(other.indices[index] + offset);
  22724. }
  22725. }
  22726. if (other.positions) {
  22727. if (!this.positions) {
  22728. this.positions = [];
  22729. }
  22730. for (index = 0; index < other.positions.length; index++) {
  22731. this.positions.push(other.positions[index]);
  22732. }
  22733. }
  22734. if (other.normals) {
  22735. if (!this.normals) {
  22736. this.normals = [];
  22737. }
  22738. for (index = 0; index < other.normals.length; index++) {
  22739. this.normals.push(other.normals[index]);
  22740. }
  22741. }
  22742. if (other.uvs) {
  22743. if (!this.uvs) {
  22744. this.uvs = [];
  22745. }
  22746. for (index = 0; index < other.uvs.length; index++) {
  22747. this.uvs.push(other.uvs[index]);
  22748. }
  22749. }
  22750. if (other.uvs2) {
  22751. if (!this.uvs2) {
  22752. this.uvs2 = [];
  22753. }
  22754. for (index = 0; index < other.uvs2.length; index++) {
  22755. this.uvs2.push(other.uvs2[index]);
  22756. }
  22757. }
  22758. if (other.uvs3) {
  22759. if (!this.uvs3) {
  22760. this.uvs3 = [];
  22761. }
  22762. for (index = 0; index < other.uvs3.length; index++) {
  22763. this.uvs3.push(other.uvs3[index]);
  22764. }
  22765. }
  22766. if (other.uvs4) {
  22767. if (!this.uvs4) {
  22768. this.uvs4 = [];
  22769. }
  22770. for (index = 0; index < other.uvs4.length; index++) {
  22771. this.uvs4.push(other.uvs4[index]);
  22772. }
  22773. }
  22774. if (other.uvs5) {
  22775. if (!this.uvs5) {
  22776. this.uvs5 = [];
  22777. }
  22778. for (index = 0; index < other.uvs5.length; index++) {
  22779. this.uvs5.push(other.uvs5[index]);
  22780. }
  22781. }
  22782. if (other.uvs6) {
  22783. if (!this.uvs6) {
  22784. this.uvs6 = [];
  22785. }
  22786. for (index = 0; index < other.uvs6.length; index++) {
  22787. this.uvs6.push(other.uvs6[index]);
  22788. }
  22789. }
  22790. if (other.matricesIndices) {
  22791. if (!this.matricesIndices) {
  22792. this.matricesIndices = [];
  22793. }
  22794. for (index = 0; index < other.matricesIndices.length; index++) {
  22795. this.matricesIndices.push(other.matricesIndices[index]);
  22796. }
  22797. }
  22798. if (other.matricesWeights) {
  22799. if (!this.matricesWeights) {
  22800. this.matricesWeights = [];
  22801. }
  22802. for (index = 0; index < other.matricesWeights.length; index++) {
  22803. this.matricesWeights.push(other.matricesWeights[index]);
  22804. }
  22805. }
  22806. if (other.colors) {
  22807. if (!this.colors) {
  22808. this.colors = [];
  22809. }
  22810. for (index = 0; index < other.colors.length; index++) {
  22811. this.colors.push(other.colors[index]);
  22812. }
  22813. }
  22814. };
  22815. // Statics
  22816. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22817. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22818. };
  22819. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22820. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22821. };
  22822. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22823. var result = new VertexData();
  22824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22825. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22826. }
  22827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22828. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22829. }
  22830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22831. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22832. }
  22833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22834. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22835. }
  22836. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22837. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22838. }
  22839. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22840. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22841. }
  22842. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22843. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22844. }
  22845. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22846. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22847. }
  22848. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22849. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22850. }
  22851. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22852. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22853. }
  22854. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22855. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22856. }
  22857. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22858. return result;
  22859. };
  22860. VertexData.CreateRibbon = function (options) {
  22861. var pathArray = options.pathArray;
  22862. var closeArray = options.closeArray || false;
  22863. var closePath = options.closePath || false;
  22864. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22865. var offset = options.offset || defaultOffset;
  22866. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22867. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22868. var positions = [];
  22869. var indices = [];
  22870. var normals = [];
  22871. var uvs = [];
  22872. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22873. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22874. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22875. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22876. var minlg; // minimal length among all paths from pathArray
  22877. var lg = []; // array of path lengths : nb of vertex per path
  22878. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22879. var p; // path iterator
  22880. var i; // point iterator
  22881. var j; // point iterator
  22882. // if single path in pathArray
  22883. if (pathArray.length < 2) {
  22884. var ar1 = [];
  22885. var ar2 = [];
  22886. for (i = 0; i < pathArray[0].length - offset; i++) {
  22887. ar1.push(pathArray[0][i]);
  22888. ar2.push(pathArray[0][i + offset]);
  22889. }
  22890. pathArray = [ar1, ar2];
  22891. }
  22892. // positions and horizontal distances (u)
  22893. var idc = 0;
  22894. var closePathCorr = (closePath) ? 1 : 0;
  22895. var path;
  22896. var l;
  22897. minlg = pathArray[0].length;
  22898. var vectlg;
  22899. var dist;
  22900. for (p = 0; p < pathArray.length; p++) {
  22901. uTotalDistance[p] = 0;
  22902. us[p] = [0];
  22903. path = pathArray[p];
  22904. l = path.length;
  22905. minlg = (minlg < l) ? minlg : l;
  22906. j = 0;
  22907. while (j < l) {
  22908. positions.push(path[j].x, path[j].y, path[j].z);
  22909. if (j > 0) {
  22910. vectlg = path[j].subtract(path[j - 1]).length();
  22911. dist = vectlg + uTotalDistance[p];
  22912. us[p].push(dist);
  22913. uTotalDistance[p] = dist;
  22914. }
  22915. j++;
  22916. }
  22917. if (closePath) {
  22918. j--;
  22919. positions.push(path[0].x, path[0].y, path[0].z);
  22920. vectlg = path[j].subtract(path[0]).length();
  22921. dist = vectlg + uTotalDistance[p];
  22922. us[p].push(dist);
  22923. uTotalDistance[p] = dist;
  22924. }
  22925. lg[p] = l + closePathCorr;
  22926. idx[p] = idc;
  22927. idc += (l + closePathCorr);
  22928. }
  22929. // vertical distances (v)
  22930. var path1;
  22931. var path2;
  22932. var vertex1;
  22933. var vertex2;
  22934. for (i = 0; i < minlg + closePathCorr; i++) {
  22935. vTotalDistance[i] = 0;
  22936. vs[i] = [0];
  22937. for (p = 0; p < pathArray.length - 1; p++) {
  22938. path1 = pathArray[p];
  22939. path2 = pathArray[p + 1];
  22940. if (i === minlg) {
  22941. vertex1 = path1[0];
  22942. vertex2 = path2[0];
  22943. }
  22944. else {
  22945. vertex1 = path1[i];
  22946. vertex2 = path2[i];
  22947. }
  22948. vectlg = vertex2.subtract(vertex1).length();
  22949. dist = vectlg + vTotalDistance[i];
  22950. vs[i].push(dist);
  22951. vTotalDistance[i] = dist;
  22952. }
  22953. if (closeArray) {
  22954. path1 = pathArray[p];
  22955. path2 = pathArray[0];
  22956. if (i === minlg) {
  22957. vertex2 = path2[0];
  22958. }
  22959. vectlg = vertex2.subtract(vertex1).length();
  22960. dist = vectlg + vTotalDistance[i];
  22961. vTotalDistance[i] = dist;
  22962. }
  22963. }
  22964. // uvs
  22965. var u;
  22966. var v;
  22967. for (p = 0; p < pathArray.length; p++) {
  22968. for (i = 0; i < minlg + closePathCorr; i++) {
  22969. u = us[p][i] / uTotalDistance[p];
  22970. v = vs[i][p] / vTotalDistance[i];
  22971. uvs.push(u, v);
  22972. }
  22973. }
  22974. // indices
  22975. p = 0; // path index
  22976. var pi = 0; // positions array index
  22977. var l1 = lg[p] - 1; // path1 length
  22978. var l2 = lg[p + 1] - 1; // path2 length
  22979. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22980. var shft = idx[1] - idx[0]; // shift
  22981. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  22982. while (pi <= min && p < path1nb) {
  22983. // 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
  22984. indices.push(pi, pi + shft, pi + 1);
  22985. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22986. pi += 1;
  22987. if (pi === min) {
  22988. p++;
  22989. if (p === lg.length - 1) {
  22990. shft = idx[0] - idx[p];
  22991. l1 = lg[p] - 1;
  22992. l2 = lg[0] - 1;
  22993. }
  22994. else {
  22995. shft = idx[p + 1] - idx[p];
  22996. l1 = lg[p] - 1;
  22997. l2 = lg[p + 1] - 1;
  22998. }
  22999. pi = idx[p];
  23000. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23001. }
  23002. }
  23003. // normals
  23004. VertexData.ComputeNormals(positions, indices, normals);
  23005. if (closePath) {
  23006. var indexFirst = 0;
  23007. var indexLast = 0;
  23008. for (p = 0; p < pathArray.length; p++) {
  23009. indexFirst = idx[p] * 3;
  23010. if (p + 1 < pathArray.length) {
  23011. indexLast = (idx[p + 1] - 1) * 3;
  23012. }
  23013. else {
  23014. indexLast = normals.length - 3;
  23015. }
  23016. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23017. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23018. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23019. normals[indexLast] = normals[indexFirst];
  23020. normals[indexLast + 1] = normals[indexFirst + 1];
  23021. normals[indexLast + 2] = normals[indexFirst + 2];
  23022. }
  23023. }
  23024. // sides
  23025. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23026. // Result
  23027. var vertexData = new VertexData();
  23028. vertexData.indices = indices;
  23029. vertexData.positions = positions;
  23030. vertexData.normals = normals;
  23031. vertexData.uvs = uvs;
  23032. if (closePath) {
  23033. vertexData._idx = idx;
  23034. }
  23035. return vertexData;
  23036. };
  23037. VertexData.CreateBox = function (options) {
  23038. var normalsSource = [
  23039. new BABYLON.Vector3(0, 0, 1),
  23040. new BABYLON.Vector3(0, 0, -1),
  23041. new BABYLON.Vector3(1, 0, 0),
  23042. new BABYLON.Vector3(-1, 0, 0),
  23043. new BABYLON.Vector3(0, 1, 0),
  23044. new BABYLON.Vector3(0, -1, 0)
  23045. ];
  23046. var indices = [];
  23047. var positions = [];
  23048. var normals = [];
  23049. var uvs = [];
  23050. var width = options.width || options.size || 1;
  23051. var height = options.height || options.size || 1;
  23052. var depth = options.depth || options.size || 1;
  23053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23054. var faceUV = options.faceUV || new Array(6);
  23055. var faceColors = options.faceColors;
  23056. var colors = [];
  23057. // default face colors and UV if undefined
  23058. for (var f = 0; f < 6; f++) {
  23059. if (faceUV[f] === undefined) {
  23060. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23061. }
  23062. if (faceColors && faceColors[f] === undefined) {
  23063. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23064. }
  23065. }
  23066. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23067. // Create each face in turn.
  23068. for (var index = 0; index < normalsSource.length; index++) {
  23069. var normal = normalsSource[index];
  23070. // Get two vectors perpendicular to the face normal and to each other.
  23071. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23072. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23073. // Six indices (two triangles) per face.
  23074. var verticesLength = positions.length / 3;
  23075. indices.push(verticesLength);
  23076. indices.push(verticesLength + 1);
  23077. indices.push(verticesLength + 2);
  23078. indices.push(verticesLength);
  23079. indices.push(verticesLength + 2);
  23080. indices.push(verticesLength + 3);
  23081. // Four vertices per face.
  23082. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23083. positions.push(vertex.x, vertex.y, vertex.z);
  23084. normals.push(normal.x, normal.y, normal.z);
  23085. uvs.push(faceUV[index].z, faceUV[index].w);
  23086. if (faceColors) {
  23087. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23088. }
  23089. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23090. positions.push(vertex.x, vertex.y, vertex.z);
  23091. normals.push(normal.x, normal.y, normal.z);
  23092. uvs.push(faceUV[index].x, faceUV[index].w);
  23093. if (faceColors) {
  23094. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23095. }
  23096. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23097. positions.push(vertex.x, vertex.y, vertex.z);
  23098. normals.push(normal.x, normal.y, normal.z);
  23099. uvs.push(faceUV[index].x, faceUV[index].y);
  23100. if (faceColors) {
  23101. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23102. }
  23103. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23104. positions.push(vertex.x, vertex.y, vertex.z);
  23105. normals.push(normal.x, normal.y, normal.z);
  23106. uvs.push(faceUV[index].z, faceUV[index].y);
  23107. if (faceColors) {
  23108. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23109. }
  23110. }
  23111. // sides
  23112. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23113. // Result
  23114. var vertexData = new VertexData();
  23115. vertexData.indices = indices;
  23116. vertexData.positions = positions;
  23117. vertexData.normals = normals;
  23118. vertexData.uvs = uvs;
  23119. if (faceColors) {
  23120. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23121. vertexData.colors = totalColors;
  23122. }
  23123. return vertexData;
  23124. };
  23125. VertexData.CreateSphere = function (options) {
  23126. var segments = options.segments || 32;
  23127. var diameterX = options.diameterX || options.diameter || 1;
  23128. var diameterY = options.diameterY || options.diameter || 1;
  23129. var diameterZ = options.diameterZ || options.diameter || 1;
  23130. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  23131. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23132. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23133. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23134. var totalZRotationSteps = 2 + segments;
  23135. var totalYRotationSteps = 2 * totalZRotationSteps;
  23136. var indices = [];
  23137. var positions = [];
  23138. var normals = [];
  23139. var uvs = [];
  23140. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23141. var normalizedZ = zRotationStep / totalZRotationSteps;
  23142. var angleZ = normalizedZ * Math.PI * slice;
  23143. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23144. var normalizedY = yRotationStep / totalYRotationSteps;
  23145. var angleY = normalizedY * Math.PI * 2 * arc;
  23146. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23147. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23148. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23149. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23150. var vertex = complete.multiply(radius);
  23151. var normal = BABYLON.Vector3.Normalize(vertex);
  23152. positions.push(vertex.x, vertex.y, vertex.z);
  23153. normals.push(normal.x, normal.y, normal.z);
  23154. uvs.push(normalizedY, normalizedZ);
  23155. }
  23156. if (zRotationStep > 0) {
  23157. var verticesCount = positions.length / 3;
  23158. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23159. indices.push((firstIndex));
  23160. indices.push((firstIndex + 1));
  23161. indices.push(firstIndex + totalYRotationSteps + 1);
  23162. indices.push((firstIndex + totalYRotationSteps + 1));
  23163. indices.push((firstIndex + 1));
  23164. indices.push((firstIndex + totalYRotationSteps + 2));
  23165. }
  23166. }
  23167. }
  23168. // Sides
  23169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23170. // Result
  23171. var vertexData = new VertexData();
  23172. vertexData.indices = indices;
  23173. vertexData.positions = positions;
  23174. vertexData.normals = normals;
  23175. vertexData.uvs = uvs;
  23176. return vertexData;
  23177. };
  23178. // Cylinder and cone
  23179. VertexData.CreateCylinder = function (options) {
  23180. var height = options.height || 2;
  23181. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23182. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23183. var tessellation = options.tessellation || 24;
  23184. var subdivisions = options.subdivisions || 1;
  23185. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  23186. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23187. var faceUV = options.faceUV || new Array(3);
  23188. var faceColors = options.faceColors;
  23189. // default face colors and UV if undefined
  23190. for (var f = 0; f < 3; f++) {
  23191. if (faceColors && faceColors[f] === undefined) {
  23192. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23193. }
  23194. if (faceUV && faceUV[f] === undefined) {
  23195. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23196. }
  23197. }
  23198. var indices = [];
  23199. var positions = [];
  23200. var normals = [];
  23201. var uvs = [];
  23202. var colors = [];
  23203. var angle_step = Math.PI * 2 * arc / tessellation;
  23204. var angle;
  23205. var h;
  23206. var radius;
  23207. var tan = (diameterBottom - diameterTop) / 2 / height;
  23208. var ringVertex = BABYLON.Vector3.Zero();
  23209. var ringNormal = BABYLON.Vector3.Zero();
  23210. // positions, normals, uvs
  23211. var i;
  23212. var j;
  23213. for (i = 0; i <= subdivisions; i++) {
  23214. h = i / subdivisions;
  23215. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23216. for (j = 0; j <= tessellation; j++) {
  23217. angle = j * angle_step;
  23218. ringVertex.x = Math.cos(-angle) * radius;
  23219. ringVertex.y = -height / 2 + h * height;
  23220. ringVertex.z = Math.sin(-angle) * radius;
  23221. if (diameterTop === 0 && i === subdivisions) {
  23222. // if no top cap, reuse former normals
  23223. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23224. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23225. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23226. }
  23227. else {
  23228. ringNormal.x = ringVertex.x;
  23229. ringNormal.z = ringVertex.z;
  23230. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23231. ringNormal.normalize();
  23232. }
  23233. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23234. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23235. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23236. if (faceColors) {
  23237. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23238. }
  23239. }
  23240. }
  23241. // indices
  23242. for (i = 0; i < subdivisions; i++) {
  23243. for (j = 0; j < tessellation; j++) {
  23244. var i0 = i * (tessellation + 1) + j;
  23245. var i1 = (i + 1) * (tessellation + 1) + j;
  23246. var i2 = i * (tessellation + 1) + (j + 1);
  23247. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23248. indices.push(i0, i1, i2);
  23249. indices.push(i3, i2, i1);
  23250. }
  23251. }
  23252. // Caps
  23253. var createCylinderCap = function (isTop) {
  23254. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23255. if (radius === 0) {
  23256. return;
  23257. }
  23258. // Cap positions, normals & uvs
  23259. var angle;
  23260. var circleVector;
  23261. var i;
  23262. var u = (isTop) ? faceUV[2] : faceUV[0];
  23263. var c;
  23264. if (faceColors) {
  23265. c = (isTop) ? faceColors[2] : faceColors[0];
  23266. }
  23267. // cap center
  23268. var vbase = positions.length / 3;
  23269. var offset = isTop ? height / 2 : -height / 2;
  23270. var center = new BABYLON.Vector3(0, offset, 0);
  23271. positions.push(center.x, center.y, center.z);
  23272. normals.push(0, isTop ? 1 : -1, 0);
  23273. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23274. if (faceColors) {
  23275. colors.push(c.r, c.g, c.b, c.a);
  23276. }
  23277. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23278. for (i = 0; i <= tessellation; i++) {
  23279. angle = Math.PI * 2 * i * arc / tessellation;
  23280. var cos = Math.cos(-angle);
  23281. var sin = Math.sin(-angle);
  23282. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23283. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23284. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23285. normals.push(0, isTop ? 1 : -1, 0);
  23286. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23287. if (faceColors) {
  23288. colors.push(c.r, c.g, c.b, c.a);
  23289. }
  23290. }
  23291. // Cap indices
  23292. for (i = 0; i < tessellation; i++) {
  23293. if (!isTop) {
  23294. indices.push(vbase);
  23295. indices.push(vbase + (i + 1));
  23296. indices.push(vbase + (i + 2));
  23297. }
  23298. else {
  23299. indices.push(vbase);
  23300. indices.push(vbase + (i + 2));
  23301. indices.push(vbase + (i + 1));
  23302. }
  23303. }
  23304. };
  23305. // add caps to geometry
  23306. createCylinderCap(false);
  23307. createCylinderCap(true);
  23308. // Sides
  23309. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23310. var vertexData = new VertexData();
  23311. vertexData.indices = indices;
  23312. vertexData.positions = positions;
  23313. vertexData.normals = normals;
  23314. vertexData.uvs = uvs;
  23315. if (faceColors) {
  23316. vertexData.colors = colors;
  23317. }
  23318. return vertexData;
  23319. };
  23320. VertexData.CreateTorus = function (options) {
  23321. var indices = [];
  23322. var positions = [];
  23323. var normals = [];
  23324. var uvs = [];
  23325. var diameter = options.diameter || 1;
  23326. var thickness = options.thickness || 0.5;
  23327. var tessellation = options.tessellation || 16;
  23328. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23329. var stride = tessellation + 1;
  23330. for (var i = 0; i <= tessellation; i++) {
  23331. var u = i / tessellation;
  23332. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23333. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23334. for (var j = 0; j <= tessellation; j++) {
  23335. var v = 1 - j / tessellation;
  23336. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23337. var dx = Math.cos(innerAngle);
  23338. var dy = Math.sin(innerAngle);
  23339. // Create a vertex.
  23340. var normal = new BABYLON.Vector3(dx, dy, 0);
  23341. var position = normal.scale(thickness / 2);
  23342. var textureCoordinate = new BABYLON.Vector2(u, v);
  23343. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23344. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23345. positions.push(position.x, position.y, position.z);
  23346. normals.push(normal.x, normal.y, normal.z);
  23347. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23348. // And create indices for two triangles.
  23349. var nextI = (i + 1) % stride;
  23350. var nextJ = (j + 1) % stride;
  23351. indices.push(i * stride + j);
  23352. indices.push(i * stride + nextJ);
  23353. indices.push(nextI * stride + j);
  23354. indices.push(i * stride + nextJ);
  23355. indices.push(nextI * stride + nextJ);
  23356. indices.push(nextI * stride + j);
  23357. }
  23358. }
  23359. // Sides
  23360. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23361. // Result
  23362. var vertexData = new VertexData();
  23363. vertexData.indices = indices;
  23364. vertexData.positions = positions;
  23365. vertexData.normals = normals;
  23366. vertexData.uvs = uvs;
  23367. return vertexData;
  23368. };
  23369. VertexData.CreateLines = function (options) {
  23370. var indices = [];
  23371. var positions = [];
  23372. var points = options.points;
  23373. for (var index = 0; index < points.length; index++) {
  23374. positions.push(points[index].x, points[index].y, points[index].z);
  23375. if (index > 0) {
  23376. indices.push(index - 1);
  23377. indices.push(index);
  23378. }
  23379. }
  23380. // Result
  23381. var vertexData = new VertexData();
  23382. vertexData.indices = indices;
  23383. vertexData.positions = positions;
  23384. return vertexData;
  23385. };
  23386. VertexData.CreateDashedLines = function (options) {
  23387. var dashSize = options.dashSize || 3;
  23388. var gapSize = options.gapSize || 1;
  23389. var dashNb = options.dashNb || 200;
  23390. var points = options.points;
  23391. var positions = new Array();
  23392. var indices = new Array();
  23393. var curvect = BABYLON.Vector3.Zero();
  23394. var lg = 0;
  23395. var nb = 0;
  23396. var shft = 0;
  23397. var dashshft = 0;
  23398. var curshft = 0;
  23399. var idx = 0;
  23400. var i = 0;
  23401. for (i = 0; i < points.length - 1; i++) {
  23402. points[i + 1].subtractToRef(points[i], curvect);
  23403. lg += curvect.length();
  23404. }
  23405. shft = lg / dashNb;
  23406. dashshft = dashSize * shft / (dashSize + gapSize);
  23407. for (i = 0; i < points.length - 1; i++) {
  23408. points[i + 1].subtractToRef(points[i], curvect);
  23409. nb = Math.floor(curvect.length() / shft);
  23410. curvect.normalize();
  23411. for (var j = 0; j < nb; j++) {
  23412. curshft = shft * j;
  23413. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23414. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23415. indices.push(idx, idx + 1);
  23416. idx += 2;
  23417. }
  23418. }
  23419. // Result
  23420. var vertexData = new VertexData();
  23421. vertexData.positions = positions;
  23422. vertexData.indices = indices;
  23423. return vertexData;
  23424. };
  23425. VertexData.CreateGround = function (options) {
  23426. var indices = [];
  23427. var positions = [];
  23428. var normals = [];
  23429. var uvs = [];
  23430. var row, col;
  23431. var width = options.width || 1;
  23432. var height = options.height || 1;
  23433. var subdivisions = options.subdivisions || 1;
  23434. for (row = 0; row <= subdivisions; row++) {
  23435. for (col = 0; col <= subdivisions; col++) {
  23436. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23437. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23438. positions.push(position.x, position.y, position.z);
  23439. normals.push(normal.x, normal.y, normal.z);
  23440. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23441. }
  23442. }
  23443. for (row = 0; row < subdivisions; row++) {
  23444. for (col = 0; col < subdivisions; col++) {
  23445. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23446. indices.push(col + 1 + row * (subdivisions + 1));
  23447. indices.push(col + row * (subdivisions + 1));
  23448. indices.push(col + (row + 1) * (subdivisions + 1));
  23449. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23450. indices.push(col + row * (subdivisions + 1));
  23451. }
  23452. }
  23453. // Result
  23454. var vertexData = new VertexData();
  23455. vertexData.indices = indices;
  23456. vertexData.positions = positions;
  23457. vertexData.normals = normals;
  23458. vertexData.uvs = uvs;
  23459. return vertexData;
  23460. };
  23461. VertexData.CreateTiledGround = function (options) {
  23462. var xmin = options.xmin;
  23463. var zmin = options.zmin;
  23464. var xmax = options.xmax;
  23465. var zmax = options.zmax;
  23466. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23467. var precision = options.precision || { w: 1, h: 1 };
  23468. var indices = [];
  23469. var positions = [];
  23470. var normals = [];
  23471. var uvs = [];
  23472. var row, col, tileRow, tileCol;
  23473. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23474. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23475. precision.w = (precision.w < 1) ? 1 : precision.w;
  23476. precision.h = (precision.h < 1) ? 1 : precision.h;
  23477. var tileSize = {
  23478. 'w': (xmax - xmin) / subdivisions.w,
  23479. 'h': (zmax - zmin) / subdivisions.h
  23480. };
  23481. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23482. // Indices
  23483. var base = positions.length / 3;
  23484. var rowLength = precision.w + 1;
  23485. for (row = 0; row < precision.h; row++) {
  23486. for (col = 0; col < precision.w; col++) {
  23487. var square = [
  23488. base + col + row * rowLength,
  23489. base + (col + 1) + row * rowLength,
  23490. base + (col + 1) + (row + 1) * rowLength,
  23491. base + col + (row + 1) * rowLength
  23492. ];
  23493. indices.push(square[1]);
  23494. indices.push(square[2]);
  23495. indices.push(square[3]);
  23496. indices.push(square[0]);
  23497. indices.push(square[1]);
  23498. indices.push(square[3]);
  23499. }
  23500. }
  23501. // Position, normals and uvs
  23502. var position = BABYLON.Vector3.Zero();
  23503. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23504. for (row = 0; row <= precision.h; row++) {
  23505. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23506. for (col = 0; col <= precision.w; col++) {
  23507. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23508. position.y = 0;
  23509. positions.push(position.x, position.y, position.z);
  23510. normals.push(normal.x, normal.y, normal.z);
  23511. uvs.push(col / precision.w, row / precision.h);
  23512. }
  23513. }
  23514. }
  23515. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23516. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23517. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23518. }
  23519. }
  23520. // Result
  23521. var vertexData = new VertexData();
  23522. vertexData.indices = indices;
  23523. vertexData.positions = positions;
  23524. vertexData.normals = normals;
  23525. vertexData.uvs = uvs;
  23526. return vertexData;
  23527. };
  23528. VertexData.CreateGroundFromHeightMap = function (options) {
  23529. var indices = [];
  23530. var positions = [];
  23531. var normals = [];
  23532. var uvs = [];
  23533. var row, col;
  23534. // Vertices
  23535. for (row = 0; row <= options.subdivisions; row++) {
  23536. for (col = 0; col <= options.subdivisions; col++) {
  23537. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  23538. // Compute height
  23539. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23540. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23541. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23542. var r = options.buffer[pos] / 255.0;
  23543. var g = options.buffer[pos + 1] / 255.0;
  23544. var b = options.buffer[pos + 2] / 255.0;
  23545. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23546. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23547. // Add vertex
  23548. positions.push(position.x, position.y, position.z);
  23549. normals.push(0, 0, 0);
  23550. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23551. }
  23552. }
  23553. // Indices
  23554. for (row = 0; row < options.subdivisions; row++) {
  23555. for (col = 0; col < options.subdivisions; col++) {
  23556. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23557. indices.push(col + 1 + row * (options.subdivisions + 1));
  23558. indices.push(col + row * (options.subdivisions + 1));
  23559. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23560. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23561. indices.push(col + row * (options.subdivisions + 1));
  23562. }
  23563. }
  23564. // Normals
  23565. VertexData.ComputeNormals(positions, indices, normals);
  23566. // Result
  23567. var vertexData = new VertexData();
  23568. vertexData.indices = indices;
  23569. vertexData.positions = positions;
  23570. vertexData.normals = normals;
  23571. vertexData.uvs = uvs;
  23572. return vertexData;
  23573. };
  23574. VertexData.CreatePlane = function (options) {
  23575. var indices = [];
  23576. var positions = [];
  23577. var normals = [];
  23578. var uvs = [];
  23579. var width = options.width || options.size || 1;
  23580. var height = options.height || options.size || 1;
  23581. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23582. // Vertices
  23583. var halfWidth = width / 2.0;
  23584. var halfHeight = height / 2.0;
  23585. positions.push(-halfWidth, -halfHeight, 0);
  23586. normals.push(0, 0, -1.0);
  23587. uvs.push(0.0, 0.0);
  23588. positions.push(halfWidth, -halfHeight, 0);
  23589. normals.push(0, 0, -1.0);
  23590. uvs.push(1.0, 0.0);
  23591. positions.push(halfWidth, halfHeight, 0);
  23592. normals.push(0, 0, -1.0);
  23593. uvs.push(1.0, 1.0);
  23594. positions.push(-halfWidth, halfHeight, 0);
  23595. normals.push(0, 0, -1.0);
  23596. uvs.push(0.0, 1.0);
  23597. // Indices
  23598. indices.push(0);
  23599. indices.push(1);
  23600. indices.push(2);
  23601. indices.push(0);
  23602. indices.push(2);
  23603. indices.push(3);
  23604. // Sides
  23605. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23606. // Result
  23607. var vertexData = new VertexData();
  23608. vertexData.indices = indices;
  23609. vertexData.positions = positions;
  23610. vertexData.normals = normals;
  23611. vertexData.uvs = uvs;
  23612. return vertexData;
  23613. };
  23614. VertexData.CreateDisc = function (options) {
  23615. var positions = [];
  23616. var indices = [];
  23617. var normals = [];
  23618. var uvs = [];
  23619. var radius = options.radius || 0.5;
  23620. var tessellation = options.tessellation || 64;
  23621. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  23622. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23623. // positions and uvs
  23624. positions.push(0, 0, 0); // disc center first
  23625. uvs.push(0.5, 0.5);
  23626. var theta = Math.PI * 2 * arc;
  23627. var step = theta / tessellation;
  23628. for (var a = 0; a < theta; a += step) {
  23629. var x = Math.cos(a);
  23630. var y = Math.sin(a);
  23631. var u = (x + 1) / 2;
  23632. var v = (1 - y) / 2;
  23633. positions.push(radius * x, radius * y, 0);
  23634. uvs.push(u, v);
  23635. }
  23636. if (arc === 1) {
  23637. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23638. uvs.push(uvs[2], uvs[3]);
  23639. }
  23640. //indices
  23641. var vertexNb = positions.length / 3;
  23642. for (var i = 1; i < vertexNb - 1; i++) {
  23643. indices.push(i + 1, 0, i);
  23644. }
  23645. // result
  23646. VertexData.ComputeNormals(positions, indices, normals);
  23647. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23648. var vertexData = new VertexData();
  23649. vertexData.indices = indices;
  23650. vertexData.positions = positions;
  23651. vertexData.normals = normals;
  23652. vertexData.uvs = uvs;
  23653. return vertexData;
  23654. };
  23655. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  23656. VertexData.CreatePolyhedron = function (options) {
  23657. // provided polyhedron types :
  23658. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  23659. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  23660. var polyhedra = [];
  23661. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  23662. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  23663. polyhedra[2] = {
  23664. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  23665. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  23666. };
  23667. polyhedra[3] = {
  23668. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  23669. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  23670. };
  23671. polyhedra[4] = {
  23672. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  23673. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  23674. };
  23675. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  23676. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  23677. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  23678. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  23679. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  23680. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  23681. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  23682. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  23683. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  23684. polyhedra[14] = {
  23685. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  23686. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  23687. };
  23688. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  23689. var size = options.size;
  23690. var sizeX = options.sizeX || size || 1;
  23691. var sizeY = options.sizeY || size || 1;
  23692. var sizeZ = options.sizeZ || size || 1;
  23693. var data = options.custom || polyhedra[type];
  23694. var nbfaces = data.face.length;
  23695. var faceUV = options.faceUV || new Array(nbfaces);
  23696. var faceColors = options.faceColors;
  23697. var singleFace = options.singleFace;
  23698. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23699. var positions = [];
  23700. var indices = [];
  23701. var normals = [];
  23702. var uvs = [];
  23703. var colors = [];
  23704. var index = 0;
  23705. var faceIdx = 0; // face cursor in the array "indexes"
  23706. var indexes = [];
  23707. var i = 0;
  23708. var f = 0;
  23709. var u, v, ang, x, y, tmp;
  23710. // default face colors and UV if undefined
  23711. if (!singleFace) {
  23712. for (f = 0; f < nbfaces; f++) {
  23713. if (faceColors && faceColors[f] === undefined) {
  23714. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23715. }
  23716. if (faceUV && faceUV[f] === undefined) {
  23717. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23718. }
  23719. }
  23720. }
  23721. if (singleFace) {
  23722. for (i = 0; i < data.vertex.length; i++) {
  23723. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  23724. uvs.push(0, 0);
  23725. }
  23726. for (f = 0; f < nbfaces; f++) {
  23727. for (i = 0; i < data.face[f].length - 2; i++) {
  23728. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  23729. }
  23730. }
  23731. }
  23732. else {
  23733. for (f = 0; f < nbfaces; f++) {
  23734. var fl = data.face[f].length; // number of vertices of the current face
  23735. ang = 2 * Math.PI / fl;
  23736. x = 0.5 * Math.tan(ang / 2);
  23737. y = 0.5;
  23738. // positions, uvs, colors
  23739. for (i = 0; i < fl; i++) {
  23740. // positions
  23741. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  23742. indexes.push(index);
  23743. index++;
  23744. // uvs
  23745. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  23746. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  23747. uvs.push(u, v);
  23748. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  23749. y = x * Math.sin(ang) + y * Math.cos(ang);
  23750. x = tmp;
  23751. // colors
  23752. if (faceColors) {
  23753. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  23754. }
  23755. }
  23756. // indices from indexes
  23757. for (i = 0; i < fl - 2; i++) {
  23758. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  23759. }
  23760. faceIdx += fl;
  23761. }
  23762. }
  23763. VertexData.ComputeNormals(positions, indices, normals);
  23764. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23765. var vertexData = new VertexData();
  23766. vertexData.positions = positions;
  23767. vertexData.indices = indices;
  23768. vertexData.normals = normals;
  23769. vertexData.uvs = uvs;
  23770. if (faceColors && !singleFace) {
  23771. vertexData.colors = colors;
  23772. }
  23773. return vertexData;
  23774. };
  23775. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23776. VertexData.CreateTorusKnot = function (options) {
  23777. var indices = [];
  23778. var positions = [];
  23779. var normals = [];
  23780. var uvs = [];
  23781. var radius = options.radius || 2;
  23782. var tube = options.tube || 0.5;
  23783. var radialSegments = options.radialSegments || 32;
  23784. var tubularSegments = options.tubularSegments || 32;
  23785. var p = options.p || 2;
  23786. var q = options.q || 3;
  23787. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23788. // Helper
  23789. var getPos = function (angle) {
  23790. var cu = Math.cos(angle);
  23791. var su = Math.sin(angle);
  23792. var quOverP = q / p * angle;
  23793. var cs = Math.cos(quOverP);
  23794. var tx = radius * (2 + cs) * 0.5 * cu;
  23795. var ty = radius * (2 + cs) * su * 0.5;
  23796. var tz = radius * Math.sin(quOverP) * 0.5;
  23797. return new BABYLON.Vector3(tx, ty, tz);
  23798. };
  23799. // Vertices
  23800. var i;
  23801. var j;
  23802. for (i = 0; i <= radialSegments; i++) {
  23803. var modI = i % radialSegments;
  23804. var u = modI / radialSegments * 2 * p * Math.PI;
  23805. var p1 = getPos(u);
  23806. var p2 = getPos(u + 0.01);
  23807. var tang = p2.subtract(p1);
  23808. var n = p2.add(p1);
  23809. var bitan = BABYLON.Vector3.Cross(tang, n);
  23810. n = BABYLON.Vector3.Cross(bitan, tang);
  23811. bitan.normalize();
  23812. n.normalize();
  23813. for (j = 0; j < tubularSegments; j++) {
  23814. var modJ = j % tubularSegments;
  23815. var v = modJ / tubularSegments * 2 * Math.PI;
  23816. var cx = -tube * Math.cos(v);
  23817. var cy = tube * Math.sin(v);
  23818. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23819. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23820. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23821. uvs.push(i / radialSegments);
  23822. uvs.push(j / tubularSegments);
  23823. }
  23824. }
  23825. for (i = 0; i < radialSegments; i++) {
  23826. for (j = 0; j < tubularSegments; j++) {
  23827. var jNext = (j + 1) % tubularSegments;
  23828. var a = i * tubularSegments + j;
  23829. var b = (i + 1) * tubularSegments + j;
  23830. var c = (i + 1) * tubularSegments + jNext;
  23831. var d = i * tubularSegments + jNext;
  23832. indices.push(d);
  23833. indices.push(b);
  23834. indices.push(a);
  23835. indices.push(d);
  23836. indices.push(c);
  23837. indices.push(b);
  23838. }
  23839. }
  23840. // Normals
  23841. VertexData.ComputeNormals(positions, indices, normals);
  23842. // Sides
  23843. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23844. // Result
  23845. var vertexData = new VertexData();
  23846. vertexData.indices = indices;
  23847. vertexData.positions = positions;
  23848. vertexData.normals = normals;
  23849. vertexData.uvs = uvs;
  23850. return vertexData;
  23851. };
  23852. // Tools
  23853. /**
  23854. * @param {any} - positions (number[] or Float32Array)
  23855. * @param {any} - indices (number[] or Uint16Array)
  23856. * @param {any} - normals (number[] or Float32Array)
  23857. */
  23858. VertexData.ComputeNormals = function (positions, indices, normals) {
  23859. var index = 0;
  23860. // temp Vector3
  23861. var p1p2 = BABYLON.Vector3.Zero();
  23862. var p3p2 = BABYLON.Vector3.Zero();
  23863. var faceNormal = BABYLON.Vector3.Zero();
  23864. var vertexNormali1 = BABYLON.Vector3.Zero();
  23865. for (index = 0; index < positions.length; index++) {
  23866. normals[index] = 0.0;
  23867. }
  23868. // indice triplet = 1 face
  23869. var nbFaces = indices.length / 3;
  23870. for (index = 0; index < nbFaces; index++) {
  23871. var i1 = indices[index * 3];
  23872. var i2 = indices[index * 3 + 1];
  23873. var i3 = indices[index * 3 + 2];
  23874. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  23875. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  23876. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  23877. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  23878. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  23879. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  23880. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  23881. faceNormal.normalize();
  23882. normals[i1 * 3] += faceNormal.x;
  23883. normals[i1 * 3 + 1] += faceNormal.y;
  23884. normals[i1 * 3 + 2] += faceNormal.z;
  23885. normals[i2 * 3] += faceNormal.x;
  23886. normals[i2 * 3 + 1] += faceNormal.y;
  23887. normals[i2 * 3 + 2] += faceNormal.z;
  23888. normals[i3 * 3] += faceNormal.x;
  23889. normals[i3 * 3 + 1] += faceNormal.y;
  23890. normals[i3 * 3 + 2] += faceNormal.z;
  23891. }
  23892. // last normalization
  23893. for (index = 0; index < normals.length / 3; index++) {
  23894. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  23895. vertexNormali1.normalize();
  23896. normals[index * 3] = vertexNormali1.x;
  23897. normals[index * 3 + 1] = vertexNormali1.y;
  23898. normals[index * 3 + 2] = vertexNormali1.z;
  23899. }
  23900. };
  23901. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23902. var li = indices.length;
  23903. var ln = normals.length;
  23904. var i;
  23905. var n;
  23906. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23907. switch (sideOrientation) {
  23908. case BABYLON.Mesh.FRONTSIDE:
  23909. // nothing changed
  23910. break;
  23911. case BABYLON.Mesh.BACKSIDE:
  23912. var tmp;
  23913. // indices
  23914. for (i = 0; i < li; i += 3) {
  23915. tmp = indices[i];
  23916. indices[i] = indices[i + 2];
  23917. indices[i + 2] = tmp;
  23918. }
  23919. // normals
  23920. for (n = 0; n < ln; n++) {
  23921. normals[n] = -normals[n];
  23922. }
  23923. break;
  23924. case BABYLON.Mesh.DOUBLESIDE:
  23925. // positions
  23926. var lp = positions.length;
  23927. var l = lp / 3;
  23928. for (var p = 0; p < lp; p++) {
  23929. positions[lp + p] = positions[p];
  23930. }
  23931. // indices
  23932. for (i = 0; i < li; i += 3) {
  23933. indices[i + li] = indices[i + 2] + l;
  23934. indices[i + 1 + li] = indices[i + 1] + l;
  23935. indices[i + 2 + li] = indices[i] + l;
  23936. }
  23937. // normals
  23938. for (n = 0; n < ln; n++) {
  23939. normals[ln + n] = -normals[n];
  23940. }
  23941. // uvs
  23942. var lu = uvs.length;
  23943. for (var u = 0; u < lu; u++) {
  23944. uvs[u + lu] = uvs[u];
  23945. }
  23946. break;
  23947. }
  23948. };
  23949. return VertexData;
  23950. })();
  23951. BABYLON.VertexData = VertexData;
  23952. })(BABYLON || (BABYLON = {}));
  23953. var BABYLON;
  23954. (function (BABYLON) {
  23955. var Tags = (function () {
  23956. function Tags() {
  23957. }
  23958. Tags.EnableFor = function (obj) {
  23959. obj._tags = obj._tags || {};
  23960. obj.hasTags = function () {
  23961. return Tags.HasTags(obj);
  23962. };
  23963. obj.addTags = function (tagsString) {
  23964. return Tags.AddTagsTo(obj, tagsString);
  23965. };
  23966. obj.removeTags = function (tagsString) {
  23967. return Tags.RemoveTagsFrom(obj, tagsString);
  23968. };
  23969. obj.matchesTagsQuery = function (tagsQuery) {
  23970. return Tags.MatchesQuery(obj, tagsQuery);
  23971. };
  23972. };
  23973. Tags.DisableFor = function (obj) {
  23974. delete obj._tags;
  23975. delete obj.hasTags;
  23976. delete obj.addTags;
  23977. delete obj.removeTags;
  23978. delete obj.matchesTagsQuery;
  23979. };
  23980. Tags.HasTags = function (obj) {
  23981. if (!obj._tags) {
  23982. return false;
  23983. }
  23984. return !BABYLON.Tools.IsEmpty(obj._tags);
  23985. };
  23986. Tags.GetTags = function (obj) {
  23987. if (!obj._tags) {
  23988. return null;
  23989. }
  23990. return obj._tags;
  23991. };
  23992. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23993. // a tag cannot start with '||', '&&', and '!'
  23994. // it cannot contain whitespaces
  23995. Tags.AddTagsTo = function (obj, tagsString) {
  23996. if (!tagsString) {
  23997. return;
  23998. }
  23999. var tags = tagsString.split(" ");
  24000. for (var t in tags) {
  24001. Tags._AddTagTo(obj, tags[t]);
  24002. }
  24003. };
  24004. Tags._AddTagTo = function (obj, tag) {
  24005. tag = tag.trim();
  24006. if (tag === "" || tag === "true" || tag === "false") {
  24007. return;
  24008. }
  24009. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24010. return;
  24011. }
  24012. Tags.EnableFor(obj);
  24013. obj._tags[tag] = true;
  24014. };
  24015. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24016. if (!Tags.HasTags(obj)) {
  24017. return;
  24018. }
  24019. var tags = tagsString.split(" ");
  24020. for (var t in tags) {
  24021. Tags._RemoveTagFrom(obj, tags[t]);
  24022. }
  24023. };
  24024. Tags._RemoveTagFrom = function (obj, tag) {
  24025. delete obj._tags[tag];
  24026. };
  24027. Tags.MatchesQuery = function (obj, tagsQuery) {
  24028. if (tagsQuery === undefined) {
  24029. return true;
  24030. }
  24031. if (tagsQuery === "") {
  24032. return Tags.HasTags(obj);
  24033. }
  24034. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24035. };
  24036. return Tags;
  24037. })();
  24038. BABYLON.Tags = Tags;
  24039. })(BABYLON || (BABYLON = {}));
  24040. var BABYLON;
  24041. (function (BABYLON) {
  24042. var Internals;
  24043. (function (Internals) {
  24044. var AndOrNotEvaluator = (function () {
  24045. function AndOrNotEvaluator() {
  24046. }
  24047. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24048. if (!query.match(/\([^\(\)]*\)/g)) {
  24049. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24050. }
  24051. else {
  24052. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24053. // remove parenthesis
  24054. r = r.slice(1, r.length - 1);
  24055. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24056. });
  24057. }
  24058. if (query === "true") {
  24059. return true;
  24060. }
  24061. if (query === "false") {
  24062. return false;
  24063. }
  24064. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24065. };
  24066. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24067. evaluateCallback = evaluateCallback || (function (r) {
  24068. return r === "true" ? true : false;
  24069. });
  24070. var result;
  24071. var or = parenthesisContent.split("||");
  24072. for (var i in or) {
  24073. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24074. var and = ori.split("&&");
  24075. if (and.length > 1) {
  24076. for (var j = 0; j < and.length; ++j) {
  24077. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24078. if (andj !== "true" && andj !== "false") {
  24079. if (andj[0] === "!") {
  24080. result = !evaluateCallback(andj.substring(1));
  24081. }
  24082. else {
  24083. result = evaluateCallback(andj);
  24084. }
  24085. }
  24086. else {
  24087. result = andj === "true" ? true : false;
  24088. }
  24089. if (!result) {
  24090. ori = "false";
  24091. break;
  24092. }
  24093. }
  24094. }
  24095. if (result || ori === "true") {
  24096. result = true;
  24097. break;
  24098. }
  24099. // result equals false (or undefined)
  24100. if (ori !== "true" && ori !== "false") {
  24101. if (ori[0] === "!") {
  24102. result = !evaluateCallback(ori.substring(1));
  24103. }
  24104. else {
  24105. result = evaluateCallback(ori);
  24106. }
  24107. }
  24108. else {
  24109. result = ori === "true" ? true : false;
  24110. }
  24111. }
  24112. // the whole parenthesis scope is replaced by 'true' or 'false'
  24113. return result ? "true" : "false";
  24114. };
  24115. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24116. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24117. // remove whitespaces
  24118. r = r.replace(/[\s]/g, function () { return ""; });
  24119. return r.length % 2 ? "!" : "";
  24120. });
  24121. booleanString = booleanString.trim();
  24122. if (booleanString === "!true") {
  24123. booleanString = "false";
  24124. }
  24125. else if (booleanString === "!false") {
  24126. booleanString = "true";
  24127. }
  24128. return booleanString;
  24129. };
  24130. return AndOrNotEvaluator;
  24131. })();
  24132. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24133. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24134. })(BABYLON || (BABYLON = {}));
  24135. var BABYLON;
  24136. (function (BABYLON) {
  24137. var PostProcessRenderPass = (function () {
  24138. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24139. this._enabled = true;
  24140. this._refCount = 0;
  24141. this._name = name;
  24142. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24143. this.setRenderList(renderList);
  24144. this._renderTexture.onBeforeRender = beforeRender;
  24145. this._renderTexture.onAfterRender = afterRender;
  24146. this._scene = scene;
  24147. this._renderList = renderList;
  24148. }
  24149. // private
  24150. PostProcessRenderPass.prototype._incRefCount = function () {
  24151. if (this._refCount === 0) {
  24152. this._scene.customRenderTargets.push(this._renderTexture);
  24153. }
  24154. return ++this._refCount;
  24155. };
  24156. PostProcessRenderPass.prototype._decRefCount = function () {
  24157. this._refCount--;
  24158. if (this._refCount <= 0) {
  24159. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24160. }
  24161. return this._refCount;
  24162. };
  24163. PostProcessRenderPass.prototype._update = function () {
  24164. this.setRenderList(this._renderList);
  24165. };
  24166. // public
  24167. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24168. this._renderTexture.renderList = renderList;
  24169. };
  24170. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24171. return this._renderTexture;
  24172. };
  24173. return PostProcessRenderPass;
  24174. })();
  24175. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24176. })(BABYLON || (BABYLON = {}));
  24177. var BABYLON;
  24178. (function (BABYLON) {
  24179. var PostProcessRenderEffect = (function () {
  24180. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24181. this._engine = engine;
  24182. this._name = name;
  24183. this._singleInstance = singleInstance || true;
  24184. this._getPostProcess = getPostProcess;
  24185. this._cameras = [];
  24186. this._indicesForCamera = [];
  24187. this._postProcesses = {};
  24188. this._renderPasses = {};
  24189. this._renderEffectAsPasses = {};
  24190. }
  24191. PostProcessRenderEffect.prototype._update = function () {
  24192. for (var renderPassName in this._renderPasses) {
  24193. this._renderPasses[renderPassName]._update();
  24194. }
  24195. };
  24196. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24197. this._renderPasses[renderPass._name] = renderPass;
  24198. this._linkParameters();
  24199. };
  24200. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24201. delete this._renderPasses[renderPass._name];
  24202. this._linkParameters();
  24203. };
  24204. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24205. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24206. this._linkParameters();
  24207. };
  24208. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24209. for (var renderPassName in this._renderPasses) {
  24210. if (renderPassName === passName) {
  24211. return this._renderPasses[passName];
  24212. }
  24213. }
  24214. };
  24215. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24216. this._renderPasses = {};
  24217. this._linkParameters();
  24218. };
  24219. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24220. var cameraKey;
  24221. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24222. for (var i = 0; i < _cam.length; i++) {
  24223. var camera = _cam[i];
  24224. var cameraName = camera.name;
  24225. if (this._singleInstance) {
  24226. cameraKey = 0;
  24227. }
  24228. else {
  24229. cameraKey = cameraName;
  24230. }
  24231. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24232. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24233. if (!this._indicesForCamera[cameraName]) {
  24234. this._indicesForCamera[cameraName] = [];
  24235. }
  24236. this._indicesForCamera[cameraName].push(index);
  24237. if (this._cameras.indexOf(camera) === -1) {
  24238. this._cameras[cameraName] = camera;
  24239. }
  24240. for (var passName in this._renderPasses) {
  24241. this._renderPasses[passName]._incRefCount();
  24242. }
  24243. }
  24244. this._linkParameters();
  24245. };
  24246. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24247. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24248. for (var i = 0; i < _cam.length; i++) {
  24249. var camera = _cam[i];
  24250. var cameraName = camera.name;
  24251. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24252. var index = this._cameras.indexOf(cameraName);
  24253. this._indicesForCamera.splice(index, 1);
  24254. this._cameras.splice(index, 1);
  24255. for (var passName in this._renderPasses) {
  24256. this._renderPasses[passName]._decRefCount();
  24257. }
  24258. }
  24259. };
  24260. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24261. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24262. for (var i = 0; i < _cam.length; i++) {
  24263. var camera = _cam[i];
  24264. var cameraName = camera.name;
  24265. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24266. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24267. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24268. }
  24269. }
  24270. for (var passName in this._renderPasses) {
  24271. this._renderPasses[passName]._incRefCount();
  24272. }
  24273. }
  24274. };
  24275. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24276. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24277. for (var i = 0; i < _cam.length; i++) {
  24278. var camera = _cam[i];
  24279. var cameraName = camera.Name;
  24280. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24281. for (var passName in this._renderPasses) {
  24282. this._renderPasses[passName]._decRefCount();
  24283. }
  24284. }
  24285. };
  24286. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24287. if (this._singleInstance) {
  24288. return this._postProcesses[0];
  24289. }
  24290. else {
  24291. return this._postProcesses[camera.name];
  24292. }
  24293. };
  24294. PostProcessRenderEffect.prototype._linkParameters = function () {
  24295. var _this = this;
  24296. for (var index in this._postProcesses) {
  24297. if (this.applyParameters) {
  24298. this.applyParameters(this._postProcesses[index]);
  24299. }
  24300. this._postProcesses[index].onBeforeRender = function (effect) {
  24301. _this._linkTextures(effect);
  24302. };
  24303. }
  24304. };
  24305. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24306. for (var renderPassName in this._renderPasses) {
  24307. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24308. }
  24309. for (var renderEffectName in this._renderEffectAsPasses) {
  24310. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24311. }
  24312. };
  24313. return PostProcessRenderEffect;
  24314. })();
  24315. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24316. })(BABYLON || (BABYLON = {}));
  24317. var BABYLON;
  24318. (function (BABYLON) {
  24319. var PostProcessRenderPipeline = (function () {
  24320. function PostProcessRenderPipeline(engine, name) {
  24321. this._engine = engine;
  24322. this._name = name;
  24323. this._renderEffects = {};
  24324. this._renderEffectsForIsolatedPass = {};
  24325. this._cameras = [];
  24326. }
  24327. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24328. this._renderEffects[renderEffect._name] = renderEffect;
  24329. };
  24330. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24331. var renderEffects = this._renderEffects[renderEffectName];
  24332. if (!renderEffects) {
  24333. return;
  24334. }
  24335. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24336. };
  24337. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24338. var renderEffects = this._renderEffects[renderEffectName];
  24339. if (!renderEffects) {
  24340. return;
  24341. }
  24342. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24343. };
  24344. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24345. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24346. var indicesToDelete = [];
  24347. for (var i = 0; i < _cam.length; i++) {
  24348. var camera = _cam[i];
  24349. var cameraName = camera.name;
  24350. if (this._cameras.indexOf(camera) === -1) {
  24351. this._cameras[cameraName] = camera;
  24352. }
  24353. else if (unique) {
  24354. indicesToDelete.push(i);
  24355. }
  24356. }
  24357. for (var i = 0; i < indicesToDelete.length; i++) {
  24358. cameras.splice(indicesToDelete[i], 1);
  24359. }
  24360. for (var renderEffectName in this._renderEffects) {
  24361. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24362. }
  24363. };
  24364. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24365. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24366. for (var renderEffectName in this._renderEffects) {
  24367. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24368. }
  24369. for (var i = 0; i < _cam.length; i++) {
  24370. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24371. }
  24372. };
  24373. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24374. var _this = this;
  24375. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24376. var pass = null;
  24377. for (var renderEffectName in this._renderEffects) {
  24378. pass = this._renderEffects[renderEffectName].getPass(passName);
  24379. if (pass != null) {
  24380. break;
  24381. }
  24382. }
  24383. if (pass === null) {
  24384. return;
  24385. }
  24386. for (var renderEffectName in this._renderEffects) {
  24387. this._renderEffects[renderEffectName]._disable(_cam);
  24388. }
  24389. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24390. for (var i = 0; i < _cam.length; i++) {
  24391. var camera = _cam[i];
  24392. var cameraName = camera.name;
  24393. 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); });
  24394. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24395. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24396. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24397. }
  24398. };
  24399. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24400. var _this = this;
  24401. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24402. for (var i = 0; i < _cam.length; i++) {
  24403. var camera = _cam[i];
  24404. var cameraName = camera.name;
  24405. 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); });
  24406. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24407. }
  24408. for (var renderEffectName in this._renderEffects) {
  24409. this._renderEffects[renderEffectName]._enable(_cam);
  24410. }
  24411. };
  24412. PostProcessRenderPipeline.prototype._update = function () {
  24413. for (var renderEffectName in this._renderEffects) {
  24414. this._renderEffects[renderEffectName]._update();
  24415. }
  24416. for (var i = 0; i < this._cameras.length; i++) {
  24417. var cameraName = this._cameras[i].name;
  24418. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24419. this._renderEffectsForIsolatedPass[cameraName]._update();
  24420. }
  24421. }
  24422. };
  24423. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24424. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24425. return PostProcessRenderPipeline;
  24426. })();
  24427. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24428. })(BABYLON || (BABYLON = {}));
  24429. var BABYLON;
  24430. (function (BABYLON) {
  24431. var PostProcessRenderPipelineManager = (function () {
  24432. function PostProcessRenderPipelineManager() {
  24433. this._renderPipelines = {};
  24434. }
  24435. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24436. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24437. };
  24438. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24439. var renderPipeline = this._renderPipelines[renderPipelineName];
  24440. if (!renderPipeline) {
  24441. return;
  24442. }
  24443. renderPipeline._attachCameras(cameras, unique);
  24444. };
  24445. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24446. var renderPipeline = this._renderPipelines[renderPipelineName];
  24447. if (!renderPipeline) {
  24448. return;
  24449. }
  24450. renderPipeline._detachCameras(cameras);
  24451. };
  24452. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24453. var renderPipeline = this._renderPipelines[renderPipelineName];
  24454. if (!renderPipeline) {
  24455. return;
  24456. }
  24457. renderPipeline._enableEffect(renderEffectName, cameras);
  24458. };
  24459. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24460. var renderPipeline = this._renderPipelines[renderPipelineName];
  24461. if (!renderPipeline) {
  24462. return;
  24463. }
  24464. renderPipeline._disableEffect(renderEffectName, cameras);
  24465. };
  24466. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24467. var renderPipeline = this._renderPipelines[renderPipelineName];
  24468. if (!renderPipeline) {
  24469. return;
  24470. }
  24471. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24472. };
  24473. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24474. var renderPipeline = this._renderPipelines[renderPipelineName];
  24475. if (!renderPipeline) {
  24476. return;
  24477. }
  24478. renderPipeline._disableDisplayOnlyPass(cameras);
  24479. };
  24480. PostProcessRenderPipelineManager.prototype.update = function () {
  24481. for (var renderPipelineName in this._renderPipelines) {
  24482. this._renderPipelines[renderPipelineName]._update();
  24483. }
  24484. };
  24485. return PostProcessRenderPipelineManager;
  24486. })();
  24487. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24488. })(BABYLON || (BABYLON = {}));
  24489. var BABYLON;
  24490. (function (BABYLON) {
  24491. var BoundingBoxRenderer = (function () {
  24492. function BoundingBoxRenderer(scene) {
  24493. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24494. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24495. this.showBackLines = true;
  24496. this.renderList = new BABYLON.SmartArray(32);
  24497. this._scene = scene;
  24498. }
  24499. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24500. if (this._colorShader) {
  24501. return;
  24502. }
  24503. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24504. attributes: ["position"],
  24505. uniforms: ["worldViewProjection", "color"]
  24506. });
  24507. var engine = this._scene.getEngine();
  24508. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24509. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24510. 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]);
  24511. };
  24512. BoundingBoxRenderer.prototype.reset = function () {
  24513. this.renderList.reset();
  24514. };
  24515. BoundingBoxRenderer.prototype.render = function () {
  24516. if (this.renderList.length === 0) {
  24517. return;
  24518. }
  24519. this._prepareRessources();
  24520. if (!this._colorShader.isReady()) {
  24521. return;
  24522. }
  24523. var engine = this._scene.getEngine();
  24524. engine.setDepthWrite(false);
  24525. this._colorShader._preBind();
  24526. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24527. var boundingBox = this.renderList.data[boundingBoxIndex];
  24528. var min = boundingBox.minimum;
  24529. var max = boundingBox.maximum;
  24530. var diff = max.subtract(min);
  24531. var median = min.add(diff.scale(0.5));
  24532. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24533. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24534. .multiply(boundingBox.getWorldMatrix());
  24535. // VBOs
  24536. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24537. if (this.showBackLines) {
  24538. // Back
  24539. engine.setDepthFunctionToGreaterOrEqual();
  24540. this._scene.resetCachedMaterial();
  24541. this._colorShader.setColor4("color", this.backColor.toColor4());
  24542. this._colorShader.bind(worldMatrix);
  24543. // Draw order
  24544. engine.draw(false, 0, 24);
  24545. }
  24546. // Front
  24547. engine.setDepthFunctionToLess();
  24548. this._scene.resetCachedMaterial();
  24549. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24550. this._colorShader.bind(worldMatrix);
  24551. // Draw order
  24552. engine.draw(false, 0, 24);
  24553. }
  24554. this._colorShader.unbind();
  24555. engine.setDepthFunctionToLessOrEqual();
  24556. engine.setDepthWrite(true);
  24557. };
  24558. BoundingBoxRenderer.prototype.dispose = function () {
  24559. if (!this._colorShader) {
  24560. return;
  24561. }
  24562. this._colorShader.dispose();
  24563. this._vb.dispose();
  24564. this._scene.getEngine()._releaseBuffer(this._ib);
  24565. };
  24566. return BoundingBoxRenderer;
  24567. })();
  24568. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  24569. })(BABYLON || (BABYLON = {}));
  24570. var BABYLON;
  24571. (function (BABYLON) {
  24572. var Condition = (function () {
  24573. function Condition(actionManager) {
  24574. this._actionManager = actionManager;
  24575. }
  24576. Condition.prototype.isValid = function () {
  24577. return true;
  24578. };
  24579. Condition.prototype._getProperty = function (propertyPath) {
  24580. return this._actionManager._getProperty(propertyPath);
  24581. };
  24582. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24583. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24584. };
  24585. return Condition;
  24586. })();
  24587. BABYLON.Condition = Condition;
  24588. var ValueCondition = (function (_super) {
  24589. __extends(ValueCondition, _super);
  24590. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24591. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24592. _super.call(this, actionManager);
  24593. this.propertyPath = propertyPath;
  24594. this.value = value;
  24595. this.operator = operator;
  24596. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24597. this._property = this._getProperty(this.propertyPath);
  24598. }
  24599. Object.defineProperty(ValueCondition, "IsEqual", {
  24600. get: function () {
  24601. return ValueCondition._IsEqual;
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. Object.defineProperty(ValueCondition, "IsDifferent", {
  24607. get: function () {
  24608. return ValueCondition._IsDifferent;
  24609. },
  24610. enumerable: true,
  24611. configurable: true
  24612. });
  24613. Object.defineProperty(ValueCondition, "IsGreater", {
  24614. get: function () {
  24615. return ValueCondition._IsGreater;
  24616. },
  24617. enumerable: true,
  24618. configurable: true
  24619. });
  24620. Object.defineProperty(ValueCondition, "IsLesser", {
  24621. get: function () {
  24622. return ValueCondition._IsLesser;
  24623. },
  24624. enumerable: true,
  24625. configurable: true
  24626. });
  24627. // Methods
  24628. ValueCondition.prototype.isValid = function () {
  24629. switch (this.operator) {
  24630. case ValueCondition.IsGreater:
  24631. return this._target[this._property] > this.value;
  24632. case ValueCondition.IsLesser:
  24633. return this._target[this._property] < this.value;
  24634. case ValueCondition.IsEqual:
  24635. case ValueCondition.IsDifferent:
  24636. var check;
  24637. if (this.value.equals) {
  24638. check = this.value.equals(this._target[this._property]);
  24639. }
  24640. else {
  24641. check = this.value === this._target[this._property];
  24642. }
  24643. return this.operator === ValueCondition.IsEqual ? check : !check;
  24644. }
  24645. return false;
  24646. };
  24647. // Statics
  24648. ValueCondition._IsEqual = 0;
  24649. ValueCondition._IsDifferent = 1;
  24650. ValueCondition._IsGreater = 2;
  24651. ValueCondition._IsLesser = 3;
  24652. return ValueCondition;
  24653. })(Condition);
  24654. BABYLON.ValueCondition = ValueCondition;
  24655. var PredicateCondition = (function (_super) {
  24656. __extends(PredicateCondition, _super);
  24657. function PredicateCondition(actionManager, predicate) {
  24658. _super.call(this, actionManager);
  24659. this.predicate = predicate;
  24660. }
  24661. PredicateCondition.prototype.isValid = function () {
  24662. return this.predicate();
  24663. };
  24664. return PredicateCondition;
  24665. })(Condition);
  24666. BABYLON.PredicateCondition = PredicateCondition;
  24667. var StateCondition = (function (_super) {
  24668. __extends(StateCondition, _super);
  24669. function StateCondition(actionManager, target, value) {
  24670. _super.call(this, actionManager);
  24671. this.value = value;
  24672. this._target = target;
  24673. }
  24674. // Methods
  24675. StateCondition.prototype.isValid = function () {
  24676. return this._target.state === this.value;
  24677. };
  24678. return StateCondition;
  24679. })(Condition);
  24680. BABYLON.StateCondition = StateCondition;
  24681. })(BABYLON || (BABYLON = {}));
  24682. var BABYLON;
  24683. (function (BABYLON) {
  24684. var Action = (function () {
  24685. function Action(triggerOptions, condition) {
  24686. this.triggerOptions = triggerOptions;
  24687. if (triggerOptions.parameter) {
  24688. this.trigger = triggerOptions.trigger;
  24689. this._triggerParameter = triggerOptions.parameter;
  24690. }
  24691. else {
  24692. this.trigger = triggerOptions;
  24693. }
  24694. this._nextActiveAction = this;
  24695. this._condition = condition;
  24696. }
  24697. // Methods
  24698. Action.prototype._prepare = function () {
  24699. };
  24700. Action.prototype.getTriggerParameter = function () {
  24701. return this._triggerParameter;
  24702. };
  24703. Action.prototype._executeCurrent = function (evt) {
  24704. if (this._nextActiveAction._condition) {
  24705. var condition = this._nextActiveAction._condition;
  24706. var currentRenderId = this._actionManager.getScene().getRenderId();
  24707. // We cache the current evaluation for the current frame
  24708. if (condition._evaluationId === currentRenderId) {
  24709. if (!condition._currentResult) {
  24710. return;
  24711. }
  24712. }
  24713. else {
  24714. condition._evaluationId = currentRenderId;
  24715. if (!condition.isValid()) {
  24716. condition._currentResult = false;
  24717. return;
  24718. }
  24719. condition._currentResult = true;
  24720. }
  24721. }
  24722. this._nextActiveAction.execute(evt);
  24723. if (this._nextActiveAction._child) {
  24724. if (!this._nextActiveAction._child._actionManager) {
  24725. this._nextActiveAction._child._actionManager = this._actionManager;
  24726. }
  24727. this._nextActiveAction = this._nextActiveAction._child;
  24728. }
  24729. else {
  24730. this._nextActiveAction = this;
  24731. }
  24732. };
  24733. Action.prototype.execute = function (evt) {
  24734. };
  24735. Action.prototype.then = function (action) {
  24736. this._child = action;
  24737. action._actionManager = this._actionManager;
  24738. action._prepare();
  24739. return action;
  24740. };
  24741. Action.prototype._getProperty = function (propertyPath) {
  24742. return this._actionManager._getProperty(propertyPath);
  24743. };
  24744. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24745. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24746. };
  24747. return Action;
  24748. })();
  24749. BABYLON.Action = Action;
  24750. })(BABYLON || (BABYLON = {}));
  24751. var BABYLON;
  24752. (function (BABYLON) {
  24753. /**
  24754. * ActionEvent is the event beint sent when an action is triggered.
  24755. */
  24756. var ActionEvent = (function () {
  24757. /**
  24758. * @constructor
  24759. * @param source The mesh or sprite that triggered the action.
  24760. * @param pointerX The X mouse cursor position at the time of the event
  24761. * @param pointerY The Y mouse cursor position at the time of the event
  24762. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24763. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24764. */
  24765. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  24766. this.source = source;
  24767. this.pointerX = pointerX;
  24768. this.pointerY = pointerY;
  24769. this.meshUnderPointer = meshUnderPointer;
  24770. this.sourceEvent = sourceEvent;
  24771. this.additionalData = additionalData;
  24772. }
  24773. /**
  24774. * Helper function to auto-create an ActionEvent from a source mesh.
  24775. * @param source The source mesh that triggered the event
  24776. * @param evt {Event} The original (browser) event
  24777. */
  24778. ActionEvent.CreateNew = function (source, evt, additionalData) {
  24779. var scene = source.getScene();
  24780. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24781. };
  24782. /**
  24783. * Helper function to auto-create an ActionEvent from a source mesh.
  24784. * @param source The source sprite that triggered the event
  24785. * @param scene Scene associated with the sprite
  24786. * @param evt {Event} The original (browser) event
  24787. */
  24788. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  24789. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24790. };
  24791. /**
  24792. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24793. * @param scene the scene where the event occurred
  24794. * @param evt {Event} The original (browser) event
  24795. */
  24796. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24797. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24798. };
  24799. return ActionEvent;
  24800. })();
  24801. BABYLON.ActionEvent = ActionEvent;
  24802. /**
  24803. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24804. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24805. */
  24806. var ActionManager = (function () {
  24807. function ActionManager(scene) {
  24808. // Members
  24809. this.actions = new Array();
  24810. this._scene = scene;
  24811. scene._actionManagers.push(this);
  24812. }
  24813. Object.defineProperty(ActionManager, "NothingTrigger", {
  24814. get: function () {
  24815. return ActionManager._NothingTrigger;
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24821. get: function () {
  24822. return ActionManager._OnPickTrigger;
  24823. },
  24824. enumerable: true,
  24825. configurable: true
  24826. });
  24827. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24828. get: function () {
  24829. return ActionManager._OnLeftPickTrigger;
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24835. get: function () {
  24836. return ActionManager._OnRightPickTrigger;
  24837. },
  24838. enumerable: true,
  24839. configurable: true
  24840. });
  24841. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24842. get: function () {
  24843. return ActionManager._OnCenterPickTrigger;
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24849. get: function () {
  24850. return ActionManager._OnPointerOverTrigger;
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24856. get: function () {
  24857. return ActionManager._OnPointerOutTrigger;
  24858. },
  24859. enumerable: true,
  24860. configurable: true
  24861. });
  24862. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24863. get: function () {
  24864. return ActionManager._OnEveryFrameTrigger;
  24865. },
  24866. enumerable: true,
  24867. configurable: true
  24868. });
  24869. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24870. get: function () {
  24871. return ActionManager._OnIntersectionEnterTrigger;
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24877. get: function () {
  24878. return ActionManager._OnIntersectionExitTrigger;
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24884. get: function () {
  24885. return ActionManager._OnKeyDownTrigger;
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24891. get: function () {
  24892. return ActionManager._OnKeyUpTrigger;
  24893. },
  24894. enumerable: true,
  24895. configurable: true
  24896. });
  24897. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  24898. get: function () {
  24899. return ActionManager._OnPickUpTrigger;
  24900. },
  24901. enumerable: true,
  24902. configurable: true
  24903. });
  24904. // Methods
  24905. ActionManager.prototype.dispose = function () {
  24906. var index = this._scene._actionManagers.indexOf(this);
  24907. if (index > -1) {
  24908. this._scene._actionManagers.splice(index, 1);
  24909. }
  24910. };
  24911. ActionManager.prototype.getScene = function () {
  24912. return this._scene;
  24913. };
  24914. /**
  24915. * Does this action manager handles actions of any of the given triggers
  24916. * @param {number[]} triggers - the triggers to be tested
  24917. * @return {boolean} whether one (or more) of the triggers is handeled
  24918. */
  24919. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24920. for (var index = 0; index < this.actions.length; index++) {
  24921. var action = this.actions[index];
  24922. if (triggers.indexOf(action.trigger) > -1) {
  24923. return true;
  24924. }
  24925. }
  24926. return false;
  24927. };
  24928. /**
  24929. * Does this action manager handles actions of a given trigger
  24930. * @param {number} trigger - the trigger to be tested
  24931. * @return {boolean} whether the trigger is handeled
  24932. */
  24933. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  24934. for (var index = 0; index < this.actions.length; index++) {
  24935. var action = this.actions[index];
  24936. if (action.trigger === trigger) {
  24937. return true;
  24938. }
  24939. }
  24940. return false;
  24941. };
  24942. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24943. /**
  24944. * Does this action manager has pointer triggers
  24945. * @return {boolean} whether or not it has pointer triggers
  24946. */
  24947. get: function () {
  24948. for (var index = 0; index < this.actions.length; index++) {
  24949. var action = this.actions[index];
  24950. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24951. return true;
  24952. }
  24953. if (action.trigger === ActionManager._OnPickUpTrigger) {
  24954. return true;
  24955. }
  24956. }
  24957. return false;
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24963. /**
  24964. * Does this action manager has pick triggers
  24965. * @return {boolean} whether or not it has pick triggers
  24966. */
  24967. get: function () {
  24968. for (var index = 0; index < this.actions.length; index++) {
  24969. var action = this.actions[index];
  24970. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24971. return true;
  24972. }
  24973. if (action.trigger === ActionManager._OnPickUpTrigger) {
  24974. return true;
  24975. }
  24976. }
  24977. return false;
  24978. },
  24979. enumerable: true,
  24980. configurable: true
  24981. });
  24982. /**
  24983. * Registers an action to this action manager
  24984. * @param {BABYLON.Action} action - the action to be registered
  24985. * @return {BABYLON.Action} the action amended (prepared) after registration
  24986. */
  24987. ActionManager.prototype.registerAction = function (action) {
  24988. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24989. if (this.getScene().actionManager !== this) {
  24990. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24991. return null;
  24992. }
  24993. }
  24994. this.actions.push(action);
  24995. action._actionManager = this;
  24996. action._prepare();
  24997. return action;
  24998. };
  24999. /**
  25000. * Process a specific trigger
  25001. * @param {number} trigger - the trigger to process
  25002. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25003. */
  25004. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25005. for (var index = 0; index < this.actions.length; index++) {
  25006. var action = this.actions[index];
  25007. if (action.trigger === trigger) {
  25008. if (trigger === ActionManager.OnKeyUpTrigger
  25009. || trigger === ActionManager.OnKeyDownTrigger) {
  25010. var parameter = action.getTriggerParameter();
  25011. if (parameter) {
  25012. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25013. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25014. if (actualkey !== parameter.toLowerCase()) {
  25015. continue;
  25016. }
  25017. }
  25018. }
  25019. action._executeCurrent(evt);
  25020. }
  25021. }
  25022. };
  25023. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25024. var properties = propertyPath.split(".");
  25025. for (var index = 0; index < properties.length - 1; index++) {
  25026. target = target[properties[index]];
  25027. }
  25028. return target;
  25029. };
  25030. ActionManager.prototype._getProperty = function (propertyPath) {
  25031. var properties = propertyPath.split(".");
  25032. return properties[properties.length - 1];
  25033. };
  25034. // Statics
  25035. ActionManager._NothingTrigger = 0;
  25036. ActionManager._OnPickTrigger = 1;
  25037. ActionManager._OnLeftPickTrigger = 2;
  25038. ActionManager._OnRightPickTrigger = 3;
  25039. ActionManager._OnCenterPickTrigger = 4;
  25040. ActionManager._OnPointerOverTrigger = 5;
  25041. ActionManager._OnPointerOutTrigger = 6;
  25042. ActionManager._OnEveryFrameTrigger = 7;
  25043. ActionManager._OnIntersectionEnterTrigger = 8;
  25044. ActionManager._OnIntersectionExitTrigger = 9;
  25045. ActionManager._OnKeyDownTrigger = 10;
  25046. ActionManager._OnKeyUpTrigger = 11;
  25047. ActionManager._OnPickUpTrigger = 12;
  25048. return ActionManager;
  25049. })();
  25050. BABYLON.ActionManager = ActionManager;
  25051. })(BABYLON || (BABYLON = {}));
  25052. var BABYLON;
  25053. (function (BABYLON) {
  25054. var InterpolateValueAction = (function (_super) {
  25055. __extends(InterpolateValueAction, _super);
  25056. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25057. if (duration === void 0) { duration = 1000; }
  25058. _super.call(this, triggerOptions, condition);
  25059. this.propertyPath = propertyPath;
  25060. this.value = value;
  25061. this.duration = duration;
  25062. this.stopOtherAnimations = stopOtherAnimations;
  25063. this.onInterpolationDone = onInterpolationDone;
  25064. this._target = target;
  25065. }
  25066. InterpolateValueAction.prototype._prepare = function () {
  25067. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25068. this._property = this._getProperty(this.propertyPath);
  25069. };
  25070. InterpolateValueAction.prototype.execute = function () {
  25071. var scene = this._actionManager.getScene();
  25072. var keys = [
  25073. {
  25074. frame: 0,
  25075. value: this._target[this._property]
  25076. }, {
  25077. frame: 100,
  25078. value: this.value
  25079. }
  25080. ];
  25081. var dataType;
  25082. if (typeof this.value === "number") {
  25083. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25084. }
  25085. else if (this.value instanceof BABYLON.Color3) {
  25086. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25087. }
  25088. else if (this.value instanceof BABYLON.Vector3) {
  25089. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25090. }
  25091. else if (this.value instanceof BABYLON.Matrix) {
  25092. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25093. }
  25094. else if (this.value instanceof BABYLON.Quaternion) {
  25095. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25096. }
  25097. else {
  25098. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25099. return;
  25100. }
  25101. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25102. animation.setKeys(keys);
  25103. if (this.stopOtherAnimations) {
  25104. scene.stopAnimation(this._target);
  25105. }
  25106. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25107. };
  25108. return InterpolateValueAction;
  25109. })(BABYLON.Action);
  25110. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25111. })(BABYLON || (BABYLON = {}));
  25112. var BABYLON;
  25113. (function (BABYLON) {
  25114. var SwitchBooleanAction = (function (_super) {
  25115. __extends(SwitchBooleanAction, _super);
  25116. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25117. _super.call(this, triggerOptions, condition);
  25118. this.propertyPath = propertyPath;
  25119. this._target = target;
  25120. }
  25121. SwitchBooleanAction.prototype._prepare = function () {
  25122. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25123. this._property = this._getProperty(this.propertyPath);
  25124. };
  25125. SwitchBooleanAction.prototype.execute = function () {
  25126. this._target[this._property] = !this._target[this._property];
  25127. };
  25128. return SwitchBooleanAction;
  25129. })(BABYLON.Action);
  25130. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25131. var SetStateAction = (function (_super) {
  25132. __extends(SetStateAction, _super);
  25133. function SetStateAction(triggerOptions, target, value, condition) {
  25134. _super.call(this, triggerOptions, condition);
  25135. this.value = value;
  25136. this._target = target;
  25137. }
  25138. SetStateAction.prototype.execute = function () {
  25139. this._target.state = this.value;
  25140. };
  25141. return SetStateAction;
  25142. })(BABYLON.Action);
  25143. BABYLON.SetStateAction = SetStateAction;
  25144. var SetValueAction = (function (_super) {
  25145. __extends(SetValueAction, _super);
  25146. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25147. _super.call(this, triggerOptions, condition);
  25148. this.propertyPath = propertyPath;
  25149. this.value = value;
  25150. this._target = target;
  25151. }
  25152. SetValueAction.prototype._prepare = function () {
  25153. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25154. this._property = this._getProperty(this.propertyPath);
  25155. };
  25156. SetValueAction.prototype.execute = function () {
  25157. this._target[this._property] = this.value;
  25158. };
  25159. return SetValueAction;
  25160. })(BABYLON.Action);
  25161. BABYLON.SetValueAction = SetValueAction;
  25162. var IncrementValueAction = (function (_super) {
  25163. __extends(IncrementValueAction, _super);
  25164. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25165. _super.call(this, triggerOptions, condition);
  25166. this.propertyPath = propertyPath;
  25167. this.value = value;
  25168. this._target = target;
  25169. }
  25170. IncrementValueAction.prototype._prepare = function () {
  25171. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25172. this._property = this._getProperty(this.propertyPath);
  25173. if (typeof this._target[this._property] !== "number") {
  25174. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25175. }
  25176. };
  25177. IncrementValueAction.prototype.execute = function () {
  25178. this._target[this._property] += this.value;
  25179. };
  25180. return IncrementValueAction;
  25181. })(BABYLON.Action);
  25182. BABYLON.IncrementValueAction = IncrementValueAction;
  25183. var PlayAnimationAction = (function (_super) {
  25184. __extends(PlayAnimationAction, _super);
  25185. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25186. _super.call(this, triggerOptions, condition);
  25187. this.from = from;
  25188. this.to = to;
  25189. this.loop = loop;
  25190. this._target = target;
  25191. }
  25192. PlayAnimationAction.prototype._prepare = function () {
  25193. };
  25194. PlayAnimationAction.prototype.execute = function () {
  25195. var scene = this._actionManager.getScene();
  25196. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25197. };
  25198. return PlayAnimationAction;
  25199. })(BABYLON.Action);
  25200. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25201. var StopAnimationAction = (function (_super) {
  25202. __extends(StopAnimationAction, _super);
  25203. function StopAnimationAction(triggerOptions, target, condition) {
  25204. _super.call(this, triggerOptions, condition);
  25205. this._target = target;
  25206. }
  25207. StopAnimationAction.prototype._prepare = function () {
  25208. };
  25209. StopAnimationAction.prototype.execute = function () {
  25210. var scene = this._actionManager.getScene();
  25211. scene.stopAnimation(this._target);
  25212. };
  25213. return StopAnimationAction;
  25214. })(BABYLON.Action);
  25215. BABYLON.StopAnimationAction = StopAnimationAction;
  25216. var DoNothingAction = (function (_super) {
  25217. __extends(DoNothingAction, _super);
  25218. function DoNothingAction(triggerOptions, condition) {
  25219. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25220. _super.call(this, triggerOptions, condition);
  25221. }
  25222. DoNothingAction.prototype.execute = function () {
  25223. };
  25224. return DoNothingAction;
  25225. })(BABYLON.Action);
  25226. BABYLON.DoNothingAction = DoNothingAction;
  25227. var CombineAction = (function (_super) {
  25228. __extends(CombineAction, _super);
  25229. function CombineAction(triggerOptions, children, condition) {
  25230. _super.call(this, triggerOptions, condition);
  25231. this.children = children;
  25232. }
  25233. CombineAction.prototype._prepare = function () {
  25234. for (var index = 0; index < this.children.length; index++) {
  25235. this.children[index]._actionManager = this._actionManager;
  25236. this.children[index]._prepare();
  25237. }
  25238. };
  25239. CombineAction.prototype.execute = function (evt) {
  25240. for (var index = 0; index < this.children.length; index++) {
  25241. this.children[index].execute(evt);
  25242. }
  25243. };
  25244. return CombineAction;
  25245. })(BABYLON.Action);
  25246. BABYLON.CombineAction = CombineAction;
  25247. var ExecuteCodeAction = (function (_super) {
  25248. __extends(ExecuteCodeAction, _super);
  25249. function ExecuteCodeAction(triggerOptions, func, condition) {
  25250. _super.call(this, triggerOptions, condition);
  25251. this.func = func;
  25252. }
  25253. ExecuteCodeAction.prototype.execute = function (evt) {
  25254. this.func(evt);
  25255. };
  25256. return ExecuteCodeAction;
  25257. })(BABYLON.Action);
  25258. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25259. var SetParentAction = (function (_super) {
  25260. __extends(SetParentAction, _super);
  25261. function SetParentAction(triggerOptions, target, parent, condition) {
  25262. _super.call(this, triggerOptions, condition);
  25263. this._target = target;
  25264. this._parent = parent;
  25265. }
  25266. SetParentAction.prototype._prepare = function () {
  25267. };
  25268. SetParentAction.prototype.execute = function () {
  25269. if (this._target.parent === this._parent) {
  25270. return;
  25271. }
  25272. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25273. invertParentWorldMatrix.invert();
  25274. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25275. this._target.parent = this._parent;
  25276. };
  25277. return SetParentAction;
  25278. })(BABYLON.Action);
  25279. BABYLON.SetParentAction = SetParentAction;
  25280. var PlaySoundAction = (function (_super) {
  25281. __extends(PlaySoundAction, _super);
  25282. function PlaySoundAction(triggerOptions, sound, condition) {
  25283. _super.call(this, triggerOptions, condition);
  25284. this._sound = sound;
  25285. }
  25286. PlaySoundAction.prototype._prepare = function () {
  25287. };
  25288. PlaySoundAction.prototype.execute = function () {
  25289. if (this._sound !== undefined)
  25290. this._sound.play();
  25291. };
  25292. return PlaySoundAction;
  25293. })(BABYLON.Action);
  25294. BABYLON.PlaySoundAction = PlaySoundAction;
  25295. var StopSoundAction = (function (_super) {
  25296. __extends(StopSoundAction, _super);
  25297. function StopSoundAction(triggerOptions, sound, condition) {
  25298. _super.call(this, triggerOptions, condition);
  25299. this._sound = sound;
  25300. }
  25301. StopSoundAction.prototype._prepare = function () {
  25302. };
  25303. StopSoundAction.prototype.execute = function () {
  25304. if (this._sound !== undefined)
  25305. this._sound.stop();
  25306. };
  25307. return StopSoundAction;
  25308. })(BABYLON.Action);
  25309. BABYLON.StopSoundAction = StopSoundAction;
  25310. })(BABYLON || (BABYLON = {}));
  25311. var BABYLON;
  25312. (function (BABYLON) {
  25313. var Geometry = (function () {
  25314. function Geometry(id, scene, vertexData, updatable, mesh) {
  25315. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25316. this._totalVertices = 0;
  25317. this._isDisposed = false;
  25318. this.id = id;
  25319. this._engine = scene.getEngine();
  25320. this._meshes = [];
  25321. this._scene = scene;
  25322. //Init vertex buffer cache
  25323. this._vertexBuffers = {};
  25324. this._indices = [];
  25325. // vertexData
  25326. if (vertexData) {
  25327. this.setAllVerticesData(vertexData, updatable);
  25328. }
  25329. else {
  25330. this._totalVertices = 0;
  25331. this._indices = [];
  25332. }
  25333. // applyToMesh
  25334. if (mesh) {
  25335. this.applyToMesh(mesh);
  25336. mesh.computeWorldMatrix(true);
  25337. }
  25338. }
  25339. Object.defineProperty(Geometry.prototype, "extend", {
  25340. get: function () {
  25341. return this._extend;
  25342. },
  25343. enumerable: true,
  25344. configurable: true
  25345. });
  25346. Geometry.prototype.getScene = function () {
  25347. return this._scene;
  25348. };
  25349. Geometry.prototype.getEngine = function () {
  25350. return this._engine;
  25351. };
  25352. Geometry.prototype.isReady = function () {
  25353. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25354. };
  25355. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25356. vertexData.applyToGeometry(this, updatable);
  25357. this.notifyUpdate();
  25358. };
  25359. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25360. if (this._vertexBuffers[kind]) {
  25361. this._vertexBuffers[kind].dispose();
  25362. }
  25363. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25364. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25365. stride = this._vertexBuffers[kind].getStrideSize();
  25366. this._totalVertices = data.length / stride;
  25367. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25368. var meshes = this._meshes;
  25369. var numOfMeshes = meshes.length;
  25370. for (var index = 0; index < numOfMeshes; index++) {
  25371. var mesh = meshes[index];
  25372. mesh._resetPointsArrayCache();
  25373. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25374. mesh._createGlobalSubMesh();
  25375. mesh.computeWorldMatrix(true);
  25376. }
  25377. }
  25378. this.notifyUpdate(kind);
  25379. };
  25380. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25381. var vertexBuffer = this.getVertexBuffer(kind);
  25382. if (!vertexBuffer) {
  25383. return;
  25384. }
  25385. vertexBuffer.updateDirectly(data, offset);
  25386. this.notifyUpdate(kind);
  25387. };
  25388. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25389. var vertexBuffer = this.getVertexBuffer(kind);
  25390. if (!vertexBuffer) {
  25391. return;
  25392. }
  25393. vertexBuffer.update(data);
  25394. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25395. var stride = vertexBuffer.getStrideSize();
  25396. this._totalVertices = data.length / stride;
  25397. if (updateExtends) {
  25398. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25399. }
  25400. var meshes = this._meshes;
  25401. var numOfMeshes = meshes.length;
  25402. for (var index = 0; index < numOfMeshes; index++) {
  25403. var mesh = meshes[index];
  25404. mesh._resetPointsArrayCache();
  25405. if (updateExtends) {
  25406. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25407. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25408. var subMesh = mesh.subMeshes[subIndex];
  25409. subMesh.refreshBoundingInfo();
  25410. }
  25411. }
  25412. }
  25413. }
  25414. this.notifyUpdate(kind);
  25415. };
  25416. Geometry.prototype.getTotalVertices = function () {
  25417. if (!this.isReady()) {
  25418. return 0;
  25419. }
  25420. return this._totalVertices;
  25421. };
  25422. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25423. var vertexBuffer = this.getVertexBuffer(kind);
  25424. if (!vertexBuffer) {
  25425. return null;
  25426. }
  25427. var orig = vertexBuffer.getData();
  25428. if (!copyWhenShared || this._meshes.length === 1) {
  25429. return orig;
  25430. }
  25431. else {
  25432. var len = orig.length;
  25433. var copy = [];
  25434. for (var i = 0; i < len; i++) {
  25435. copy.push(orig[i]);
  25436. }
  25437. return copy;
  25438. }
  25439. };
  25440. Geometry.prototype.getVertexBuffer = function (kind) {
  25441. if (!this.isReady()) {
  25442. return null;
  25443. }
  25444. return this._vertexBuffers[kind];
  25445. };
  25446. Geometry.prototype.getVertexBuffers = function () {
  25447. if (!this.isReady()) {
  25448. return null;
  25449. }
  25450. return this._vertexBuffers;
  25451. };
  25452. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25453. if (!this._vertexBuffers) {
  25454. if (this._delayInfo) {
  25455. return this._delayInfo.indexOf(kind) !== -1;
  25456. }
  25457. return false;
  25458. }
  25459. return this._vertexBuffers[kind] !== undefined;
  25460. };
  25461. Geometry.prototype.getVerticesDataKinds = function () {
  25462. var result = [];
  25463. var kind;
  25464. if (!this._vertexBuffers && this._delayInfo) {
  25465. for (kind in this._delayInfo) {
  25466. result.push(kind);
  25467. }
  25468. }
  25469. else {
  25470. for (kind in this._vertexBuffers) {
  25471. result.push(kind);
  25472. }
  25473. }
  25474. return result;
  25475. };
  25476. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25477. if (this._indexBuffer) {
  25478. this._engine._releaseBuffer(this._indexBuffer);
  25479. }
  25480. this._indices = indices;
  25481. if (this._meshes.length !== 0 && this._indices) {
  25482. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25483. }
  25484. if (totalVertices !== undefined) {
  25485. this._totalVertices = totalVertices;
  25486. }
  25487. var meshes = this._meshes;
  25488. var numOfMeshes = meshes.length;
  25489. for (var index = 0; index < numOfMeshes; index++) {
  25490. meshes[index]._createGlobalSubMesh();
  25491. }
  25492. this.notifyUpdate();
  25493. };
  25494. Geometry.prototype.getTotalIndices = function () {
  25495. if (!this.isReady()) {
  25496. return 0;
  25497. }
  25498. return this._indices.length;
  25499. };
  25500. Geometry.prototype.getIndices = function (copyWhenShared) {
  25501. if (!this.isReady()) {
  25502. return null;
  25503. }
  25504. var orig = this._indices;
  25505. if (!copyWhenShared || this._meshes.length === 1) {
  25506. return orig;
  25507. }
  25508. else {
  25509. var len = orig.length;
  25510. var copy = [];
  25511. for (var i = 0; i < len; i++) {
  25512. copy.push(orig[i]);
  25513. }
  25514. return copy;
  25515. }
  25516. };
  25517. Geometry.prototype.getIndexBuffer = function () {
  25518. if (!this.isReady()) {
  25519. return null;
  25520. }
  25521. return this._indexBuffer;
  25522. };
  25523. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25524. var meshes = this._meshes;
  25525. var index = meshes.indexOf(mesh);
  25526. if (index === -1) {
  25527. return;
  25528. }
  25529. for (var kind in this._vertexBuffers) {
  25530. this._vertexBuffers[kind].dispose();
  25531. }
  25532. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25533. this._indexBuffer = null;
  25534. }
  25535. meshes.splice(index, 1);
  25536. mesh._geometry = null;
  25537. if (meshes.length === 0 && shouldDispose) {
  25538. this.dispose();
  25539. }
  25540. };
  25541. Geometry.prototype.applyToMesh = function (mesh) {
  25542. if (mesh._geometry === this) {
  25543. return;
  25544. }
  25545. var previousGeometry = mesh._geometry;
  25546. if (previousGeometry) {
  25547. previousGeometry.releaseForMesh(mesh);
  25548. }
  25549. var meshes = this._meshes;
  25550. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25551. mesh._geometry = this;
  25552. this._scene.pushGeometry(this);
  25553. meshes.push(mesh);
  25554. if (this.isReady()) {
  25555. this._applyToMesh(mesh);
  25556. }
  25557. else {
  25558. mesh._boundingInfo = this._boundingInfo;
  25559. }
  25560. };
  25561. Geometry.prototype._applyToMesh = function (mesh) {
  25562. var numOfMeshes = this._meshes.length;
  25563. // vertexBuffers
  25564. for (var kind in this._vertexBuffers) {
  25565. if (numOfMeshes === 1) {
  25566. this._vertexBuffers[kind].create();
  25567. }
  25568. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25569. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25570. mesh._resetPointsArrayCache();
  25571. if (!this._extend) {
  25572. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25573. }
  25574. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25575. mesh._createGlobalSubMesh();
  25576. //bounding info was just created again, world matrix should be applied again.
  25577. mesh._updateBoundingInfo();
  25578. }
  25579. }
  25580. // indexBuffer
  25581. if (numOfMeshes === 1 && this._indices) {
  25582. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25583. }
  25584. if (this._indexBuffer) {
  25585. this._indexBuffer.references = numOfMeshes;
  25586. }
  25587. };
  25588. Geometry.prototype.notifyUpdate = function (kind) {
  25589. if (this.onGeometryUpdated) {
  25590. this.onGeometryUpdated(this, kind);
  25591. }
  25592. };
  25593. Geometry.prototype.load = function (scene, onLoaded) {
  25594. var _this = this;
  25595. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25596. return;
  25597. }
  25598. if (this.isReady()) {
  25599. if (onLoaded) {
  25600. onLoaded();
  25601. }
  25602. return;
  25603. }
  25604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25605. scene._addPendingData(this);
  25606. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25607. _this._delayLoadingFunction(JSON.parse(data), _this);
  25608. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25609. _this._delayInfo = [];
  25610. scene._removePendingData(_this);
  25611. var meshes = _this._meshes;
  25612. var numOfMeshes = meshes.length;
  25613. for (var index = 0; index < numOfMeshes; index++) {
  25614. _this._applyToMesh(meshes[index]);
  25615. }
  25616. if (onLoaded) {
  25617. onLoaded();
  25618. }
  25619. }, function () { }, scene.database);
  25620. };
  25621. Geometry.prototype.isDisposed = function () {
  25622. return this._isDisposed;
  25623. };
  25624. Geometry.prototype.dispose = function () {
  25625. var meshes = this._meshes;
  25626. var numOfMeshes = meshes.length;
  25627. var index;
  25628. for (index = 0; index < numOfMeshes; index++) {
  25629. this.releaseForMesh(meshes[index]);
  25630. }
  25631. this._meshes = [];
  25632. for (var kind in this._vertexBuffers) {
  25633. this._vertexBuffers[kind].dispose();
  25634. }
  25635. this._vertexBuffers = [];
  25636. this._totalVertices = 0;
  25637. if (this._indexBuffer) {
  25638. this._engine._releaseBuffer(this._indexBuffer);
  25639. }
  25640. this._indexBuffer = null;
  25641. this._indices = [];
  25642. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25643. this.delayLoadingFile = null;
  25644. this._delayLoadingFunction = null;
  25645. this._delayInfo = [];
  25646. this._boundingInfo = null;
  25647. this._scene.removeGeometry(this);
  25648. this._isDisposed = true;
  25649. };
  25650. Geometry.prototype.copy = function (id) {
  25651. var vertexData = new BABYLON.VertexData();
  25652. vertexData.indices = [];
  25653. var indices = this.getIndices();
  25654. for (var index = 0; index < indices.length; index++) {
  25655. vertexData.indices.push(indices[index]);
  25656. }
  25657. var updatable = false;
  25658. var stopChecking = false;
  25659. var kind;
  25660. for (kind in this._vertexBuffers) {
  25661. // using slice() to make a copy of the array and not just reference it
  25662. var data = this.getVerticesData(kind);
  25663. if (data instanceof Float32Array) {
  25664. vertexData.set(new Float32Array(data), kind);
  25665. }
  25666. else {
  25667. vertexData.set(data.slice(0), kind);
  25668. }
  25669. if (!stopChecking) {
  25670. updatable = this.getVertexBuffer(kind).isUpdatable();
  25671. stopChecking = !updatable;
  25672. }
  25673. }
  25674. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25675. geometry.delayLoadState = this.delayLoadState;
  25676. geometry.delayLoadingFile = this.delayLoadingFile;
  25677. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25678. for (kind in this._delayInfo) {
  25679. geometry._delayInfo = geometry._delayInfo || [];
  25680. geometry._delayInfo.push(kind);
  25681. }
  25682. // Bounding info
  25683. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25684. return geometry;
  25685. };
  25686. // Statics
  25687. Geometry.ExtractFromMesh = function (mesh, id) {
  25688. var geometry = mesh._geometry;
  25689. if (!geometry) {
  25690. return null;
  25691. }
  25692. return geometry.copy(id);
  25693. };
  25694. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25695. // be aware Math.random() could cause collisions
  25696. Geometry.RandomId = function () {
  25697. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25698. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25699. return v.toString(16);
  25700. });
  25701. };
  25702. return Geometry;
  25703. })();
  25704. BABYLON.Geometry = Geometry;
  25705. /////// Primitives //////////////////////////////////////////////
  25706. var Geometry;
  25707. (function (Geometry) {
  25708. var Primitives;
  25709. (function (Primitives) {
  25710. /// Abstract class
  25711. var _Primitive = (function (_super) {
  25712. __extends(_Primitive, _super);
  25713. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25714. this._beingRegenerated = true;
  25715. this._canBeRegenerated = canBeRegenerated;
  25716. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25717. this._beingRegenerated = false;
  25718. }
  25719. _Primitive.prototype.canBeRegenerated = function () {
  25720. return this._canBeRegenerated;
  25721. };
  25722. _Primitive.prototype.regenerate = function () {
  25723. if (!this._canBeRegenerated) {
  25724. return;
  25725. }
  25726. this._beingRegenerated = true;
  25727. this.setAllVerticesData(this._regenerateVertexData(), false);
  25728. this._beingRegenerated = false;
  25729. };
  25730. _Primitive.prototype.asNewGeometry = function (id) {
  25731. return _super.prototype.copy.call(this, id);
  25732. };
  25733. // overrides
  25734. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25735. if (!this._beingRegenerated) {
  25736. return;
  25737. }
  25738. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25739. };
  25740. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25741. if (!this._beingRegenerated) {
  25742. return;
  25743. }
  25744. _super.prototype.setVerticesData.call(this, kind, data, false);
  25745. };
  25746. // to override
  25747. // protected
  25748. _Primitive.prototype._regenerateVertexData = function () {
  25749. throw new Error("Abstract method");
  25750. };
  25751. _Primitive.prototype.copy = function (id) {
  25752. throw new Error("Must be overriden in sub-classes.");
  25753. };
  25754. return _Primitive;
  25755. })(Geometry);
  25756. Primitives._Primitive = _Primitive;
  25757. var Ribbon = (function (_super) {
  25758. __extends(Ribbon, _super);
  25759. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25760. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25761. this.pathArray = pathArray;
  25762. this.closeArray = closeArray;
  25763. this.closePath = closePath;
  25764. this.offset = offset;
  25765. this.side = side;
  25766. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25767. }
  25768. Ribbon.prototype._regenerateVertexData = function () {
  25769. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  25770. };
  25771. Ribbon.prototype.copy = function (id) {
  25772. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25773. };
  25774. return Ribbon;
  25775. })(_Primitive);
  25776. Primitives.Ribbon = Ribbon;
  25777. var Box = (function (_super) {
  25778. __extends(Box, _super);
  25779. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25780. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25781. this.size = size;
  25782. this.side = side;
  25783. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25784. }
  25785. Box.prototype._regenerateVertexData = function () {
  25786. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  25787. };
  25788. Box.prototype.copy = function (id) {
  25789. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25790. };
  25791. return Box;
  25792. })(_Primitive);
  25793. Primitives.Box = Box;
  25794. var Sphere = (function (_super) {
  25795. __extends(Sphere, _super);
  25796. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25797. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25798. this.segments = segments;
  25799. this.diameter = diameter;
  25800. this.side = side;
  25801. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25802. }
  25803. Sphere.prototype._regenerateVertexData = function () {
  25804. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  25805. };
  25806. Sphere.prototype.copy = function (id) {
  25807. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25808. };
  25809. return Sphere;
  25810. })(_Primitive);
  25811. Primitives.Sphere = Sphere;
  25812. var Disc = (function (_super) {
  25813. __extends(Disc, _super);
  25814. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  25815. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25816. this.radius = radius;
  25817. this.tessellation = tessellation;
  25818. this.side = side;
  25819. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25820. }
  25821. Disc.prototype._regenerateVertexData = function () {
  25822. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  25823. };
  25824. Disc.prototype.copy = function (id) {
  25825. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  25826. };
  25827. return Disc;
  25828. })(_Primitive);
  25829. Primitives.Disc = Disc;
  25830. var Cylinder = (function (_super) {
  25831. __extends(Cylinder, _super);
  25832. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25833. if (subdivisions === void 0) { subdivisions = 1; }
  25834. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25835. this.height = height;
  25836. this.diameterTop = diameterTop;
  25837. this.diameterBottom = diameterBottom;
  25838. this.tessellation = tessellation;
  25839. this.subdivisions = subdivisions;
  25840. this.side = side;
  25841. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25842. }
  25843. Cylinder.prototype._regenerateVertexData = function () {
  25844. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  25845. };
  25846. Cylinder.prototype.copy = function (id) {
  25847. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25848. };
  25849. return Cylinder;
  25850. })(_Primitive);
  25851. Primitives.Cylinder = Cylinder;
  25852. var Torus = (function (_super) {
  25853. __extends(Torus, _super);
  25854. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25855. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25856. this.diameter = diameter;
  25857. this.thickness = thickness;
  25858. this.tessellation = tessellation;
  25859. this.side = side;
  25860. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25861. }
  25862. Torus.prototype._regenerateVertexData = function () {
  25863. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  25864. };
  25865. Torus.prototype.copy = function (id) {
  25866. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25867. };
  25868. return Torus;
  25869. })(_Primitive);
  25870. Primitives.Torus = Torus;
  25871. var Ground = (function (_super) {
  25872. __extends(Ground, _super);
  25873. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25874. this.width = width;
  25875. this.height = height;
  25876. this.subdivisions = subdivisions;
  25877. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25878. }
  25879. Ground.prototype._regenerateVertexData = function () {
  25880. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  25881. };
  25882. Ground.prototype.copy = function (id) {
  25883. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25884. };
  25885. return Ground;
  25886. })(_Primitive);
  25887. Primitives.Ground = Ground;
  25888. var TiledGround = (function (_super) {
  25889. __extends(TiledGround, _super);
  25890. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25891. this.xmin = xmin;
  25892. this.zmin = zmin;
  25893. this.xmax = xmax;
  25894. this.zmax = zmax;
  25895. this.subdivisions = subdivisions;
  25896. this.precision = precision;
  25897. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25898. }
  25899. TiledGround.prototype._regenerateVertexData = function () {
  25900. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  25901. };
  25902. TiledGround.prototype.copy = function (id) {
  25903. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25904. };
  25905. return TiledGround;
  25906. })(_Primitive);
  25907. Primitives.TiledGround = TiledGround;
  25908. var Plane = (function (_super) {
  25909. __extends(Plane, _super);
  25910. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25911. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25912. this.size = size;
  25913. this.side = side;
  25914. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25915. }
  25916. Plane.prototype._regenerateVertexData = function () {
  25917. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  25918. };
  25919. Plane.prototype.copy = function (id) {
  25920. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25921. };
  25922. return Plane;
  25923. })(_Primitive);
  25924. Primitives.Plane = Plane;
  25925. var TorusKnot = (function (_super) {
  25926. __extends(TorusKnot, _super);
  25927. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25928. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25929. this.radius = radius;
  25930. this.tube = tube;
  25931. this.radialSegments = radialSegments;
  25932. this.tubularSegments = tubularSegments;
  25933. this.p = p;
  25934. this.q = q;
  25935. this.side = side;
  25936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25937. }
  25938. TorusKnot.prototype._regenerateVertexData = function () {
  25939. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  25940. };
  25941. TorusKnot.prototype.copy = function (id) {
  25942. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25943. };
  25944. return TorusKnot;
  25945. })(_Primitive);
  25946. Primitives.TorusKnot = TorusKnot;
  25947. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25948. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25949. })(BABYLON || (BABYLON = {}));
  25950. var BABYLON;
  25951. (function (BABYLON) {
  25952. var GroundMesh = (function (_super) {
  25953. __extends(GroundMesh, _super);
  25954. function GroundMesh(name, scene) {
  25955. _super.call(this, name, scene);
  25956. this.generateOctree = false;
  25957. this._worldInverse = new BABYLON.Matrix();
  25958. }
  25959. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  25960. get: function () {
  25961. return this._subdivisions;
  25962. },
  25963. enumerable: true,
  25964. configurable: true
  25965. });
  25966. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  25967. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  25968. this._subdivisions = chunksCount;
  25969. this.subdivide(this._subdivisions);
  25970. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  25971. };
  25972. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  25973. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  25974. this.getWorldMatrix().invertToRef(this._worldInverse);
  25975. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  25976. var pickInfo = this.intersects(ray);
  25977. if (pickInfo.hit) {
  25978. return pickInfo.pickedPoint.y;
  25979. }
  25980. return 0;
  25981. };
  25982. return GroundMesh;
  25983. })(BABYLON.Mesh);
  25984. BABYLON.GroundMesh = GroundMesh;
  25985. })(BABYLON || (BABYLON = {}));
  25986. var BABYLON;
  25987. (function (BABYLON) {
  25988. var LinesMesh = (function (_super) {
  25989. __extends(LinesMesh, _super);
  25990. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  25991. if (parent === void 0) { parent = null; }
  25992. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  25993. this.color = new BABYLON.Color3(1, 1, 1);
  25994. this.alpha = 1;
  25995. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25996. attributes: ["position"],
  25997. uniforms: ["worldViewProjection", "color"],
  25998. needAlphaBlending: true
  25999. });
  26000. }
  26001. Object.defineProperty(LinesMesh.prototype, "material", {
  26002. get: function () {
  26003. return this._colorShader;
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26009. get: function () {
  26010. return false;
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26016. get: function () {
  26017. return false;
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26023. var engine = this.getScene().getEngine();
  26024. var indexToBind = this._geometry.getIndexBuffer();
  26025. // VBOs
  26026. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26027. // Color
  26028. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26029. };
  26030. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26031. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26032. return;
  26033. }
  26034. var engine = this.getScene().getEngine();
  26035. // Draw order
  26036. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26037. };
  26038. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26039. return null;
  26040. };
  26041. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26042. this._colorShader.dispose();
  26043. _super.prototype.dispose.call(this, doNotRecurse);
  26044. };
  26045. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26046. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26047. };
  26048. return LinesMesh;
  26049. })(BABYLON.Mesh);
  26050. BABYLON.LinesMesh = LinesMesh;
  26051. })(BABYLON || (BABYLON = {}));
  26052. var BABYLON;
  26053. (function (BABYLON) {
  26054. var DebugLayer = (function () {
  26055. function DebugLayer(scene) {
  26056. var _this = this;
  26057. this._transformationMatrix = BABYLON.Matrix.Identity();
  26058. this._enabled = false;
  26059. this._labelsEnabled = false;
  26060. this._displayStatistics = true;
  26061. this._displayTree = false;
  26062. this._displayLogs = false;
  26063. this._identityMatrix = BABYLON.Matrix.Identity();
  26064. this.axisRatio = 0.02;
  26065. this.accentColor = "orange";
  26066. this._scene = scene;
  26067. this._syncPositions = function () {
  26068. var engine = _this._scene.getEngine();
  26069. var canvasRect = engine.getRenderingCanvasClientRect();
  26070. if (_this._showUI) {
  26071. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26072. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26073. _this._statsDiv.style.width = "400px";
  26074. _this._statsDiv.style.height = "auto";
  26075. _this._statsSubsetDiv.style.maxHeight = "240px";
  26076. _this._optionsDiv.style.left = "0px";
  26077. _this._optionsDiv.style.top = "10px";
  26078. _this._optionsDiv.style.width = "200px";
  26079. _this._optionsDiv.style.height = "auto";
  26080. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26081. _this._logDiv.style.left = "0px";
  26082. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26083. _this._logDiv.style.width = "600px";
  26084. _this._logDiv.style.height = "160px";
  26085. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26086. _this._treeDiv.style.top = "10px";
  26087. _this._treeDiv.style.width = "300px";
  26088. _this._treeDiv.style.height = "auto";
  26089. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26090. }
  26091. _this._globalDiv.style.left = canvasRect.left + "px";
  26092. _this._globalDiv.style.top = canvasRect.top + "px";
  26093. _this._drawingCanvas.style.left = "0px";
  26094. _this._drawingCanvas.style.top = "0px";
  26095. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26096. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26097. var devicePixelRatio = window.devicePixelRatio || 1;
  26098. var context = _this._drawingContext;
  26099. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26100. context.mozBackingStorePixelRatio ||
  26101. context.msBackingStorePixelRatio ||
  26102. context.oBackingStorePixelRatio ||
  26103. context.backingStorePixelRatio || 1;
  26104. _this._ratio = devicePixelRatio / backingStoreRatio;
  26105. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26106. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26107. };
  26108. this._onCanvasClick = function (evt) {
  26109. _this._clickPosition = {
  26110. x: evt.clientX * _this._ratio,
  26111. y: evt.clientY * _this._ratio
  26112. };
  26113. };
  26114. this._syncUI = function () {
  26115. if (_this._showUI) {
  26116. if (_this._displayStatistics) {
  26117. _this._displayStats();
  26118. _this._statsDiv.style.display = "";
  26119. }
  26120. else {
  26121. _this._statsDiv.style.display = "none";
  26122. }
  26123. if (_this._displayLogs) {
  26124. _this._logDiv.style.display = "";
  26125. }
  26126. else {
  26127. _this._logDiv.style.display = "none";
  26128. }
  26129. if (_this._displayTree) {
  26130. _this._treeDiv.style.display = "";
  26131. if (_this._needToRefreshMeshesTree) {
  26132. _this._needToRefreshMeshesTree = false;
  26133. _this._refreshMeshesTreeContent();
  26134. }
  26135. }
  26136. else {
  26137. _this._treeDiv.style.display = "none";
  26138. }
  26139. }
  26140. };
  26141. this._syncData = function () {
  26142. if (_this._labelsEnabled || !_this._showUI) {
  26143. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26144. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26145. var engine = _this._scene.getEngine();
  26146. var viewport = _this._camera.viewport;
  26147. var globalViewport = viewport.toGlobal(engine);
  26148. // Meshes
  26149. var meshes = _this._camera.getActiveMeshes();
  26150. for (var index = 0; index < meshes.length; index++) {
  26151. var mesh = meshes.data[index];
  26152. var position = mesh.getBoundingInfo().boundingSphere.center;
  26153. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26154. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26155. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26156. }
  26157. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26158. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26159. }
  26160. }
  26161. // Cameras
  26162. var cameras = _this._scene.cameras;
  26163. for (index = 0; index < cameras.length; index++) {
  26164. var camera = cameras[index];
  26165. if (camera === _this._camera) {
  26166. continue;
  26167. }
  26168. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26169. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26170. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26171. _this._camera.detachControl(engine.getRenderingCanvas());
  26172. _this._camera = camera;
  26173. _this._camera.attachControl(engine.getRenderingCanvas());
  26174. }, function () { return "purple"; });
  26175. }
  26176. }
  26177. // Lights
  26178. var lights = _this._scene.lights;
  26179. for (index = 0; index < lights.length; index++) {
  26180. var light = lights[index];
  26181. if (light.position) {
  26182. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26183. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26184. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26185. light.setEnabled(!light.isEnabled());
  26186. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26187. }
  26188. }
  26189. }
  26190. }
  26191. _this._clickPosition = undefined;
  26192. };
  26193. }
  26194. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26195. while (this._treeSubsetDiv.hasChildNodes()) {
  26196. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26197. }
  26198. // Add meshes
  26199. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26200. sortedArray.sort(function (a, b) {
  26201. if (a.name === b.name) {
  26202. return 0;
  26203. }
  26204. return (a.name > b.name) ? 1 : -1;
  26205. });
  26206. for (var index = 0; index < sortedArray.length; index++) {
  26207. var mesh = sortedArray[index];
  26208. if (!mesh.isEnabled()) {
  26209. continue;
  26210. }
  26211. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26212. m.isVisible = element.checked;
  26213. }, mesh);
  26214. }
  26215. };
  26216. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26217. this._drawingContext.beginPath();
  26218. this._drawingContext.moveTo(zero.x, zero.y);
  26219. this._drawingContext.lineTo(unit.x, unit.y);
  26220. this._drawingContext.strokeStyle = color;
  26221. this._drawingContext.lineWidth = 4;
  26222. this._drawingContext.stroke();
  26223. this._drawingContext.font = "normal 14px Segoe UI";
  26224. this._drawingContext.fillStyle = color;
  26225. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26226. };
  26227. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26228. var position = mesh.getBoundingInfo().boundingSphere.center;
  26229. var worldMatrix = mesh.getWorldMatrix();
  26230. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26231. var unit = (unprojectedVector.subtract(position)).length();
  26232. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26233. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26234. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26235. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26236. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26237. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26238. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26239. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26240. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26241. };
  26242. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26243. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26244. this._drawingContext.font = "normal 12px Segoe UI";
  26245. var textMetrics = this._drawingContext.measureText(text);
  26246. var centerX = projectedPosition.x - textMetrics.width / 2;
  26247. var centerY = projectedPosition.y;
  26248. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26249. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26250. onClick();
  26251. }
  26252. this._drawingContext.beginPath();
  26253. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26254. this._drawingContext.fillStyle = getFillStyle();
  26255. this._drawingContext.globalAlpha = 0.5;
  26256. this._drawingContext.fill();
  26257. this._drawingContext.globalAlpha = 1.0;
  26258. this._drawingContext.strokeStyle = '#FFFFFF';
  26259. this._drawingContext.lineWidth = 1;
  26260. this._drawingContext.stroke();
  26261. this._drawingContext.fillStyle = "#FFFFFF";
  26262. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26263. this._drawingContext.beginPath();
  26264. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26265. this._drawingContext.fill();
  26266. }
  26267. };
  26268. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26269. if (!this._clickPosition) {
  26270. return false;
  26271. }
  26272. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26273. return false;
  26274. }
  26275. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26276. return false;
  26277. }
  26278. return true;
  26279. };
  26280. DebugLayer.prototype.isVisible = function () {
  26281. return this._enabled;
  26282. };
  26283. DebugLayer.prototype.hide = function () {
  26284. if (!this._enabled) {
  26285. return;
  26286. }
  26287. this._enabled = false;
  26288. var engine = this._scene.getEngine();
  26289. this._scene.unregisterBeforeRender(this._syncData);
  26290. this._scene.unregisterAfterRender(this._syncUI);
  26291. this._rootElement.removeChild(this._globalDiv);
  26292. window.removeEventListener("resize", this._syncPositions);
  26293. this._scene.forceShowBoundingBoxes = false;
  26294. this._scene.forceWireframe = false;
  26295. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26296. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26297. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26298. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26299. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26300. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26301. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26302. BABYLON.StandardMaterial.LightmapEnabled = true;
  26303. this._scene.shadowsEnabled = true;
  26304. this._scene.particlesEnabled = true;
  26305. this._scene.postProcessesEnabled = true;
  26306. this._scene.collisionsEnabled = true;
  26307. this._scene.lightsEnabled = true;
  26308. this._scene.texturesEnabled = true;
  26309. this._scene.lensFlaresEnabled = true;
  26310. this._scene.proceduralTexturesEnabled = true;
  26311. this._scene.renderTargetsEnabled = true;
  26312. this._scene.probesEnabled = true;
  26313. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26314. };
  26315. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26316. if (showUI === void 0) { showUI = true; }
  26317. if (camera === void 0) { camera = null; }
  26318. if (rootElement === void 0) { rootElement = null; }
  26319. if (this._enabled) {
  26320. return;
  26321. }
  26322. this._enabled = true;
  26323. if (camera) {
  26324. this._camera = camera;
  26325. }
  26326. else {
  26327. this._camera = this._scene.activeCamera;
  26328. }
  26329. this._showUI = showUI;
  26330. var engine = this._scene.getEngine();
  26331. this._globalDiv = document.createElement("div");
  26332. this._rootElement = rootElement || document.body;
  26333. this._rootElement.appendChild(this._globalDiv);
  26334. this._generateDOMelements();
  26335. window.addEventListener("resize", this._syncPositions);
  26336. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26337. this._syncPositions();
  26338. this._scene.registerBeforeRender(this._syncData);
  26339. this._scene.registerAfterRender(this._syncUI);
  26340. };
  26341. DebugLayer.prototype._clearLabels = function () {
  26342. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26343. for (var index = 0; index < this._scene.meshes.length; index++) {
  26344. var mesh = this._scene.meshes[index];
  26345. mesh.renderOverlay = false;
  26346. }
  26347. };
  26348. DebugLayer.prototype._generateheader = function (root, text) {
  26349. var header = document.createElement("div");
  26350. header.innerHTML = text + "&nbsp;";
  26351. header.style.textAlign = "right";
  26352. header.style.width = "100%";
  26353. header.style.color = "white";
  26354. header.style.backgroundColor = "Black";
  26355. header.style.padding = "5px 5px 4px 0px";
  26356. header.style.marginLeft = "-5px";
  26357. header.style.fontWeight = "bold";
  26358. root.appendChild(header);
  26359. };
  26360. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26361. var label = document.createElement("label");
  26362. label.innerHTML = title;
  26363. label.style.color = color;
  26364. root.appendChild(label);
  26365. root.appendChild(document.createElement("br"));
  26366. };
  26367. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26368. if (tag === void 0) { tag = null; }
  26369. var label = document.createElement("label");
  26370. var boundingBoxesCheckbox = document.createElement("input");
  26371. boundingBoxesCheckbox.type = "checkbox";
  26372. boundingBoxesCheckbox.checked = initialState;
  26373. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26374. task(evt.target, tag);
  26375. });
  26376. label.appendChild(boundingBoxesCheckbox);
  26377. var container = document.createElement("span");
  26378. var leftPart = document.createElement("span");
  26379. var rightPart = document.createElement("span");
  26380. rightPart.style.cssFloat = "right";
  26381. leftPart.innerHTML = leftTitle;
  26382. rightPart.innerHTML = rightTitle;
  26383. rightPart.style.fontSize = "12px";
  26384. rightPart.style.maxWidth = "200px";
  26385. container.appendChild(leftPart);
  26386. container.appendChild(rightPart);
  26387. label.appendChild(container);
  26388. root.appendChild(label);
  26389. root.appendChild(document.createElement("br"));
  26390. };
  26391. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26392. if (tag === void 0) { tag = null; }
  26393. var label = document.createElement("label");
  26394. var checkBox = document.createElement("input");
  26395. checkBox.type = "checkbox";
  26396. checkBox.checked = initialState;
  26397. checkBox.addEventListener("change", function (evt) {
  26398. task(evt.target, tag);
  26399. });
  26400. label.appendChild(checkBox);
  26401. label.appendChild(document.createTextNode(title));
  26402. root.appendChild(label);
  26403. root.appendChild(document.createElement("br"));
  26404. };
  26405. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26406. if (tag === void 0) { tag = null; }
  26407. var button = document.createElement("button");
  26408. button.innerHTML = title;
  26409. button.style.height = "24px";
  26410. button.style.color = "#444444";
  26411. button.style.border = "1px solid white";
  26412. button.className = "debugLayerButton";
  26413. button.addEventListener("click", function (evt) {
  26414. task(evt.target, tag);
  26415. });
  26416. root.appendChild(button);
  26417. root.appendChild(document.createElement("br"));
  26418. };
  26419. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26420. if (tag === void 0) { tag = null; }
  26421. var label = document.createElement("label");
  26422. var boundingBoxesRadio = document.createElement("input");
  26423. boundingBoxesRadio.type = "radio";
  26424. boundingBoxesRadio.name = name;
  26425. boundingBoxesRadio.checked = initialState;
  26426. boundingBoxesRadio.addEventListener("change", function (evt) {
  26427. task(evt.target, tag);
  26428. });
  26429. label.appendChild(boundingBoxesRadio);
  26430. label.appendChild(document.createTextNode(title));
  26431. root.appendChild(label);
  26432. root.appendChild(document.createElement("br"));
  26433. };
  26434. DebugLayer.prototype._generateDOMelements = function () {
  26435. var _this = this;
  26436. this._globalDiv.id = "DebugLayer";
  26437. this._globalDiv.style.position = "absolute";
  26438. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26439. this._globalDiv.style.fontSize = "14px";
  26440. this._globalDiv.style.color = "white";
  26441. // Drawing canvas
  26442. this._drawingCanvas = document.createElement("canvas");
  26443. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26444. this._drawingCanvas.style.position = "absolute";
  26445. this._drawingCanvas.style.pointerEvents = "none";
  26446. this._drawingCanvas.style.backgroundColor = "transparent";
  26447. this._drawingContext = this._drawingCanvas.getContext("2d");
  26448. this._globalDiv.appendChild(this._drawingCanvas);
  26449. if (this._showUI) {
  26450. var background = "rgba(128, 128, 128, 0.4)";
  26451. var border = "rgb(180, 180, 180) solid 1px";
  26452. // Stats
  26453. this._statsDiv = document.createElement("div");
  26454. this._statsDiv.id = "DebugLayerStats";
  26455. this._statsDiv.style.border = border;
  26456. this._statsDiv.style.position = "absolute";
  26457. this._statsDiv.style.background = background;
  26458. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26459. this._generateheader(this._statsDiv, "STATISTICS");
  26460. this._statsSubsetDiv = document.createElement("div");
  26461. this._statsSubsetDiv.style.paddingTop = "5px";
  26462. this._statsSubsetDiv.style.paddingBottom = "5px";
  26463. this._statsSubsetDiv.style.overflowY = "auto";
  26464. this._statsDiv.appendChild(this._statsSubsetDiv);
  26465. // Tree
  26466. this._treeDiv = document.createElement("div");
  26467. this._treeDiv.id = "DebugLayerTree";
  26468. this._treeDiv.style.border = border;
  26469. this._treeDiv.style.position = "absolute";
  26470. this._treeDiv.style.background = background;
  26471. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26472. this._treeDiv.style.display = "none";
  26473. this._generateheader(this._treeDiv, "MESHES TREE");
  26474. this._treeSubsetDiv = document.createElement("div");
  26475. this._treeSubsetDiv.style.paddingTop = "5px";
  26476. this._treeSubsetDiv.style.paddingRight = "5px";
  26477. this._treeSubsetDiv.style.overflowY = "auto";
  26478. this._treeSubsetDiv.style.maxHeight = "300px";
  26479. this._treeDiv.appendChild(this._treeSubsetDiv);
  26480. this._needToRefreshMeshesTree = true;
  26481. // Logs
  26482. this._logDiv = document.createElement("div");
  26483. this._logDiv.style.border = border;
  26484. this._logDiv.id = "DebugLayerLogs";
  26485. this._logDiv.style.position = "absolute";
  26486. this._logDiv.style.background = background;
  26487. this._logDiv.style.padding = "0px 0px 0px 5px";
  26488. this._logDiv.style.display = "none";
  26489. this._generateheader(this._logDiv, "LOGS");
  26490. this._logSubsetDiv = document.createElement("div");
  26491. this._logSubsetDiv.style.height = "127px";
  26492. this._logSubsetDiv.style.paddingTop = "5px";
  26493. this._logSubsetDiv.style.overflowY = "auto";
  26494. this._logSubsetDiv.style.fontSize = "12px";
  26495. this._logSubsetDiv.style.fontFamily = "consolas";
  26496. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26497. this._logDiv.appendChild(this._logSubsetDiv);
  26498. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26499. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26500. };
  26501. // Options
  26502. this._optionsDiv = document.createElement("div");
  26503. this._optionsDiv.id = "DebugLayerOptions";
  26504. this._optionsDiv.style.border = border;
  26505. this._optionsDiv.style.position = "absolute";
  26506. this._optionsDiv.style.background = background;
  26507. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26508. this._optionsDiv.style.overflowY = "auto";
  26509. this._generateheader(this._optionsDiv, "OPTIONS");
  26510. this._optionsSubsetDiv = document.createElement("div");
  26511. this._optionsSubsetDiv.style.paddingTop = "5px";
  26512. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26513. this._optionsSubsetDiv.style.overflowY = "auto";
  26514. this._optionsSubsetDiv.style.maxHeight = "200px";
  26515. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26516. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26517. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  26518. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  26519. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26520. _this._displayTree = element.checked;
  26521. _this._needToRefreshMeshesTree = true;
  26522. });
  26523. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26524. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26525. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  26526. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26527. _this._labelsEnabled = element.checked;
  26528. if (!_this._labelsEnabled) {
  26529. _this._clearLabels();
  26530. }
  26531. });
  26532. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26533. if (element.checked) {
  26534. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26535. }
  26536. else {
  26537. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26538. }
  26539. });
  26540. ;
  26541. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26542. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26543. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26544. if (element.checked) {
  26545. _this._scene.forceWireframe = false;
  26546. _this._scene.forcePointsCloud = false;
  26547. }
  26548. });
  26549. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26550. if (element.checked) {
  26551. _this._scene.forceWireframe = true;
  26552. _this._scene.forcePointsCloud = false;
  26553. }
  26554. });
  26555. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26556. if (element.checked) {
  26557. _this._scene.forceWireframe = false;
  26558. _this._scene.forcePointsCloud = true;
  26559. }
  26560. });
  26561. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26562. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26563. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  26564. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  26565. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  26566. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  26567. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  26568. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  26569. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  26570. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  26571. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  26572. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26573. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26574. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  26575. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  26576. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  26577. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  26578. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  26579. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  26580. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  26581. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  26582. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  26583. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  26584. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  26585. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  26586. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  26587. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  26588. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  26589. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26590. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  26591. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  26592. if (element.checked) {
  26593. _this._scene.headphone = true;
  26594. }
  26595. });
  26596. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  26597. if (element.checked) {
  26598. _this._scene.headphone = false;
  26599. }
  26600. });
  26601. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  26602. _this._scene.audioEnabled = !element.checked;
  26603. });
  26604. }
  26605. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26606. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  26607. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  26608. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26609. this._globalDiv.appendChild(this._statsDiv);
  26610. this._globalDiv.appendChild(this._logDiv);
  26611. this._globalDiv.appendChild(this._optionsDiv);
  26612. this._globalDiv.appendChild(this._treeDiv);
  26613. }
  26614. };
  26615. DebugLayer.prototype._displayStats = function () {
  26616. var scene = this._scene;
  26617. var engine = scene.getEngine();
  26618. var glInfo = engine.getGlInfo();
  26619. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  26620. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26621. + "<b>Count</b><br>"
  26622. + "Total meshes: " + scene.meshes.length + "<br>"
  26623. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  26624. + "Total materials: " + scene.materials.length + "<br>"
  26625. + "Total textures: " + scene.textures.length + "<br>"
  26626. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  26627. + "Active indices: " + scene.getActiveIndices() + "<br>"
  26628. + "Active bones: " + scene.getActiveBones() + "<br>"
  26629. + "Active particles: " + scene.getActiveParticles() + "<br>"
  26630. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  26631. + "<b>Duration</b><br>"
  26632. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  26633. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  26634. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  26635. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  26636. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  26637. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  26638. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  26639. + "</div>"
  26640. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26641. + "<b>Extensions</b><br>"
  26642. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  26643. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  26644. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  26645. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  26646. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  26647. + "<b>Caps.</b><br>"
  26648. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  26649. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  26650. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  26651. + "</div><br>"
  26652. + "<b>Info</b><br>"
  26653. + glInfo.version + "<br>"
  26654. + glInfo.renderer + "<br>";
  26655. if (this.customStatsFunction) {
  26656. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26657. }
  26658. };
  26659. return DebugLayer;
  26660. })();
  26661. BABYLON.DebugLayer = DebugLayer;
  26662. })(BABYLON || (BABYLON = {}));
  26663. var BABYLON;
  26664. (function (BABYLON) {
  26665. var DefaultLoadingScreen = (function () {
  26666. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  26667. var _this = this;
  26668. if (_loadingText === void 0) { _loadingText = ""; }
  26669. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  26670. this._renderingCanvas = _renderingCanvas;
  26671. this._loadingText = _loadingText;
  26672. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  26673. // Resize
  26674. this._resizeLoadingUI = function () {
  26675. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  26676. _this._loadingDiv.style.position = "absolute";
  26677. _this._loadingDiv.style.left = canvasRect.left + "px";
  26678. _this._loadingDiv.style.top = canvasRect.top + "px";
  26679. _this._loadingDiv.style.width = canvasRect.width + "px";
  26680. _this._loadingDiv.style.height = canvasRect.height + "px";
  26681. };
  26682. }
  26683. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  26684. var _this = this;
  26685. this._loadingDiv = document.createElement("div");
  26686. this._loadingDiv.style.opacity = "0";
  26687. this._loadingDiv.style.transition = "opacity 1.5s ease";
  26688. // Loading text
  26689. this._loadingTextDiv = document.createElement("div");
  26690. this._loadingTextDiv.style.position = "absolute";
  26691. this._loadingTextDiv.style.left = "0";
  26692. this._loadingTextDiv.style.top = "50%";
  26693. this._loadingTextDiv.style.marginTop = "80px";
  26694. this._loadingTextDiv.style.width = "100%";
  26695. this._loadingTextDiv.style.height = "20px";
  26696. this._loadingTextDiv.style.fontFamily = "Arial";
  26697. this._loadingTextDiv.style.fontSize = "14px";
  26698. this._loadingTextDiv.style.color = "white";
  26699. this._loadingTextDiv.style.textAlign = "center";
  26700. this._loadingTextDiv.innerHTML = "Loading";
  26701. this._loadingDiv.appendChild(this._loadingTextDiv);
  26702. //set the predefined text
  26703. this._loadingTextDiv.innerHTML = this._loadingText;
  26704. // Loading img
  26705. var imgBack = new Image();
  26706. 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==";
  26707. imgBack.style.position = "absolute";
  26708. imgBack.style.left = "50%";
  26709. imgBack.style.top = "50%";
  26710. imgBack.style.marginLeft = "-50px";
  26711. imgBack.style.marginTop = "-50px";
  26712. imgBack.style.transition = "transform 1.0s ease";
  26713. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  26714. var deg = 360;
  26715. var onTransitionEnd = function () {
  26716. deg += 360;
  26717. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  26718. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  26719. };
  26720. imgBack.addEventListener("transitionend", onTransitionEnd);
  26721. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  26722. this._loadingDiv.appendChild(imgBack);
  26723. // front image
  26724. var imgFront = new Image();
  26725. 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=";
  26726. imgFront.style.position = "absolute";
  26727. imgFront.style.left = "50%";
  26728. imgFront.style.top = "50%";
  26729. imgFront.style.marginLeft = "-50px";
  26730. imgFront.style.marginTop = "-50px";
  26731. this._loadingDiv.appendChild(imgFront);
  26732. this._resizeLoadingUI();
  26733. window.addEventListener("resize", this._resizeLoadingUI);
  26734. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26735. document.body.appendChild(this._loadingDiv);
  26736. setTimeout(function () {
  26737. _this._loadingDiv.style.opacity = "1";
  26738. imgBack.style.transform = "rotateZ(360deg)";
  26739. imgBack.style.webkitTransform = "rotateZ(360deg)";
  26740. }, 0);
  26741. };
  26742. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  26743. var _this = this;
  26744. if (!this._loadingDiv) {
  26745. return;
  26746. }
  26747. var onTransitionEnd = function () {
  26748. if (!_this._loadingDiv) {
  26749. return;
  26750. }
  26751. document.body.removeChild(_this._loadingDiv);
  26752. window.removeEventListener("resize", _this._resizeLoadingUI);
  26753. _this._loadingDiv = null;
  26754. };
  26755. this._loadingDiv.style.opacity = "0";
  26756. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  26757. };
  26758. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  26759. set: function (text) {
  26760. this._loadingText = text;
  26761. if (this._loadingTextDiv) {
  26762. this._loadingTextDiv.innerHTML = this._loadingText;
  26763. }
  26764. },
  26765. enumerable: true,
  26766. configurable: true
  26767. });
  26768. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  26769. get: function () {
  26770. return this._loadingDivBackgroundColor;
  26771. },
  26772. set: function (color) {
  26773. this._loadingDivBackgroundColor = color;
  26774. if (!this._loadingDiv) {
  26775. return;
  26776. }
  26777. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26778. },
  26779. enumerable: true,
  26780. configurable: true
  26781. });
  26782. return DefaultLoadingScreen;
  26783. })();
  26784. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  26785. })(BABYLON || (BABYLON = {}));
  26786. var BABYLON;
  26787. (function (BABYLON) {
  26788. var SIMDVector3 = (function () {
  26789. function SIMDVector3() {
  26790. }
  26791. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  26792. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  26793. var m0 = SIMD.float32x4.load(transformation.m, 0);
  26794. var m1 = SIMD.float32x4.load(transformation.m, 4);
  26795. var m2 = SIMD.float32x4.load(transformation.m, 8);
  26796. var m3 = SIMD.float32x4.load(transformation.m, 12);
  26797. 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));
  26798. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  26799. SIMD.float32x4.storeXYZ(result._data, 0, r);
  26800. };
  26801. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  26802. var v0 = SIMD.float32x4.splat(x);
  26803. var v1 = SIMD.float32x4.splat(y);
  26804. var v2 = SIMD.float32x4.splat(z);
  26805. var m0 = SIMD.float32x4.load(transformation.m, 0);
  26806. var m1 = SIMD.float32x4.load(transformation.m, 4);
  26807. var m2 = SIMD.float32x4.load(transformation.m, 8);
  26808. var m3 = SIMD.float32x4.load(transformation.m, 12);
  26809. 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));
  26810. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  26811. SIMD.float32x4.storeXYZ(result._data, 0, r);
  26812. };
  26813. return SIMDVector3;
  26814. })();
  26815. BABYLON.SIMDVector3 = SIMDVector3;
  26816. var SIMDMatrix = (function () {
  26817. function SIMDMatrix() {
  26818. }
  26819. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  26820. if (offset === void 0) { offset = 0; }
  26821. var tm = this.m;
  26822. var om = other.m;
  26823. var om0 = SIMD.float32x4.load(om, 0);
  26824. var om1 = SIMD.float32x4.load(om, 4);
  26825. var om2 = SIMD.float32x4.load(om, 8);
  26826. var om3 = SIMD.float32x4.load(om, 12);
  26827. var tm0 = SIMD.float32x4.load(tm, 0);
  26828. 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)))));
  26829. var tm1 = SIMD.float32x4.load(tm, 4);
  26830. 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)))));
  26831. var tm2 = SIMD.float32x4.load(tm, 8);
  26832. 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)))));
  26833. var tm3 = SIMD.float32x4.load(tm, 12);
  26834. 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)))));
  26835. };
  26836. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  26837. var src = this.m;
  26838. var dest = other.m;
  26839. var row0, row1, row2, row3;
  26840. var tmp1;
  26841. var minor0, minor1, minor2, minor3;
  26842. var det;
  26843. // Load the 4 rows
  26844. var src0 = SIMD.float32x4.load(src, 0);
  26845. var src1 = SIMD.float32x4.load(src, 4);
  26846. var src2 = SIMD.float32x4.load(src, 8);
  26847. var src3 = SIMD.float32x4.load(src, 12);
  26848. // Transpose the source matrix. Sort of. Not a true transpose operation
  26849. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  26850. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  26851. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  26852. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  26853. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  26854. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  26855. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  26856. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  26857. // This is a true transposition, but it will lead to an incorrect result
  26858. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  26859. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  26860. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  26861. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  26862. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  26863. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  26864. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  26865. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  26866. // ----
  26867. tmp1 = SIMD.float32x4.mul(row2, row3);
  26868. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26869. minor0 = SIMD.float32x4.mul(row1, tmp1);
  26870. minor1 = SIMD.float32x4.mul(row0, tmp1);
  26871. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26872. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  26873. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  26874. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  26875. // ----
  26876. tmp1 = SIMD.float32x4.mul(row1, row2);
  26877. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26878. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  26879. minor3 = SIMD.float32x4.mul(row0, tmp1);
  26880. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26881. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  26882. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  26883. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  26884. // ----
  26885. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  26886. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26887. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  26888. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  26889. minor2 = SIMD.float32x4.mul(row0, tmp1);
  26890. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26891. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  26892. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  26893. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  26894. // ----
  26895. tmp1 = SIMD.float32x4.mul(row0, row1);
  26896. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26897. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  26898. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  26899. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26900. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  26901. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  26902. // ----
  26903. tmp1 = SIMD.float32x4.mul(row0, row3);
  26904. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26905. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  26906. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  26907. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26908. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  26909. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  26910. // ----
  26911. tmp1 = SIMD.float32x4.mul(row0, row2);
  26912. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26913. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  26914. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  26915. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26916. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  26917. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  26918. // Compute determinant
  26919. det = SIMD.float32x4.mul(row0, minor0);
  26920. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  26921. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  26922. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  26923. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  26924. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  26925. // These shuffles aren't necessary if the faulty transposition is done
  26926. // up at the top of this function.
  26927. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  26928. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  26929. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  26930. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  26931. // Compute final values by multiplying with 1/det
  26932. minor0 = SIMD.float32x4.mul(det, minor0);
  26933. minor1 = SIMD.float32x4.mul(det, minor1);
  26934. minor2 = SIMD.float32x4.mul(det, minor2);
  26935. minor3 = SIMD.float32x4.mul(det, minor3);
  26936. SIMD.float32x4.store(dest, 0, minor0);
  26937. SIMD.float32x4.store(dest, 4, minor1);
  26938. SIMD.float32x4.store(dest, 8, minor2);
  26939. SIMD.float32x4.store(dest, 12, minor3);
  26940. return this;
  26941. };
  26942. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  26943. var out = result.m;
  26944. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  26945. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  26946. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  26947. // cc.kmVec3Subtract(f, pCenter, pEye);
  26948. var f = SIMD.float32x4.sub(center, eye);
  26949. // cc.kmVec3Normalize(f, f);
  26950. var tmp = SIMD.float32x4.mul(f, f);
  26951. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  26952. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  26953. // cc.kmVec3Assign(up, pUp);
  26954. // cc.kmVec3Normalize(up, up);
  26955. tmp = SIMD.float32x4.mul(up, up);
  26956. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  26957. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  26958. // cc.kmVec3Cross(s, f, up);
  26959. 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)));
  26960. // cc.kmVec3Normalize(s, s);
  26961. tmp = SIMD.float32x4.mul(s, s);
  26962. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  26963. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  26964. // cc.kmVec3Cross(u, s, f);
  26965. 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)));
  26966. // cc.kmVec3Normalize(s, s);
  26967. tmp = SIMD.float32x4.mul(s, s);
  26968. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  26969. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  26970. var zero = SIMD.float32x4.splat(0.0);
  26971. s = SIMD.float32x4.neg(s);
  26972. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  26973. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  26974. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  26975. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  26976. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  26977. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  26978. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  26979. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  26980. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  26981. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  26982. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  26983. var b3 = SIMD.float32x4.neg(eye);
  26984. b3 = SIMD.float32x4.withW(b3, 1.0);
  26985. 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)))));
  26986. 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)))));
  26987. 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)))));
  26988. 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)))));
  26989. };
  26990. return SIMDMatrix;
  26991. })();
  26992. BABYLON.SIMDMatrix = SIMDMatrix;
  26993. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  26994. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  26995. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  26996. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  26997. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  26998. var SIMDHelper = (function () {
  26999. function SIMDHelper() {
  27000. }
  27001. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27002. get: function () {
  27003. return SIMDHelper._isEnabled;
  27004. },
  27005. enumerable: true,
  27006. configurable: true
  27007. });
  27008. SIMDHelper.DisableSIMD = function () {
  27009. // Replace functions
  27010. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27011. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27012. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27013. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27014. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27015. SIMDHelper._isEnabled = false;
  27016. };
  27017. SIMDHelper.EnableSIMD = function () {
  27018. if (window.SIMD === undefined) {
  27019. return;
  27020. }
  27021. // Replace functions
  27022. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27023. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27024. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27025. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27027. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27028. get: function () { return this._data[0]; },
  27029. set: function (value) {
  27030. if (!this._data) {
  27031. this._data = new Float32Array(3);
  27032. }
  27033. this._data[0] = value;
  27034. }
  27035. });
  27036. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27037. get: function () { return this._data[1]; },
  27038. set: function (value) {
  27039. this._data[1] = value;
  27040. }
  27041. });
  27042. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27043. get: function () { return this._data[2]; },
  27044. set: function (value) {
  27045. this._data[2] = value;
  27046. }
  27047. });
  27048. SIMDHelper._isEnabled = true;
  27049. };
  27050. SIMDHelper._isEnabled = false;
  27051. return SIMDHelper;
  27052. })();
  27053. BABYLON.SIMDHelper = SIMDHelper;
  27054. })(BABYLON || (BABYLON = {}));
  27055. var BABYLON;
  27056. (function (BABYLON) {
  27057. var ShaderMaterial = (function (_super) {
  27058. __extends(ShaderMaterial, _super);
  27059. function ShaderMaterial(name, scene, shaderPath, options) {
  27060. _super.call(this, name, scene);
  27061. this._textures = new Array();
  27062. this._floats = new Array();
  27063. this._floatsArrays = {};
  27064. this._colors3 = new Array();
  27065. this._colors4 = new Array();
  27066. this._vectors2 = new Array();
  27067. this._vectors3 = new Array();
  27068. this._vectors4 = new Array();
  27069. this._matrices = new Array();
  27070. this._matrices3x3 = new Array();
  27071. this._matrices2x2 = new Array();
  27072. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27073. this._shaderPath = shaderPath;
  27074. options.needAlphaBlending = options.needAlphaBlending || false;
  27075. options.needAlphaTesting = options.needAlphaTesting || false;
  27076. options.attributes = options.attributes || ["position", "normal", "uv"];
  27077. options.uniforms = options.uniforms || ["worldViewProjection"];
  27078. options.samplers = options.samplers || [];
  27079. options.defines = options.defines || [];
  27080. this._options = options;
  27081. }
  27082. ShaderMaterial.prototype.needAlphaBlending = function () {
  27083. return this._options.needAlphaBlending;
  27084. };
  27085. ShaderMaterial.prototype.needAlphaTesting = function () {
  27086. return this._options.needAlphaTesting;
  27087. };
  27088. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27089. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27090. this._options.uniforms.push(uniformName);
  27091. }
  27092. };
  27093. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27094. if (this._options.samplers.indexOf(name) === -1) {
  27095. this._options.samplers.push(name);
  27096. }
  27097. this._textures[name] = texture;
  27098. return this;
  27099. };
  27100. ShaderMaterial.prototype.setFloat = function (name, value) {
  27101. this._checkUniform(name);
  27102. this._floats[name] = value;
  27103. return this;
  27104. };
  27105. ShaderMaterial.prototype.setFloats = function (name, value) {
  27106. this._checkUniform(name);
  27107. this._floatsArrays[name] = value;
  27108. return this;
  27109. };
  27110. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27111. this._checkUniform(name);
  27112. this._colors3[name] = value;
  27113. return this;
  27114. };
  27115. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27116. this._checkUniform(name);
  27117. this._colors4[name] = value;
  27118. return this;
  27119. };
  27120. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27121. this._checkUniform(name);
  27122. this._vectors2[name] = value;
  27123. return this;
  27124. };
  27125. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27126. this._checkUniform(name);
  27127. this._vectors3[name] = value;
  27128. return this;
  27129. };
  27130. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27131. this._checkUniform(name);
  27132. this._vectors4[name] = value;
  27133. return this;
  27134. };
  27135. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27136. this._checkUniform(name);
  27137. this._matrices[name] = value;
  27138. return this;
  27139. };
  27140. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27141. this._checkUniform(name);
  27142. this._matrices3x3[name] = value;
  27143. return this;
  27144. };
  27145. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27146. this._checkUniform(name);
  27147. this._matrices2x2[name] = value;
  27148. return this;
  27149. };
  27150. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27151. var scene = this.getScene();
  27152. var engine = scene.getEngine();
  27153. if (!this.checkReadyOnEveryCall) {
  27154. if (this._renderId === scene.getRenderId()) {
  27155. return true;
  27156. }
  27157. }
  27158. // Instances
  27159. var defines = [];
  27160. var fallbacks = new BABYLON.EffectFallbacks();
  27161. if (useInstances) {
  27162. defines.push("#define INSTANCES");
  27163. }
  27164. for (var index = 0; index < this._options.defines.length; index++) {
  27165. defines.push(this._options.defines[index]);
  27166. }
  27167. // Bones
  27168. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27169. defines.push("#define BONES");
  27170. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27171. defines.push("#define BONES4");
  27172. fallbacks.addFallback(0, "BONES4");
  27173. }
  27174. // Alpha test
  27175. if (engine.getAlphaTesting()) {
  27176. defines.push("#define ALPHATEST");
  27177. }
  27178. var previousEffect = this._effect;
  27179. var join = defines.join("\n");
  27180. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27181. if (!this._effect.isReady()) {
  27182. return false;
  27183. }
  27184. if (previousEffect !== this._effect) {
  27185. scene.resetCachedMaterial();
  27186. }
  27187. this._renderId = scene.getRenderId();
  27188. return true;
  27189. };
  27190. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27191. var scene = this.getScene();
  27192. if (this._options.uniforms.indexOf("world") !== -1) {
  27193. this._effect.setMatrix("world", world);
  27194. }
  27195. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27196. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27197. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27198. }
  27199. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27200. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27201. }
  27202. };
  27203. ShaderMaterial.prototype.bind = function (world, mesh) {
  27204. // Std values
  27205. this.bindOnlyWorldMatrix(world);
  27206. if (this.getScene().getCachedMaterial() !== this) {
  27207. if (this._options.uniforms.indexOf("view") !== -1) {
  27208. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27209. }
  27210. if (this._options.uniforms.indexOf("projection") !== -1) {
  27211. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27212. }
  27213. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27214. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27215. }
  27216. // Bones
  27217. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27218. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27219. }
  27220. // Texture
  27221. for (var name in this._textures) {
  27222. this._effect.setTexture(name, this._textures[name]);
  27223. }
  27224. // Float
  27225. for (name in this._floats) {
  27226. this._effect.setFloat(name, this._floats[name]);
  27227. }
  27228. // Float s
  27229. for (name in this._floatsArrays) {
  27230. this._effect.setArray(name, this._floatsArrays[name]);
  27231. }
  27232. // Color3
  27233. for (name in this._colors3) {
  27234. this._effect.setColor3(name, this._colors3[name]);
  27235. }
  27236. // Color4
  27237. for (name in this._colors4) {
  27238. var color = this._colors4[name];
  27239. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27240. }
  27241. // Vector2
  27242. for (name in this._vectors2) {
  27243. this._effect.setVector2(name, this._vectors2[name]);
  27244. }
  27245. // Vector3
  27246. for (name in this._vectors3) {
  27247. this._effect.setVector3(name, this._vectors3[name]);
  27248. }
  27249. // Vector4
  27250. for (name in this._vectors4) {
  27251. this._effect.setVector4(name, this._vectors4[name]);
  27252. }
  27253. // Matrix
  27254. for (name in this._matrices) {
  27255. this._effect.setMatrix(name, this._matrices[name]);
  27256. }
  27257. // Matrix 3x3
  27258. for (name in this._matrices3x3) {
  27259. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27260. }
  27261. // Matrix 2x2
  27262. for (name in this._matrices2x2) {
  27263. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27264. }
  27265. }
  27266. _super.prototype.bind.call(this, world, mesh);
  27267. };
  27268. ShaderMaterial.prototype.clone = function (name) {
  27269. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27270. return newShaderMaterial;
  27271. };
  27272. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27273. for (var name in this._textures) {
  27274. this._textures[name].dispose();
  27275. }
  27276. this._textures = [];
  27277. _super.prototype.dispose.call(this, forceDisposeEffect);
  27278. };
  27279. return ShaderMaterial;
  27280. })(BABYLON.Material);
  27281. BABYLON.ShaderMaterial = ShaderMaterial;
  27282. })(BABYLON || (BABYLON = {}));
  27283. var BABYLON;
  27284. (function (BABYLON) {
  27285. var Internals;
  27286. (function (Internals) {
  27287. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27288. // All values and structures referenced from:
  27289. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27290. var DDS_MAGIC = 0x20534444;
  27291. 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;
  27292. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27293. 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;
  27294. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27295. function FourCCToInt32(value) {
  27296. return value.charCodeAt(0) +
  27297. (value.charCodeAt(1) << 8) +
  27298. (value.charCodeAt(2) << 16) +
  27299. (value.charCodeAt(3) << 24);
  27300. }
  27301. function Int32ToFourCC(value) {
  27302. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27303. }
  27304. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27305. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27306. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27307. var headerLengthInt = 31; // The header length in 32 bit ints
  27308. // Offsets into the header array
  27309. var off_magic = 0;
  27310. var off_size = 1;
  27311. var off_flags = 2;
  27312. var off_height = 3;
  27313. var off_width = 4;
  27314. var off_mipmapCount = 7;
  27315. var off_pfFlags = 20;
  27316. var off_pfFourCC = 21;
  27317. var off_RGBbpp = 22;
  27318. var off_RMask = 23;
  27319. var off_GMask = 24;
  27320. var off_BMask = 25;
  27321. var off_AMask = 26;
  27322. var off_caps1 = 27;
  27323. var off_caps2 = 28;
  27324. ;
  27325. var DDSTools = (function () {
  27326. function DDSTools() {
  27327. }
  27328. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27329. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27330. var mipmapCount = 1;
  27331. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27332. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27333. }
  27334. return {
  27335. width: header[off_width],
  27336. height: header[off_height],
  27337. mipmapCount: mipmapCount,
  27338. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27339. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27340. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27341. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27342. };
  27343. };
  27344. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27345. var byteArray = new Uint8Array(dataLength);
  27346. var srcData = new Uint8Array(arrayBuffer);
  27347. var index = 0;
  27348. for (var y = height - 1; y >= 0; y--) {
  27349. for (var x = 0; x < width; x++) {
  27350. var srcPos = dataOffset + (x + y * width) * 4;
  27351. byteArray[index + 2] = srcData[srcPos];
  27352. byteArray[index + 1] = srcData[srcPos + 1];
  27353. byteArray[index] = srcData[srcPos + 2];
  27354. byteArray[index + 3] = srcData[srcPos + 3];
  27355. index += 4;
  27356. }
  27357. }
  27358. return byteArray;
  27359. };
  27360. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27361. var byteArray = new Uint8Array(dataLength);
  27362. var srcData = new Uint8Array(arrayBuffer);
  27363. var index = 0;
  27364. for (var y = height - 1; y >= 0; y--) {
  27365. for (var x = 0; x < width; x++) {
  27366. var srcPos = dataOffset + (x + y * width) * 3;
  27367. byteArray[index + 2] = srcData[srcPos];
  27368. byteArray[index + 1] = srcData[srcPos + 1];
  27369. byteArray[index] = srcData[srcPos + 2];
  27370. index += 3;
  27371. }
  27372. }
  27373. return byteArray;
  27374. };
  27375. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27376. var byteArray = new Uint8Array(dataLength);
  27377. var srcData = new Uint8Array(arrayBuffer);
  27378. var index = 0;
  27379. for (var y = height - 1; y >= 0; y--) {
  27380. for (var x = 0; x < width; x++) {
  27381. var srcPos = dataOffset + (x + y * width);
  27382. byteArray[index] = srcData[srcPos];
  27383. index++;
  27384. }
  27385. }
  27386. return byteArray;
  27387. };
  27388. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27389. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27390. if (header[off_magic] != DDS_MAGIC) {
  27391. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27392. return;
  27393. }
  27394. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27395. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27396. return;
  27397. }
  27398. if (info.isFourCC) {
  27399. fourCC = header[off_pfFourCC];
  27400. switch (fourCC) {
  27401. case FOURCC_DXT1:
  27402. blockBytes = 8;
  27403. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27404. break;
  27405. case FOURCC_DXT3:
  27406. blockBytes = 16;
  27407. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27408. break;
  27409. case FOURCC_DXT5:
  27410. blockBytes = 16;
  27411. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27412. break;
  27413. default:
  27414. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27415. return;
  27416. }
  27417. }
  27418. mipmapCount = 1;
  27419. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27420. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27421. }
  27422. var bpp = header[off_RGBbpp];
  27423. for (var face = 0; face < faces; face++) {
  27424. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27425. width = header[off_width];
  27426. height = header[off_height];
  27427. dataOffset = header[off_size] + 4;
  27428. for (i = 0; i < mipmapCount; ++i) {
  27429. if (info.isRGB) {
  27430. if (bpp === 24) {
  27431. dataLength = width * height * 3;
  27432. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27433. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  27434. }
  27435. else {
  27436. dataLength = width * height * 4;
  27437. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27438. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  27439. }
  27440. }
  27441. else if (info.isLuminance) {
  27442. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  27443. var unpaddedRowSize = width;
  27444. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  27445. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  27446. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27447. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  27448. }
  27449. else {
  27450. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  27451. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  27452. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  27453. }
  27454. dataOffset += dataLength;
  27455. width *= 0.5;
  27456. height *= 0.5;
  27457. width = Math.max(1.0, width);
  27458. height = Math.max(1.0, height);
  27459. }
  27460. }
  27461. };
  27462. return DDSTools;
  27463. })();
  27464. Internals.DDSTools = DDSTools;
  27465. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27466. })(BABYLON || (BABYLON = {}));
  27467. var BABYLON;
  27468. (function (BABYLON) {
  27469. var CannonJSPlugin = (function () {
  27470. function CannonJSPlugin() {
  27471. this._registeredMeshes = [];
  27472. this._physicsMaterials = [];
  27473. this.updateBodyPosition = function (mesh) {
  27474. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27475. var registeredMesh = this._registeredMeshes[index];
  27476. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27477. var body = registeredMesh.body;
  27478. var center = mesh.getBoundingInfo().boundingBox.center;
  27479. body.position.set(center.x, center.y, center.z);
  27480. body.quaternion.x = mesh.rotationQuaternion.x;
  27481. body.quaternion.z = mesh.rotationQuaternion.z;
  27482. body.quaternion.y = mesh.rotationQuaternion.y;
  27483. body.quaternion.w = mesh.rotationQuaternion.w;
  27484. return;
  27485. }
  27486. }
  27487. };
  27488. }
  27489. CannonJSPlugin.prototype.initialize = function (iterations) {
  27490. if (iterations === void 0) { iterations = 10; }
  27491. this._world = new CANNON.World();
  27492. this._world.broadphase = new CANNON.NaiveBroadphase();
  27493. this._world.solver.iterations = iterations;
  27494. };
  27495. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  27496. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27497. };
  27498. CannonJSPlugin.prototype.runOneStep = function (delta) {
  27499. this._world.step(delta);
  27500. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27501. var registeredMesh = this._registeredMeshes[index];
  27502. if (registeredMesh.isChild) {
  27503. continue;
  27504. }
  27505. // Body position
  27506. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  27507. if (!registeredMesh.delta) {
  27508. registeredMesh.delta = BABYLON.Vector3.Zero();
  27509. }
  27510. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  27511. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  27512. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  27513. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  27514. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.y;
  27515. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.z;
  27516. registeredMesh.mesh.rotationQuaternion.w = registeredMesh.body.quaternion.w;
  27517. }
  27518. };
  27519. CannonJSPlugin.prototype.setGravity = function (gravity) {
  27520. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  27521. };
  27522. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27523. this.unregisterMesh(mesh);
  27524. if (!mesh.rotationQuaternion) {
  27525. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27526. }
  27527. mesh.computeWorldMatrix(true);
  27528. var shape = this._createShape(mesh, impostor, options);
  27529. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  27530. };
  27531. CannonJSPlugin.prototype._createShape = function (mesh, impostor, options) {
  27532. //get the correct bounding box
  27533. var oldQuaternion = mesh.rotationQuaternion;
  27534. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27535. mesh.computeWorldMatrix(true);
  27536. var returnValue;
  27537. switch (impostor) {
  27538. case BABYLON.PhysicsEngine.SphereImpostor:
  27539. var bbox = mesh.getBoundingInfo().boundingBox;
  27540. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27541. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27542. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27543. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  27544. break;
  27545. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  27546. case BABYLON.PhysicsEngine.CylinderImpostor:
  27547. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  27548. case BABYLON.PhysicsEngine.BoxImpostor:
  27549. bbox = mesh.getBoundingInfo().boundingBox;
  27550. var min = bbox.minimumWorld;
  27551. var max = bbox.maximumWorld;
  27552. var box = max.subtract(min).scale(0.5);
  27553. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  27554. break;
  27555. case BABYLON.PhysicsEngine.PlaneImpostor:
  27556. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  27557. returnValue = new CANNON.Plane();
  27558. break;
  27559. case BABYLON.PhysicsEngine.MeshImpostor:
  27560. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27561. var rawFaces = mesh.getIndices();
  27562. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  27563. break;
  27564. }
  27565. mesh.rotationQuaternion = oldQuaternion;
  27566. return returnValue;
  27567. };
  27568. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  27569. var verts = [], faces = [];
  27570. mesh.computeWorldMatrix(true);
  27571. // Get vertices
  27572. for (var i = 0; i < rawVerts.length; i += 3) {
  27573. var transformed = BABYLON.Vector3.Zero();
  27574. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  27575. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  27576. }
  27577. // Get faces
  27578. for (var j = 0; j < rawFaces.length; j += 3) {
  27579. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  27580. }
  27581. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  27582. return shape;
  27583. };
  27584. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  27585. var index;
  27586. var mat;
  27587. for (index = 0; index < this._physicsMaterials.length; index++) {
  27588. mat = this._physicsMaterials[index];
  27589. if (mat.friction === friction && mat.restitution === restitution) {
  27590. return mat;
  27591. }
  27592. }
  27593. var currentMat = new CANNON.Material("mat");
  27594. this._physicsMaterials.push(currentMat);
  27595. for (index = 0; index < this._physicsMaterials.length; index++) {
  27596. mat = this._physicsMaterials[index];
  27597. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  27598. this._world.addContactMaterial(contactMaterial);
  27599. }
  27600. return currentMat;
  27601. };
  27602. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  27603. if (!mesh.rotationQuaternion) {
  27604. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27605. }
  27606. // The delta between the mesh position and the mesh bounding box center
  27607. var bbox = mesh.getBoundingInfo().boundingBox;
  27608. var deltaPosition = mesh.position.subtract(bbox.center);
  27609. var material = this._addMaterial(friction, restitution);
  27610. var body = new CANNON.Body({
  27611. mass: mass,
  27612. material: material,
  27613. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  27614. });
  27615. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  27616. //is shape is a plane, it must be rotated 90 degs in the X axis.
  27617. if (shape.type === CANNON.Shape.types.PLANE) {
  27618. var tmpQ = new CANNON.Quaternion();
  27619. tmpQ.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
  27620. body.quaternion = body.quaternion.mult(tmpQ);
  27621. }
  27622. //add the shape
  27623. body.addShape(shape);
  27624. this._world.add(body);
  27625. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  27626. return body;
  27627. };
  27628. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  27629. var initialMesh = parts[0].mesh;
  27630. this.unregisterMesh(initialMesh);
  27631. initialMesh.computeWorldMatrix(true);
  27632. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  27633. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options.mass, options.friction, options.restitution);
  27634. for (var index = 1; index < parts.length; index++) {
  27635. var mesh = parts[index].mesh;
  27636. mesh.computeWorldMatrix(true);
  27637. var shape = this._createShape(mesh, parts[index].impostor);
  27638. var localPosition = mesh.position;
  27639. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  27640. }
  27641. return body;
  27642. };
  27643. CannonJSPlugin.prototype._unbindBody = function (body) {
  27644. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27645. var registeredMesh = this._registeredMeshes[index];
  27646. if (registeredMesh.body === body) {
  27647. this._world.remove(registeredMesh.body);
  27648. registeredMesh.body = null;
  27649. registeredMesh.delta = null;
  27650. }
  27651. }
  27652. };
  27653. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  27654. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27655. var registeredMesh = this._registeredMeshes[index];
  27656. if (registeredMesh.mesh === mesh) {
  27657. // Remove body
  27658. if (registeredMesh.body) {
  27659. this._unbindBody(registeredMesh.body);
  27660. }
  27661. this._registeredMeshes.splice(index, 1);
  27662. return;
  27663. }
  27664. }
  27665. };
  27666. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  27667. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  27668. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  27669. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27670. var registeredMesh = this._registeredMeshes[index];
  27671. if (registeredMesh.mesh === mesh) {
  27672. registeredMesh.body.applyImpulse(impulse, worldPoint);
  27673. return;
  27674. }
  27675. }
  27676. };
  27677. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  27678. var body1 = null, body2 = null;
  27679. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27680. var registeredMesh = this._registeredMeshes[index];
  27681. if (registeredMesh.mesh === mesh1) {
  27682. body1 = registeredMesh.body;
  27683. }
  27684. else if (registeredMesh.mesh === mesh2) {
  27685. body2 = registeredMesh.body;
  27686. }
  27687. }
  27688. if (!body1 || !body2) {
  27689. return false;
  27690. }
  27691. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  27692. this._world.addConstraint(constraint);
  27693. return true;
  27694. };
  27695. CannonJSPlugin.prototype.dispose = function () {
  27696. while (this._registeredMeshes.length) {
  27697. this.unregisterMesh(this._registeredMeshes[0].mesh);
  27698. }
  27699. };
  27700. CannonJSPlugin.prototype.isSupported = function () {
  27701. return window.CANNON !== undefined;
  27702. };
  27703. CannonJSPlugin.prototype.getWorldObject = function () {
  27704. return this._world;
  27705. };
  27706. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  27707. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27708. var registeredMesh = this._registeredMeshes[index];
  27709. if (registeredMesh.mesh === mesh) {
  27710. return registeredMesh.body;
  27711. }
  27712. }
  27713. return null;
  27714. };
  27715. return CannonJSPlugin;
  27716. })();
  27717. BABYLON.CannonJSPlugin = CannonJSPlugin;
  27718. })(BABYLON || (BABYLON = {}));
  27719. var BABYLON;
  27720. (function (BABYLON) {
  27721. var OimoJSPlugin = (function () {
  27722. function OimoJSPlugin() {
  27723. this._registeredMeshes = [];
  27724. /**
  27725. * Update the body position according to the mesh position
  27726. * @param mesh
  27727. */
  27728. this.updateBodyPosition = function (mesh) {
  27729. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27730. var registeredMesh = this._registeredMeshes[index];
  27731. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27732. var body = registeredMesh.body.body;
  27733. mesh.computeWorldMatrix(true);
  27734. var center = mesh.getBoundingInfo().boundingBox.center;
  27735. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  27736. body.setQuaternion(mesh.rotationQuaternion);
  27737. body.sleeping = false;
  27738. return;
  27739. }
  27740. // Case where the parent has been updated
  27741. if (registeredMesh.mesh.parent === mesh) {
  27742. mesh.computeWorldMatrix(true);
  27743. registeredMesh.mesh.computeWorldMatrix(true);
  27744. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  27745. body = registeredMesh.body.body;
  27746. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  27747. body.setQuaternion(mesh.rotationQuaternion);
  27748. body.sleeping = false;
  27749. return;
  27750. }
  27751. }
  27752. };
  27753. }
  27754. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  27755. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27756. };
  27757. OimoJSPlugin.prototype.initialize = function (iterations) {
  27758. this._world = new OIMO.World(null, null, iterations);
  27759. this._world.clear();
  27760. };
  27761. OimoJSPlugin.prototype.setGravity = function (gravity) {
  27762. this._world.gravity = gravity;
  27763. };
  27764. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27765. this.unregisterMesh(mesh);
  27766. if (!mesh.rotationQuaternion) {
  27767. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27768. }
  27769. mesh.computeWorldMatrix(true);
  27770. var bbox = mesh.getBoundingInfo().boundingBox;
  27771. // The delta between the mesh position and the mesh bounding box center
  27772. var deltaPosition = mesh.position.subtract(bbox.center);
  27773. //calculate rotation to fit Oimo's needs (Euler...)
  27774. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  27775. //get the correct bounding box
  27776. var oldQuaternion = mesh.rotationQuaternion;
  27777. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27778. mesh.computeWorldMatrix(true);
  27779. var bodyConfig = {
  27780. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  27781. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  27782. move: options.mass != 0,
  27783. config: [options.mass, options.friction, options.restitution],
  27784. world: this._world
  27785. };
  27786. // register mesh
  27787. switch (impostor) {
  27788. case BABYLON.PhysicsEngine.SphereImpostor:
  27789. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27790. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27791. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27792. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  27793. bodyConfig.type = 'sphere';
  27794. bodyConfig.size = [size];
  27795. break;
  27796. case BABYLON.PhysicsEngine.PlaneImpostor:
  27797. //Oimo "fakes" a cylinder as a box, so why don't we!
  27798. case BABYLON.PhysicsEngine.CylinderImpostor:
  27799. case BABYLON.PhysicsEngine.BoxImpostor:
  27800. var min = bbox.minimumWorld;
  27801. var max = bbox.maximumWorld;
  27802. var box = max.subtract(min);
  27803. var sizeX = this._checkWithEpsilon(box.x);
  27804. var sizeY = this._checkWithEpsilon(box.y);
  27805. var sizeZ = this._checkWithEpsilon(box.z);
  27806. bodyConfig.type = 'box';
  27807. bodyConfig.size = [sizeX, sizeY, sizeZ];
  27808. break;
  27809. }
  27810. var body = new OIMO.Body(bodyConfig);
  27811. //We have to access the rigid body's properties to set the quaternion.
  27812. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  27813. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  27814. //TEST
  27815. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  27816. //update the internal rotation matrix
  27817. //body.body.syncShapes();
  27818. this._registeredMeshes.push({
  27819. mesh: mesh,
  27820. body: body,
  27821. delta: deltaPosition
  27822. });
  27823. //for the sake of consistency.
  27824. mesh.rotationQuaternion = oldQuaternion;
  27825. return body;
  27826. };
  27827. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  27828. var types = [], sizes = [], positions = [], rotations = [];
  27829. var initialMesh = parts[0].mesh;
  27830. for (var index = 0; index < parts.length; index++) {
  27831. var part = parts[index];
  27832. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  27833. types.push(bodyParameters.type);
  27834. sizes.push.apply(sizes, bodyParameters.size);
  27835. positions.push.apply(positions, bodyParameters.pos);
  27836. rotations.push.apply(rotations, bodyParameters.rot);
  27837. }
  27838. var body = new OIMO.Body({
  27839. type: types,
  27840. size: sizes,
  27841. pos: positions,
  27842. rot: rotations,
  27843. move: options.mass != 0,
  27844. config: [options.mass, options.friction, options.restitution],
  27845. world: this._world
  27846. });
  27847. //Reset the body's rotation to be of the initial mesh's.
  27848. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  27849. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  27850. this._registeredMeshes.push({
  27851. mesh: initialMesh,
  27852. body: body
  27853. });
  27854. return body;
  27855. };
  27856. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  27857. var mesh = part.mesh;
  27858. if (!mesh.rotationQuaternion) {
  27859. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27860. }
  27861. // We need the bounding box/sphere info to compute the physics body
  27862. mesh.computeWorldMatrix(true);
  27863. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  27864. var bodyParameters = {
  27865. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  27866. //A bug in Oimo (Body class) prevents us from using rot directly.
  27867. rot: [0, 0, 0],
  27868. //For future reference, if the bug will ever be fixed.
  27869. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  27870. };
  27871. var oldQuaternion = mesh.rotationQuaternion;
  27872. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27873. mesh.computeWorldMatrix(true);
  27874. switch (part.impostor) {
  27875. case BABYLON.PhysicsEngine.SphereImpostor:
  27876. var bbox = mesh.getBoundingInfo().boundingBox;
  27877. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27878. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27879. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27880. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  27881. bodyParameters.type = 'sphere';
  27882. bodyParameters.size = [size, size, size];
  27883. break;
  27884. case BABYLON.PhysicsEngine.PlaneImpostor:
  27885. case BABYLON.PhysicsEngine.CylinderImpostor:
  27886. case BABYLON.PhysicsEngine.BoxImpostor:
  27887. bbox = mesh.getBoundingInfo().boundingBox;
  27888. var min = bbox.minimumWorld;
  27889. var max = bbox.maximumWorld;
  27890. var box = max.subtract(min);
  27891. var sizeX = this._checkWithEpsilon(box.x);
  27892. var sizeY = this._checkWithEpsilon(box.y);
  27893. var sizeZ = this._checkWithEpsilon(box.z);
  27894. bodyParameters.type = 'box';
  27895. bodyParameters.size = [sizeX, sizeY, sizeZ];
  27896. break;
  27897. }
  27898. mesh.rotationQuaternion = oldQuaternion;
  27899. return bodyParameters;
  27900. };
  27901. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  27902. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27903. var registeredMesh = this._registeredMeshes[index];
  27904. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27905. if (registeredMesh.body) {
  27906. this._world.removeRigidBody(registeredMesh.body.body);
  27907. this._unbindBody(registeredMesh.body);
  27908. }
  27909. this._registeredMeshes.splice(index, 1);
  27910. return;
  27911. }
  27912. }
  27913. };
  27914. OimoJSPlugin.prototype._unbindBody = function (body) {
  27915. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27916. var registeredMesh = this._registeredMeshes[index];
  27917. if (registeredMesh.body === body) {
  27918. registeredMesh.body = null;
  27919. }
  27920. }
  27921. };
  27922. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  27923. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27924. var registeredMesh = this._registeredMeshes[index];
  27925. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27926. // Get object mass to have a behaviour similar to cannon.js
  27927. var mass = registeredMesh.body.body.massInfo.mass;
  27928. // The force is scaled with the mass of object
  27929. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  27930. return;
  27931. }
  27932. }
  27933. };
  27934. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  27935. var body1 = null, body2 = null;
  27936. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27937. var registeredMesh = this._registeredMeshes[index];
  27938. if (registeredMesh.mesh === mesh1) {
  27939. body1 = registeredMesh.body.body;
  27940. }
  27941. else if (registeredMesh.mesh === mesh2) {
  27942. body2 = registeredMesh.body.body;
  27943. }
  27944. }
  27945. if (!body1 || !body2) {
  27946. return false;
  27947. }
  27948. if (!options) {
  27949. options = {};
  27950. }
  27951. new OIMO.Link({
  27952. type: options.type,
  27953. body1: body1,
  27954. body2: body2,
  27955. min: options.min,
  27956. max: options.max,
  27957. axe1: options.axe1,
  27958. axe2: options.axe2,
  27959. pos1: [pivot1.x, pivot1.y, pivot1.z],
  27960. pos2: [pivot2.x, pivot2.y, pivot2.z],
  27961. collision: options.collision,
  27962. spring: options.spring,
  27963. world: this._world
  27964. });
  27965. return true;
  27966. };
  27967. OimoJSPlugin.prototype.dispose = function () {
  27968. this._world.clear();
  27969. while (this._registeredMeshes.length) {
  27970. this.unregisterMesh(this._registeredMeshes[0].mesh);
  27971. }
  27972. };
  27973. OimoJSPlugin.prototype.isSupported = function () {
  27974. return OIMO !== undefined;
  27975. };
  27976. OimoJSPlugin.prototype.getWorldObject = function () {
  27977. return this._world;
  27978. };
  27979. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  27980. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27981. var registeredMesh = this._registeredMeshes[index];
  27982. if (registeredMesh.mesh === mesh) {
  27983. return registeredMesh.body;
  27984. }
  27985. }
  27986. return null;
  27987. };
  27988. OimoJSPlugin.prototype._getLastShape = function (body) {
  27989. var lastShape = body.shapes;
  27990. while (lastShape.next) {
  27991. lastShape = lastShape.next;
  27992. }
  27993. return lastShape;
  27994. };
  27995. OimoJSPlugin.prototype.runOneStep = function (time) {
  27996. this._world.step();
  27997. // Update the position of all registered meshes
  27998. var i = this._registeredMeshes.length;
  27999. var m;
  28000. while (i--) {
  28001. var body = this._registeredMeshes[i].body.body;
  28002. var mesh = this._registeredMeshes[i].mesh;
  28003. if (!this._registeredMeshes[i].delta) {
  28004. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28005. }
  28006. if (!body.sleeping) {
  28007. //TODO check that
  28008. if (body.shapes.next) {
  28009. var parentShape = this._getLastShape(body);
  28010. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28011. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28012. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28013. }
  28014. else {
  28015. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28016. }
  28017. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28018. mesh.computeWorldMatrix();
  28019. }
  28020. }
  28021. };
  28022. return OimoJSPlugin;
  28023. })();
  28024. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28025. })(BABYLON || (BABYLON = {}));
  28026. var BABYLON;
  28027. (function (BABYLON) {
  28028. var DisplayPassPostProcess = (function (_super) {
  28029. __extends(DisplayPassPostProcess, _super);
  28030. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28031. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28032. }
  28033. return DisplayPassPostProcess;
  28034. })(BABYLON.PostProcess);
  28035. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28036. })(BABYLON || (BABYLON = {}));
  28037. var BABYLON;
  28038. (function (BABYLON) {
  28039. var SimplificationSettings = (function () {
  28040. function SimplificationSettings(quality, distance, optimizeMesh) {
  28041. this.quality = quality;
  28042. this.distance = distance;
  28043. this.optimizeMesh = optimizeMesh;
  28044. }
  28045. return SimplificationSettings;
  28046. })();
  28047. BABYLON.SimplificationSettings = SimplificationSettings;
  28048. var SimplificationQueue = (function () {
  28049. function SimplificationQueue() {
  28050. this.running = false;
  28051. this._simplificationArray = [];
  28052. }
  28053. SimplificationQueue.prototype.addTask = function (task) {
  28054. this._simplificationArray.push(task);
  28055. };
  28056. SimplificationQueue.prototype.executeNext = function () {
  28057. var task = this._simplificationArray.pop();
  28058. if (task) {
  28059. this.running = true;
  28060. this.runSimplification(task);
  28061. }
  28062. else {
  28063. this.running = false;
  28064. }
  28065. };
  28066. SimplificationQueue.prototype.runSimplification = function (task) {
  28067. var _this = this;
  28068. if (task.parallelProcessing) {
  28069. //parallel simplifier
  28070. task.settings.forEach(function (setting) {
  28071. var simplifier = _this.getSimplifier(task);
  28072. simplifier.simplify(setting, function (newMesh) {
  28073. task.mesh.addLODLevel(setting.distance, newMesh);
  28074. newMesh.isVisible = true;
  28075. //check if it is the last
  28076. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28077. //all done, run the success callback.
  28078. task.successCallback();
  28079. }
  28080. _this.executeNext();
  28081. });
  28082. });
  28083. }
  28084. else {
  28085. //single simplifier.
  28086. var simplifier = this.getSimplifier(task);
  28087. var runDecimation = function (setting, callback) {
  28088. simplifier.simplify(setting, function (newMesh) {
  28089. task.mesh.addLODLevel(setting.distance, newMesh);
  28090. newMesh.isVisible = true;
  28091. //run the next quality level
  28092. callback();
  28093. });
  28094. };
  28095. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28096. runDecimation(task.settings[loop.index], function () {
  28097. loop.executeNext();
  28098. });
  28099. }, function () {
  28100. //execution ended, run the success callback.
  28101. if (task.successCallback) {
  28102. task.successCallback();
  28103. }
  28104. _this.executeNext();
  28105. });
  28106. }
  28107. };
  28108. SimplificationQueue.prototype.getSimplifier = function (task) {
  28109. switch (task.simplificationType) {
  28110. case SimplificationType.QUADRATIC:
  28111. default:
  28112. return new QuadraticErrorSimplification(task.mesh);
  28113. }
  28114. };
  28115. return SimplificationQueue;
  28116. })();
  28117. BABYLON.SimplificationQueue = SimplificationQueue;
  28118. /**
  28119. * The implemented types of simplification.
  28120. * At the moment only Quadratic Error Decimation is implemented.
  28121. */
  28122. (function (SimplificationType) {
  28123. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28124. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28125. var SimplificationType = BABYLON.SimplificationType;
  28126. var DecimationTriangle = (function () {
  28127. function DecimationTriangle(vertices) {
  28128. this.vertices = vertices;
  28129. this.error = new Array(4);
  28130. this.deleted = false;
  28131. this.isDirty = false;
  28132. this.deletePending = false;
  28133. this.borderFactor = 0;
  28134. }
  28135. return DecimationTriangle;
  28136. })();
  28137. BABYLON.DecimationTriangle = DecimationTriangle;
  28138. var DecimationVertex = (function () {
  28139. function DecimationVertex(position, id) {
  28140. this.position = position;
  28141. this.id = id;
  28142. this.isBorder = true;
  28143. this.q = new QuadraticMatrix();
  28144. this.triangleCount = 0;
  28145. this.triangleStart = 0;
  28146. this.originalOffsets = [];
  28147. }
  28148. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28149. this.position.copyFrom(newPosition);
  28150. };
  28151. return DecimationVertex;
  28152. })();
  28153. BABYLON.DecimationVertex = DecimationVertex;
  28154. var QuadraticMatrix = (function () {
  28155. function QuadraticMatrix(data) {
  28156. this.data = new Array(10);
  28157. for (var i = 0; i < 10; ++i) {
  28158. if (data && data[i]) {
  28159. this.data[i] = data[i];
  28160. }
  28161. else {
  28162. this.data[i] = 0;
  28163. }
  28164. }
  28165. }
  28166. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28167. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28168. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28169. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28170. return det;
  28171. };
  28172. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28173. for (var i = 0; i < 10; ++i) {
  28174. this.data[i] += matrix.data[i];
  28175. }
  28176. };
  28177. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28178. for (var i = 0; i < 10; ++i) {
  28179. this.data[i] += data[i];
  28180. }
  28181. };
  28182. QuadraticMatrix.prototype.add = function (matrix) {
  28183. var m = new QuadraticMatrix();
  28184. for (var i = 0; i < 10; ++i) {
  28185. m.data[i] = this.data[i] + matrix.data[i];
  28186. }
  28187. return m;
  28188. };
  28189. QuadraticMatrix.FromData = function (a, b, c, d) {
  28190. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28191. };
  28192. //returning an array to avoid garbage collection
  28193. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28194. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28195. };
  28196. return QuadraticMatrix;
  28197. })();
  28198. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28199. var Reference = (function () {
  28200. function Reference(vertexId, triangleId) {
  28201. this.vertexId = vertexId;
  28202. this.triangleId = triangleId;
  28203. }
  28204. return Reference;
  28205. })();
  28206. BABYLON.Reference = Reference;
  28207. /**
  28208. * An implementation of the Quadratic Error simplification algorithm.
  28209. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28210. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28211. * @author RaananW
  28212. */
  28213. var QuadraticErrorSimplification = (function () {
  28214. function QuadraticErrorSimplification(_mesh) {
  28215. this._mesh = _mesh;
  28216. this.initialized = false;
  28217. this.syncIterations = 5000;
  28218. this.aggressiveness = 7;
  28219. this.decimationIterations = 100;
  28220. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28221. }
  28222. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28223. var _this = this;
  28224. this.initDecimatedMesh();
  28225. //iterating through the submeshes array, one after the other.
  28226. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28227. _this.initWithMesh(loop.index, function () {
  28228. _this.runDecimation(settings, loop.index, function () {
  28229. loop.executeNext();
  28230. });
  28231. }, settings.optimizeMesh);
  28232. }, function () {
  28233. setTimeout(function () {
  28234. successCallback(_this._reconstructedMesh);
  28235. }, 0);
  28236. });
  28237. };
  28238. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28239. var _this = this;
  28240. var gCount = 0;
  28241. triangle.vertices.forEach(function (vertex) {
  28242. var count = 0;
  28243. var vPos = vertex.position;
  28244. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28245. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28246. ++count;
  28247. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28248. ++count;
  28249. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28250. ++count;
  28251. if (count > 1) {
  28252. ++gCount;
  28253. }
  28254. ;
  28255. });
  28256. if (gCount > 1) {
  28257. console.log(triangle, gCount);
  28258. }
  28259. return gCount > 1;
  28260. };
  28261. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28262. var _this = this;
  28263. var targetCount = ~~(this.triangles.length * settings.quality);
  28264. var deletedTriangles = 0;
  28265. var triangleCount = this.triangles.length;
  28266. var iterationFunction = function (iteration, callback) {
  28267. setTimeout(function () {
  28268. if (iteration % 5 === 0) {
  28269. _this.updateMesh(iteration === 0);
  28270. }
  28271. for (var i = 0; i < _this.triangles.length; ++i) {
  28272. _this.triangles[i].isDirty = false;
  28273. }
  28274. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28275. var trianglesIterator = function (i) {
  28276. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28277. var t = _this.triangles[tIdx];
  28278. if (!t)
  28279. return;
  28280. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28281. return;
  28282. }
  28283. for (var j = 0; j < 3; ++j) {
  28284. if (t.error[j] < threshold) {
  28285. var deleted0 = [];
  28286. var deleted1 = [];
  28287. var v0 = t.vertices[j];
  28288. var v1 = t.vertices[(j + 1) % 3];
  28289. if (v0.isBorder !== v1.isBorder)
  28290. continue;
  28291. var p = BABYLON.Vector3.Zero();
  28292. var n = BABYLON.Vector3.Zero();
  28293. var uv = BABYLON.Vector2.Zero();
  28294. var color = new BABYLON.Color4(0, 0, 0, 1);
  28295. _this.calculateError(v0, v1, p, n, uv, color);
  28296. var delTr = [];
  28297. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28298. continue;
  28299. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28300. continue;
  28301. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28302. continue;
  28303. var uniqueArray = [];
  28304. delTr.forEach(function (deletedT) {
  28305. if (uniqueArray.indexOf(deletedT) === -1) {
  28306. deletedT.deletePending = true;
  28307. uniqueArray.push(deletedT);
  28308. }
  28309. });
  28310. if (uniqueArray.length % 2 !== 0) {
  28311. continue;
  28312. }
  28313. v0.q = v1.q.add(v0.q);
  28314. v0.updatePosition(p);
  28315. var tStart = _this.references.length;
  28316. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28317. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28318. var tCount = _this.references.length - tStart;
  28319. if (tCount <= v0.triangleCount) {
  28320. if (tCount) {
  28321. for (var c = 0; c < tCount; c++) {
  28322. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28323. }
  28324. }
  28325. }
  28326. else {
  28327. v0.triangleStart = tStart;
  28328. }
  28329. v0.triangleCount = tCount;
  28330. break;
  28331. }
  28332. }
  28333. };
  28334. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  28335. }, 0);
  28336. };
  28337. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28338. if (triangleCount - deletedTriangles <= targetCount)
  28339. loop.breakLoop();
  28340. else {
  28341. iterationFunction(loop.index, function () {
  28342. loop.executeNext();
  28343. });
  28344. }
  28345. }, function () {
  28346. setTimeout(function () {
  28347. //reconstruct this part of the mesh
  28348. _this.reconstructMesh(submeshIndex);
  28349. successCallback();
  28350. }, 0);
  28351. });
  28352. };
  28353. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28354. var _this = this;
  28355. this.vertices = [];
  28356. this.triangles = [];
  28357. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28358. var indices = this._mesh.getIndices();
  28359. var submesh = this._mesh.subMeshes[submeshIndex];
  28360. var findInVertices = function (positionToSearch) {
  28361. if (optimizeMesh) {
  28362. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28363. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28364. return _this.vertices[ii];
  28365. }
  28366. }
  28367. }
  28368. return null;
  28369. };
  28370. var vertexReferences = [];
  28371. var vertexInit = function (i) {
  28372. var offset = i + submesh.verticesStart;
  28373. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28374. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28375. vertex.originalOffsets.push(offset);
  28376. if (vertex.id === _this.vertices.length) {
  28377. _this.vertices.push(vertex);
  28378. }
  28379. vertexReferences.push(vertex.id);
  28380. };
  28381. //var totalVertices = mesh.getTotalVertices();
  28382. var totalVertices = submesh.verticesCount;
  28383. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28384. var indicesInit = function (i) {
  28385. var offset = (submesh.indexStart / 3) + i;
  28386. var pos = (offset * 3);
  28387. var i0 = indices[pos + 0];
  28388. var i1 = indices[pos + 1];
  28389. var i2 = indices[pos + 2];
  28390. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28391. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28392. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28393. var triangle = new DecimationTriangle([v0, v1, v2]);
  28394. triangle.originalOffset = pos;
  28395. _this.triangles.push(triangle);
  28396. };
  28397. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28398. _this.init(callback);
  28399. });
  28400. });
  28401. };
  28402. QuadraticErrorSimplification.prototype.init = function (callback) {
  28403. var _this = this;
  28404. var triangleInit1 = function (i) {
  28405. var t = _this.triangles[i];
  28406. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28407. for (var j = 0; j < 3; j++) {
  28408. 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))));
  28409. }
  28410. };
  28411. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28412. var triangleInit2 = function (i) {
  28413. var t = _this.triangles[i];
  28414. for (var j = 0; j < 3; ++j) {
  28415. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28416. }
  28417. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28418. };
  28419. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28420. _this.initialized = true;
  28421. callback();
  28422. });
  28423. });
  28424. };
  28425. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28426. var newTriangles = [];
  28427. var i;
  28428. for (i = 0; i < this.vertices.length; ++i) {
  28429. this.vertices[i].triangleCount = 0;
  28430. }
  28431. var t;
  28432. var j;
  28433. for (i = 0; i < this.triangles.length; ++i) {
  28434. if (!this.triangles[i].deleted) {
  28435. t = this.triangles[i];
  28436. for (j = 0; j < 3; ++j) {
  28437. t.vertices[j].triangleCount = 1;
  28438. }
  28439. newTriangles.push(t);
  28440. }
  28441. }
  28442. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  28443. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  28444. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  28445. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  28446. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28447. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28448. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28449. var vertexCount = 0;
  28450. for (i = 0; i < this.vertices.length; ++i) {
  28451. var vertex = this.vertices[i];
  28452. vertex.id = vertexCount;
  28453. if (vertex.triangleCount) {
  28454. vertex.originalOffsets.forEach(function (originalOffset) {
  28455. newPositionData.push(vertex.position.x);
  28456. newPositionData.push(vertex.position.y);
  28457. newPositionData.push(vertex.position.z);
  28458. newNormalData.push(normalData[originalOffset * 3]);
  28459. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28460. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28461. if (uvs && uvs.length) {
  28462. newUVsData.push(uvs[(originalOffset * 2)]);
  28463. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28464. }
  28465. else if (colorsData && colorsData.length) {
  28466. newColorsData.push(colorsData[(originalOffset * 4)]);
  28467. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28468. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28469. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28470. }
  28471. ++vertexCount;
  28472. });
  28473. }
  28474. }
  28475. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28476. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28477. var submeshesArray = this._reconstructedMesh.subMeshes;
  28478. this._reconstructedMesh.subMeshes = [];
  28479. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28480. var originalIndices = this._mesh.getIndices();
  28481. for (i = 0; i < newTriangles.length; ++i) {
  28482. t = newTriangles[i]; //now get the new referencing point for each vertex
  28483. [0, 1, 2].forEach(function (idx) {
  28484. var id = originalIndices[t.originalOffset + idx];
  28485. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28486. if (offset < 0)
  28487. offset = 0;
  28488. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28489. });
  28490. }
  28491. //overwriting the old vertex buffers and indices.
  28492. this._reconstructedMesh.setIndices(newIndicesArray);
  28493. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28494. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28495. if (newUVsData.length > 0)
  28496. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28497. if (newColorsData.length > 0)
  28498. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28499. //create submesh
  28500. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28501. if (submeshIndex > 0) {
  28502. this._reconstructedMesh.subMeshes = [];
  28503. submeshesArray.forEach(function (submesh) {
  28504. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28505. });
  28506. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28507. }
  28508. };
  28509. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28510. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28511. this._reconstructedMesh.material = this._mesh.material;
  28512. this._reconstructedMesh.parent = this._mesh.parent;
  28513. this._reconstructedMesh.isVisible = false;
  28514. };
  28515. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  28516. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28517. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28518. if (t.deleted)
  28519. continue;
  28520. var s = this.references[vertex1.triangleStart + i].vertexId;
  28521. var v1 = t.vertices[(s + 1) % 3];
  28522. var v2 = t.vertices[(s + 2) % 3];
  28523. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  28524. deletedArray[i] = true;
  28525. delTr.push(t);
  28526. continue;
  28527. }
  28528. var d1 = v1.position.subtract(point);
  28529. d1 = d1.normalize();
  28530. var d2 = v2.position.subtract(point);
  28531. d2 = d2.normalize();
  28532. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28533. return true;
  28534. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28535. deletedArray[i] = false;
  28536. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28537. return true;
  28538. }
  28539. return false;
  28540. };
  28541. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  28542. var newDeleted = deletedTriangles;
  28543. for (var i = 0; i < vertex.triangleCount; ++i) {
  28544. var ref = this.references[vertex.triangleStart + i];
  28545. var t = this.triangles[ref.triangleId];
  28546. if (t.deleted)
  28547. continue;
  28548. if (deletedArray[i] && t.deletePending) {
  28549. t.deleted = true;
  28550. newDeleted++;
  28551. continue;
  28552. }
  28553. t.vertices[ref.vertexId] = origVertex;
  28554. t.isDirty = true;
  28555. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  28556. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  28557. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  28558. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28559. this.references.push(ref);
  28560. }
  28561. return newDeleted;
  28562. };
  28563. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28564. for (var i = 0; i < this.vertices.length; ++i) {
  28565. var vCount = [];
  28566. var vId = [];
  28567. var v = this.vertices[i];
  28568. var j;
  28569. for (j = 0; j < v.triangleCount; ++j) {
  28570. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28571. for (var ii = 0; ii < 3; ii++) {
  28572. var ofs = 0;
  28573. var vv = triangle.vertices[ii];
  28574. while (ofs < vCount.length) {
  28575. if (vId[ofs] === vv.id)
  28576. break;
  28577. ++ofs;
  28578. }
  28579. if (ofs === vCount.length) {
  28580. vCount.push(1);
  28581. vId.push(vv.id);
  28582. }
  28583. else {
  28584. vCount[ofs]++;
  28585. }
  28586. }
  28587. }
  28588. for (j = 0; j < vCount.length; ++j) {
  28589. if (vCount[j] === 1) {
  28590. this.vertices[vId[j]].isBorder = true;
  28591. }
  28592. else {
  28593. this.vertices[vId[j]].isBorder = false;
  28594. }
  28595. }
  28596. }
  28597. };
  28598. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28599. if (identifyBorders === void 0) { identifyBorders = false; }
  28600. var i;
  28601. if (!identifyBorders) {
  28602. var newTrianglesVector = [];
  28603. for (i = 0; i < this.triangles.length; ++i) {
  28604. if (!this.triangles[i].deleted) {
  28605. newTrianglesVector.push(this.triangles[i]);
  28606. }
  28607. }
  28608. this.triangles = newTrianglesVector;
  28609. }
  28610. for (i = 0; i < this.vertices.length; ++i) {
  28611. this.vertices[i].triangleCount = 0;
  28612. this.vertices[i].triangleStart = 0;
  28613. }
  28614. var t;
  28615. var j;
  28616. var v;
  28617. for (i = 0; i < this.triangles.length; ++i) {
  28618. t = this.triangles[i];
  28619. for (j = 0; j < 3; ++j) {
  28620. v = t.vertices[j];
  28621. v.triangleCount++;
  28622. }
  28623. }
  28624. var tStart = 0;
  28625. for (i = 0; i < this.vertices.length; ++i) {
  28626. this.vertices[i].triangleStart = tStart;
  28627. tStart += this.vertices[i].triangleCount;
  28628. this.vertices[i].triangleCount = 0;
  28629. }
  28630. var newReferences = new Array(this.triangles.length * 3);
  28631. for (i = 0; i < this.triangles.length; ++i) {
  28632. t = this.triangles[i];
  28633. for (j = 0; j < 3; ++j) {
  28634. v = t.vertices[j];
  28635. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28636. v.triangleCount++;
  28637. }
  28638. }
  28639. this.references = newReferences;
  28640. if (identifyBorders) {
  28641. this.identifyBorder();
  28642. }
  28643. };
  28644. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28645. var x = point.x;
  28646. var y = point.y;
  28647. var z = point.z;
  28648. 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
  28649. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  28650. };
  28651. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28652. var q = vertex1.q.add(vertex2.q);
  28653. var border = vertex1.isBorder && vertex2.isBorder;
  28654. var error = 0;
  28655. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28656. if (qDet !== 0 && !border) {
  28657. if (!pointResult) {
  28658. pointResult = BABYLON.Vector3.Zero();
  28659. }
  28660. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28661. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28662. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28663. error = this.vertexError(q, pointResult);
  28664. }
  28665. else {
  28666. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28667. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28668. var error1 = this.vertexError(q, vertex1.position);
  28669. var error2 = this.vertexError(q, vertex2.position);
  28670. var error3 = this.vertexError(q, p3);
  28671. error = Math.min(error1, error2, error3);
  28672. if (error === error1) {
  28673. if (pointResult) {
  28674. pointResult.copyFrom(vertex1.position);
  28675. }
  28676. }
  28677. else if (error === error2) {
  28678. if (pointResult) {
  28679. pointResult.copyFrom(vertex2.position);
  28680. }
  28681. }
  28682. else {
  28683. if (pointResult) {
  28684. pointResult.copyFrom(p3);
  28685. }
  28686. }
  28687. }
  28688. return error;
  28689. };
  28690. return QuadraticErrorSimplification;
  28691. })();
  28692. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28693. })(BABYLON || (BABYLON = {}));
  28694. var BABYLON;
  28695. (function (BABYLON) {
  28696. var serializeLight = function (light) {
  28697. var serializationObject = {};
  28698. serializationObject.name = light.name;
  28699. serializationObject.id = light.id;
  28700. serializationObject.tags = BABYLON.Tags.GetTags(light);
  28701. if (light instanceof BABYLON.PointLight) {
  28702. serializationObject.type = 0;
  28703. serializationObject.position = (light).position.asArray();
  28704. }
  28705. else if (light instanceof BABYLON.DirectionalLight) {
  28706. serializationObject.type = 1;
  28707. var directionalLight = light;
  28708. serializationObject.position = directionalLight.position.asArray();
  28709. serializationObject.direction = directionalLight.direction.asArray();
  28710. }
  28711. else if (light instanceof BABYLON.SpotLight) {
  28712. serializationObject.type = 2;
  28713. var spotLight = light;
  28714. serializationObject.position = spotLight.position.asArray();
  28715. serializationObject.direction = spotLight.position.asArray();
  28716. serializationObject.angle = spotLight.angle;
  28717. serializationObject.exponent = spotLight.exponent;
  28718. }
  28719. else if (light instanceof BABYLON.HemisphericLight) {
  28720. serializationObject.type = 3;
  28721. var hemisphericLight = light;
  28722. serializationObject.direction = hemisphericLight.direction.asArray();
  28723. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  28724. }
  28725. if (light.intensity) {
  28726. serializationObject.intensity = light.intensity;
  28727. }
  28728. serializationObject.range = light.range;
  28729. serializationObject.diffuse = light.diffuse.asArray();
  28730. serializationObject.specular = light.specular.asArray();
  28731. return serializationObject;
  28732. };
  28733. var serializeFresnelParameter = function (fresnelParameter) {
  28734. var serializationObject = {};
  28735. serializationObject.isEnabled = fresnelParameter.isEnabled;
  28736. serializationObject.leftColor = fresnelParameter.leftColor;
  28737. serializationObject.rightColor = fresnelParameter.rightColor;
  28738. serializationObject.bias = fresnelParameter.bias;
  28739. serializationObject.power = fresnelParameter.power;
  28740. return serializationObject;
  28741. };
  28742. var serializeAnimation;
  28743. var appendAnimations = function (source, destination) {
  28744. if (source.animations) {
  28745. destination.animations = [];
  28746. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28747. var animation = source.animations[animationIndex];
  28748. destination.animations.push(serializeAnimation(animation));
  28749. }
  28750. }
  28751. };
  28752. var serializeCamera = function (camera) {
  28753. var serializationObject = {};
  28754. serializationObject.name = camera.name;
  28755. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  28756. serializationObject.id = camera.id;
  28757. serializationObject.position = camera.position.asArray();
  28758. // Parent
  28759. if (camera.parent) {
  28760. serializationObject.parentId = camera.parent.id;
  28761. }
  28762. serializationObject.fov = camera.fov;
  28763. serializationObject.minZ = camera.minZ;
  28764. serializationObject.maxZ = camera.maxZ;
  28765. serializationObject.inertia = camera.inertia;
  28766. //setting the type
  28767. if (camera instanceof BABYLON.FreeCamera) {
  28768. serializationObject.type = "FreeCamera";
  28769. }
  28770. else if (camera instanceof BABYLON.ArcRotateCamera) {
  28771. serializationObject.type = "ArcRotateCamera";
  28772. }
  28773. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  28774. serializationObject.type = "AnaglyphArcRotateCamera";
  28775. }
  28776. else if (camera instanceof BABYLON.GamepadCamera) {
  28777. serializationObject.type = "GamepadCamera";
  28778. }
  28779. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  28780. serializationObject.type = "AnaglyphFreeCamera";
  28781. }
  28782. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  28783. serializationObject.type = "DeviceOrientationCamera";
  28784. }
  28785. else if (camera instanceof BABYLON.FollowCamera) {
  28786. serializationObject.type = "FollowCamera";
  28787. }
  28788. else if (camera instanceof BABYLON.TouchCamera) {
  28789. serializationObject.type = "TouchCamera";
  28790. }
  28791. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  28792. serializationObject.type = "VirtualJoysticksCamera";
  28793. }
  28794. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  28795. serializationObject.type = "WebVRFreeCamera";
  28796. }
  28797. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  28798. serializationObject.type = "VRDeviceOrientationFreeCamera";
  28799. }
  28800. //special properties of specific cameras
  28801. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  28802. var arcCamera = camera;
  28803. serializationObject.alpha = arcCamera.alpha;
  28804. serializationObject.beta = arcCamera.beta;
  28805. serializationObject.radius = arcCamera.radius;
  28806. if (arcCamera.target && arcCamera.target.id) {
  28807. serializationObject.lockedTargetId = arcCamera.target.id;
  28808. }
  28809. }
  28810. else if (camera instanceof BABYLON.FollowCamera) {
  28811. var followCam = camera;
  28812. serializationObject.radius = followCam.radius;
  28813. serializationObject.heightOffset = followCam.heightOffset;
  28814. serializationObject.rotationOffset = followCam.rotationOffset;
  28815. }
  28816. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  28817. //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.
  28818. if (camera['_interaxialDistance'] !== undefined) {
  28819. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  28820. }
  28821. }
  28822. //general properties that not all cameras have. The [] is due to typescript's type safety
  28823. if (camera['speed'] !== undefined) {
  28824. serializationObject.speed = camera['speed'];
  28825. }
  28826. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  28827. serializationObject.target = camera['target'].asArray();
  28828. }
  28829. // Target
  28830. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  28831. serializationObject.rotation = camera['rotation'].asArray();
  28832. }
  28833. // Locked target
  28834. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  28835. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  28836. }
  28837. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  28838. serializationObject.applyGravity = camera['applyGravity'] || false;
  28839. if (camera['ellipsoid']) {
  28840. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  28841. }
  28842. // Animations
  28843. appendAnimations(camera, serializationObject);
  28844. // Layer mask
  28845. serializationObject.layerMask = camera.layerMask;
  28846. return serializationObject;
  28847. };
  28848. serializeAnimation = function (animation) {
  28849. var serializationObject = {};
  28850. serializationObject.name = animation.name;
  28851. serializationObject.property = animation.targetProperty;
  28852. serializationObject.framePerSecond = animation.framePerSecond;
  28853. serializationObject.dataType = animation.dataType;
  28854. serializationObject.loopBehavior = animation.loopMode;
  28855. var dataType = animation.dataType;
  28856. serializationObject.keys = [];
  28857. var keys = animation.getKeys();
  28858. for (var index = 0; index < keys.length; index++) {
  28859. var animationKey = keys[index];
  28860. var key = {};
  28861. key.frame = animationKey.frame;
  28862. switch (dataType) {
  28863. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  28864. key.values = [animationKey.value];
  28865. break;
  28866. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  28867. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  28868. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  28869. key.values = animationKey.value.asArray();
  28870. break;
  28871. }
  28872. serializationObject.keys.push(key);
  28873. }
  28874. return serializationObject;
  28875. };
  28876. var serializeMultiMaterial = function (material) {
  28877. var serializationObject = {};
  28878. serializationObject.name = material.name;
  28879. serializationObject.id = material.id;
  28880. serializationObject.tags = BABYLON.Tags.GetTags(material);
  28881. serializationObject.materials = [];
  28882. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  28883. var subMat = material.subMaterials[matIndex];
  28884. if (subMat) {
  28885. serializationObject.materials.push(subMat.id);
  28886. }
  28887. else {
  28888. serializationObject.materials.push(null);
  28889. }
  28890. }
  28891. return serializationObject;
  28892. };
  28893. var serializeTexture;
  28894. var serializeMaterial = function (material) {
  28895. var serializationObject = {};
  28896. serializationObject.name = material.name;
  28897. serializationObject.ambient = material.ambientColor.asArray();
  28898. serializationObject.diffuse = material.diffuseColor.asArray();
  28899. serializationObject.specular = material.specularColor.asArray();
  28900. serializationObject.specularPower = material.specularPower;
  28901. serializationObject.emissive = material.emissiveColor.asArray();
  28902. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  28903. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  28904. serializationObject.alpha = material.alpha;
  28905. serializationObject.id = material.id;
  28906. serializationObject.tags = BABYLON.Tags.GetTags(material);
  28907. serializationObject.backFaceCulling = material.backFaceCulling;
  28908. if (material.diffuseTexture) {
  28909. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  28910. }
  28911. if (material.diffuseFresnelParameters) {
  28912. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  28913. }
  28914. if (material.ambientTexture) {
  28915. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  28916. }
  28917. if (material.opacityTexture) {
  28918. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  28919. }
  28920. if (material.opacityFresnelParameters) {
  28921. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  28922. }
  28923. if (material.reflectionTexture) {
  28924. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  28925. }
  28926. if (material.reflectionFresnelParameters) {
  28927. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  28928. }
  28929. if (material.emissiveTexture) {
  28930. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  28931. }
  28932. if (material.lightmapTexture) {
  28933. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  28934. serializationObject.lightmapThreshold = material.lightmapThreshold;
  28935. }
  28936. if (material.emissiveFresnelParameters) {
  28937. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  28938. }
  28939. if (material.specularTexture) {
  28940. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  28941. }
  28942. if (material.bumpTexture) {
  28943. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  28944. }
  28945. return serializationObject;
  28946. };
  28947. serializeTexture = function (texture) {
  28948. var serializationObject = {};
  28949. if (!texture.name) {
  28950. return null;
  28951. }
  28952. if (texture instanceof BABYLON.CubeTexture) {
  28953. serializationObject.name = texture.name;
  28954. serializationObject.hasAlpha = texture.hasAlpha;
  28955. serializationObject.isCube = true;
  28956. serializationObject.level = texture.level;
  28957. serializationObject.coordinatesMode = texture.coordinatesMode;
  28958. return serializationObject;
  28959. }
  28960. var index;
  28961. if (texture instanceof BABYLON.MirrorTexture) {
  28962. var mirrorTexture = texture;
  28963. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  28964. serializationObject.renderList = [];
  28965. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  28966. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  28967. }
  28968. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  28969. }
  28970. else if (texture instanceof BABYLON.RenderTargetTexture) {
  28971. var renderTargetTexture = texture;
  28972. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  28973. serializationObject.renderList = [];
  28974. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  28975. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  28976. }
  28977. }
  28978. var regularTexture = texture;
  28979. serializationObject.name = texture.name;
  28980. serializationObject.hasAlpha = texture.hasAlpha;
  28981. serializationObject.level = texture.level;
  28982. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  28983. serializationObject.coordinatesMode = texture.coordinatesMode;
  28984. serializationObject.uOffset = regularTexture.uOffset;
  28985. serializationObject.vOffset = regularTexture.vOffset;
  28986. serializationObject.uScale = regularTexture.uScale;
  28987. serializationObject.vScale = regularTexture.vScale;
  28988. serializationObject.uAng = regularTexture.uAng;
  28989. serializationObject.vAng = regularTexture.vAng;
  28990. serializationObject.wAng = regularTexture.wAng;
  28991. serializationObject.wrapU = texture.wrapU;
  28992. serializationObject.wrapV = texture.wrapV;
  28993. // Animations
  28994. appendAnimations(texture, serializationObject);
  28995. return serializationObject;
  28996. };
  28997. var serializeSkeleton = function (skeleton) {
  28998. var serializationObject = {};
  28999. serializationObject.name = skeleton.name;
  29000. serializationObject.id = skeleton.id;
  29001. serializationObject.bones = [];
  29002. for (var index = 0; index < skeleton.bones.length; index++) {
  29003. var bone = skeleton.bones[index];
  29004. var serializedBone = {
  29005. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29006. name: bone.name,
  29007. matrix: bone.getLocalMatrix().toArray()
  29008. };
  29009. serializationObject.bones.push(serializedBone);
  29010. if (bone.animations && bone.animations.length > 0) {
  29011. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29012. }
  29013. }
  29014. return serializationObject;
  29015. };
  29016. var serializeParticleSystem = function (particleSystem) {
  29017. var serializationObject = {};
  29018. serializationObject.emitterId = particleSystem.emitter.id;
  29019. serializationObject.capacity = particleSystem.getCapacity();
  29020. if (particleSystem.particleTexture) {
  29021. serializationObject.textureName = particleSystem.particleTexture.name;
  29022. }
  29023. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29024. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29025. serializationObject.minSize = particleSystem.minSize;
  29026. serializationObject.maxSize = particleSystem.maxSize;
  29027. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29028. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29029. serializationObject.emitRate = particleSystem.emitRate;
  29030. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29031. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29032. serializationObject.gravity = particleSystem.gravity.asArray();
  29033. serializationObject.direction1 = particleSystem.direction1.asArray();
  29034. serializationObject.direction2 = particleSystem.direction2.asArray();
  29035. serializationObject.color1 = particleSystem.color1.asArray();
  29036. serializationObject.color2 = particleSystem.color2.asArray();
  29037. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29038. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29039. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29040. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29041. serializationObject.blendMode = particleSystem.blendMode;
  29042. return serializationObject;
  29043. };
  29044. var serializeLensFlareSystem = function (lensFlareSystem) {
  29045. var serializationObject = {};
  29046. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29047. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29048. serializationObject.flares = [];
  29049. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29050. var flare = lensFlareSystem.lensFlares[index];
  29051. serializationObject.flares.push({
  29052. size: flare.size,
  29053. position: flare.position,
  29054. color: flare.color.asArray(),
  29055. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29056. });
  29057. }
  29058. return serializationObject;
  29059. };
  29060. var serializeShadowGenerator = function (light) {
  29061. var serializationObject = {};
  29062. var shadowGenerator = light.getShadowGenerator();
  29063. serializationObject.lightId = light.id;
  29064. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29065. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29066. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29067. serializationObject.renderList = [];
  29068. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29069. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29070. serializationObject.renderList.push(mesh.id);
  29071. }
  29072. return serializationObject;
  29073. };
  29074. var serializedGeometries = [];
  29075. var serializeVertexData;
  29076. var serializeTorusKnot;
  29077. var serializePlane;
  29078. var serializeGround;
  29079. var serializeTorus;
  29080. var serializeCylinder;
  29081. var serializeSphere;
  29082. var serializeBox;
  29083. var serializeGeometry = function (geometry, serializationGeometries) {
  29084. if (serializedGeometries[geometry.id]) {
  29085. return;
  29086. }
  29087. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29088. serializationGeometries.boxes.push(serializeBox(geometry));
  29089. }
  29090. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29091. serializationGeometries.spheres.push(serializeSphere(geometry));
  29092. }
  29093. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29094. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29095. }
  29096. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29097. serializationGeometries.toruses.push(serializeTorus(geometry));
  29098. }
  29099. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29100. serializationGeometries.grounds.push(serializeGround(geometry));
  29101. }
  29102. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29103. serializationGeometries.planes.push(serializePlane(geometry));
  29104. }
  29105. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29106. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29107. }
  29108. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29109. throw new Error("Unknown primitive type");
  29110. }
  29111. else {
  29112. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29113. }
  29114. serializedGeometries[geometry.id] = true;
  29115. };
  29116. var serializeGeometryBase = function (geometry) {
  29117. var serializationObject = {};
  29118. serializationObject.id = geometry.id;
  29119. if (BABYLON.Tags.HasTags(geometry)) {
  29120. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29121. }
  29122. return serializationObject;
  29123. };
  29124. serializeVertexData = function (vertexData) {
  29125. var serializationObject = serializeGeometryBase(vertexData);
  29126. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29127. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29128. }
  29129. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29130. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29131. }
  29132. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29133. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29134. }
  29135. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29136. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29137. }
  29138. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29139. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29140. }
  29141. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29142. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29143. }
  29144. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29145. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29146. }
  29147. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29148. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29149. }
  29150. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29151. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29152. }
  29153. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29154. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29155. serializationObject.matricesIndices._isExpanded = true;
  29156. }
  29157. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29158. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29159. }
  29160. serializationObject.indices = vertexData.getIndices();
  29161. return serializationObject;
  29162. };
  29163. var serializePrimitive = function (primitive) {
  29164. var serializationObject = serializeGeometryBase(primitive);
  29165. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29166. return serializationObject;
  29167. };
  29168. serializeBox = function (box) {
  29169. var serializationObject = serializePrimitive(box);
  29170. serializationObject.size = box.size;
  29171. return serializationObject;
  29172. };
  29173. serializeSphere = function (sphere) {
  29174. var serializationObject = serializePrimitive(sphere);
  29175. serializationObject.segments = sphere.segments;
  29176. serializationObject.diameter = sphere.diameter;
  29177. return serializationObject;
  29178. };
  29179. serializeCylinder = function (cylinder) {
  29180. var serializationObject = serializePrimitive(cylinder);
  29181. serializationObject.height = cylinder.height;
  29182. serializationObject.diameterTop = cylinder.diameterTop;
  29183. serializationObject.diameterBottom = cylinder.diameterBottom;
  29184. serializationObject.tessellation = cylinder.tessellation;
  29185. return serializationObject;
  29186. };
  29187. serializeTorus = function (torus) {
  29188. var serializationObject = serializePrimitive(torus);
  29189. serializationObject.diameter = torus.diameter;
  29190. serializationObject.thickness = torus.thickness;
  29191. serializationObject.tessellation = torus.tessellation;
  29192. return serializationObject;
  29193. };
  29194. serializeGround = function (ground) {
  29195. var serializationObject = serializePrimitive(ground);
  29196. serializationObject.width = ground.width;
  29197. serializationObject.height = ground.height;
  29198. serializationObject.subdivisions = ground.subdivisions;
  29199. return serializationObject;
  29200. };
  29201. serializePlane = function (plane) {
  29202. var serializationObject = serializePrimitive(plane);
  29203. serializationObject.size = plane.size;
  29204. return serializationObject;
  29205. };
  29206. serializeTorusKnot = function (torusKnot) {
  29207. var serializationObject = serializePrimitive(torusKnot);
  29208. serializationObject.radius = torusKnot.radius;
  29209. serializationObject.tube = torusKnot.tube;
  29210. serializationObject.radialSegments = torusKnot.radialSegments;
  29211. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29212. serializationObject.p = torusKnot.p;
  29213. serializationObject.q = torusKnot.q;
  29214. return serializationObject;
  29215. };
  29216. var serializeMesh = function (mesh, serializationScene) {
  29217. var serializationObject = {};
  29218. serializationObject.name = mesh.name;
  29219. serializationObject.id = mesh.id;
  29220. if (BABYLON.Tags.HasTags(mesh)) {
  29221. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29222. }
  29223. serializationObject.position = mesh.position.asArray();
  29224. if (mesh.rotationQuaternion) {
  29225. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29226. }
  29227. else if (mesh.rotation) {
  29228. serializationObject.rotation = mesh.rotation.asArray();
  29229. }
  29230. serializationObject.scaling = mesh.scaling.asArray();
  29231. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29232. serializationObject.isEnabled = mesh.isEnabled();
  29233. serializationObject.isVisible = mesh.isVisible;
  29234. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29235. serializationObject.pickable = mesh.isPickable;
  29236. serializationObject.receiveShadows = mesh.receiveShadows;
  29237. serializationObject.billboardMode = mesh.billboardMode;
  29238. serializationObject.visibility = mesh.visibility;
  29239. serializationObject.checkCollisions = mesh.checkCollisions;
  29240. // Parent
  29241. if (mesh.parent) {
  29242. serializationObject.parentId = mesh.parent.id;
  29243. }
  29244. // Geometry
  29245. var geometry = mesh._geometry;
  29246. if (geometry) {
  29247. var geometryId = geometry.id;
  29248. serializationObject.geometryId = geometryId;
  29249. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29250. // 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
  29251. serializeGeometry(geometry, serializationScene.geometries);
  29252. }
  29253. // SubMeshes
  29254. serializationObject.subMeshes = [];
  29255. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29256. var subMesh = mesh.subMeshes[subIndex];
  29257. serializationObject.subMeshes.push({
  29258. materialIndex: subMesh.materialIndex,
  29259. verticesStart: subMesh.verticesStart,
  29260. verticesCount: subMesh.verticesCount,
  29261. indexStart: subMesh.indexStart,
  29262. indexCount: subMesh.indexCount
  29263. });
  29264. }
  29265. }
  29266. // Material
  29267. if (mesh.material) {
  29268. serializationObject.materialId = mesh.material.id;
  29269. }
  29270. else {
  29271. mesh.material = null;
  29272. }
  29273. // Skeleton
  29274. if (mesh.skeleton) {
  29275. serializationObject.skeletonId = mesh.skeleton.id;
  29276. }
  29277. // Physics
  29278. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29279. serializationObject.physicsMass = mesh.getPhysicsMass();
  29280. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29281. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29282. switch (mesh.getPhysicsImpostor()) {
  29283. case BABYLON.PhysicsEngine.BoxImpostor:
  29284. serializationObject.physicsImpostor = 1;
  29285. break;
  29286. case BABYLON.PhysicsEngine.SphereImpostor:
  29287. serializationObject.physicsImpostor = 2;
  29288. break;
  29289. }
  29290. }
  29291. // Instances
  29292. serializationObject.instances = [];
  29293. for (var index = 0; index < mesh.instances.length; index++) {
  29294. var instance = mesh.instances[index];
  29295. var serializationInstance = {
  29296. name: instance.name,
  29297. position: instance.position.asArray(),
  29298. rotation: instance.rotation.asArray(),
  29299. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29300. scaling: instance.scaling.asArray()
  29301. };
  29302. serializationObject.instances.push(serializationInstance);
  29303. // Animations
  29304. appendAnimations(instance, serializationInstance);
  29305. }
  29306. // Animations
  29307. appendAnimations(mesh, serializationObject);
  29308. // Layer mask
  29309. serializationObject.layerMask = mesh.layerMask;
  29310. return serializationObject;
  29311. };
  29312. var finalizeSingleMesh = function (mesh, serializationObject) {
  29313. //only works if the mesh is already loaded
  29314. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29315. //serialize material
  29316. if (mesh.material) {
  29317. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29318. serializationObject.materials = serializationObject.materials || [];
  29319. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29320. serializationObject.materials.push(serializeMaterial(mesh.material));
  29321. }
  29322. }
  29323. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29324. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29325. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29326. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  29327. }
  29328. }
  29329. }
  29330. //serialize geometry
  29331. var geometry = mesh._geometry;
  29332. if (geometry) {
  29333. if (!serializationObject.geometries) {
  29334. serializationObject.geometries = {};
  29335. serializationObject.geometries.boxes = [];
  29336. serializationObject.geometries.spheres = [];
  29337. serializationObject.geometries.cylinders = [];
  29338. serializationObject.geometries.toruses = [];
  29339. serializationObject.geometries.grounds = [];
  29340. serializationObject.geometries.planes = [];
  29341. serializationObject.geometries.torusKnots = [];
  29342. serializationObject.geometries.vertexData = [];
  29343. }
  29344. serializeGeometry(geometry, serializationObject.geometries);
  29345. }
  29346. // Skeletons
  29347. if (mesh.skeleton) {
  29348. serializationObject.skeletons = serializationObject.skeletons || [];
  29349. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  29350. }
  29351. //serialize the actual mesh
  29352. serializationObject.meshes = serializationObject.meshes || [];
  29353. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29354. }
  29355. };
  29356. var SceneSerializer = (function () {
  29357. function SceneSerializer() {
  29358. }
  29359. SceneSerializer.Serialize = function (scene) {
  29360. var serializationObject = {};
  29361. // Scene
  29362. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  29363. serializationObject.autoClear = scene.autoClear;
  29364. serializationObject.clearColor = scene.clearColor.asArray();
  29365. serializationObject.ambientColor = scene.ambientColor.asArray();
  29366. serializationObject.gravity = scene.gravity.asArray();
  29367. // Fog
  29368. if (scene.fogMode && scene.fogMode !== 0) {
  29369. serializationObject.fogMode = scene.fogMode;
  29370. serializationObject.fogColor = scene.fogColor.asArray();
  29371. serializationObject.fogStart = scene.fogStart;
  29372. serializationObject.fogEnd = scene.fogEnd;
  29373. serializationObject.fogDensity = scene.fogDensity;
  29374. }
  29375. // Lights
  29376. serializationObject.lights = [];
  29377. var index;
  29378. var light;
  29379. for (index = 0; index < scene.lights.length; index++) {
  29380. light = scene.lights[index];
  29381. serializationObject.lights.push(serializeLight(light));
  29382. }
  29383. // Cameras
  29384. serializationObject.cameras = [];
  29385. for (index = 0; index < scene.cameras.length; index++) {
  29386. var camera = scene.cameras[index];
  29387. serializationObject.cameras.push(serializeCamera(camera));
  29388. }
  29389. if (scene.activeCamera) {
  29390. serializationObject.activeCameraID = scene.activeCamera.id;
  29391. }
  29392. // Materials
  29393. serializationObject.materials = [];
  29394. serializationObject.multiMaterials = [];
  29395. var material;
  29396. for (index = 0; index < scene.materials.length; index++) {
  29397. material = scene.materials[index];
  29398. serializationObject.materials.push(serializeMaterial(material));
  29399. }
  29400. // MultiMaterials
  29401. serializationObject.multiMaterials = [];
  29402. for (index = 0; index < scene.multiMaterials.length; index++) {
  29403. var multiMaterial = scene.multiMaterials[index];
  29404. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  29405. }
  29406. for (index = 0; index < scene.materials.length; index++) {
  29407. material = scene.materials[index];
  29408. if (material instanceof BABYLON.StandardMaterial) {
  29409. serializationObject.materials.push(serializeMaterial(material));
  29410. }
  29411. else if (material instanceof BABYLON.MultiMaterial) {
  29412. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  29413. }
  29414. }
  29415. // Skeletons
  29416. serializationObject.skeletons = [];
  29417. for (index = 0; index < scene.skeletons.length; index++) {
  29418. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  29419. }
  29420. // Geometries
  29421. serializationObject.geometries = {};
  29422. serializationObject.geometries.boxes = [];
  29423. serializationObject.geometries.spheres = [];
  29424. serializationObject.geometries.cylinders = [];
  29425. serializationObject.geometries.toruses = [];
  29426. serializationObject.geometries.grounds = [];
  29427. serializationObject.geometries.planes = [];
  29428. serializationObject.geometries.torusKnots = [];
  29429. serializationObject.geometries.vertexData = [];
  29430. serializedGeometries = [];
  29431. var geometries = scene.getGeometries();
  29432. for (index = 0; index < geometries.length; index++) {
  29433. var geometry = geometries[index];
  29434. if (geometry.isReady()) {
  29435. serializeGeometry(geometry, serializationObject.geometries);
  29436. }
  29437. }
  29438. // Meshes
  29439. serializationObject.meshes = [];
  29440. for (index = 0; index < scene.meshes.length; index++) {
  29441. var abstractMesh = scene.meshes[index];
  29442. if (abstractMesh instanceof BABYLON.Mesh) {
  29443. var mesh = abstractMesh;
  29444. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29445. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29446. }
  29447. }
  29448. }
  29449. // Particles Systems
  29450. serializationObject.particleSystems = [];
  29451. for (index = 0; index < scene.particleSystems.length; index++) {
  29452. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  29453. }
  29454. // Lens flares
  29455. serializationObject.lensFlareSystems = [];
  29456. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  29457. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  29458. }
  29459. // Shadows
  29460. serializationObject.shadowGenerators = [];
  29461. for (index = 0; index < scene.lights.length; index++) {
  29462. light = scene.lights[index];
  29463. if (light.getShadowGenerator()) {
  29464. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  29465. }
  29466. }
  29467. return serializationObject;
  29468. };
  29469. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  29470. if (withParents === void 0) { withParents = false; }
  29471. if (withChildren === void 0) { withChildren = false; }
  29472. var serializationObject = {};
  29473. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  29474. if (withParents || withChildren) {
  29475. //deliberate for loop! not for each, appended should be processed as well.
  29476. for (var i = 0; i < toSerialize.length; ++i) {
  29477. if (withChildren) {
  29478. toSerialize[i].getDescendants().forEach(function (node) {
  29479. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  29480. toSerialize.push(node);
  29481. }
  29482. });
  29483. }
  29484. //make sure the array doesn't contain the object already
  29485. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  29486. toSerialize.push(toSerialize[i].parent);
  29487. }
  29488. }
  29489. }
  29490. toSerialize.forEach(function (mesh) {
  29491. finalizeSingleMesh(mesh, serializationObject);
  29492. });
  29493. return serializationObject;
  29494. };
  29495. return SceneSerializer;
  29496. })();
  29497. BABYLON.SceneSerializer = SceneSerializer;
  29498. })(BABYLON || (BABYLON = {}));
  29499. var BABYLON;
  29500. (function (BABYLON) {
  29501. // Unique ID when we import meshes from Babylon to CSG
  29502. var currentCSGMeshId = 0;
  29503. // # class Vertex
  29504. // Represents a vertex of a polygon. Use your own vertex class instead of this
  29505. // one to provide additional features like texture coordinates and vertex
  29506. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  29507. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  29508. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  29509. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  29510. // is not used anywhere else.
  29511. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  29512. var Vertex = (function () {
  29513. function Vertex(pos, normal, uv) {
  29514. this.pos = pos;
  29515. this.normal = normal;
  29516. this.uv = uv;
  29517. }
  29518. Vertex.prototype.clone = function () {
  29519. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  29520. };
  29521. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  29522. // orientation of a polygon is flipped.
  29523. Vertex.prototype.flip = function () {
  29524. this.normal = this.normal.scale(-1);
  29525. };
  29526. // Create a new vertex between this vertex and `other` by linearly
  29527. // interpolating all properties using a parameter of `t`. Subclasses should
  29528. // override this to interpolate additional properties.
  29529. Vertex.prototype.interpolate = function (other, t) {
  29530. 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));
  29531. };
  29532. return Vertex;
  29533. })();
  29534. // # class Plane
  29535. // Represents a plane in 3D space.
  29536. var Plane = (function () {
  29537. function Plane(normal, w) {
  29538. this.normal = normal;
  29539. this.w = w;
  29540. }
  29541. Plane.FromPoints = function (a, b, c) {
  29542. var v0 = c.subtract(a);
  29543. var v1 = b.subtract(a);
  29544. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  29545. return null;
  29546. }
  29547. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  29548. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  29549. };
  29550. Plane.prototype.clone = function () {
  29551. return new Plane(this.normal.clone(), this.w);
  29552. };
  29553. Plane.prototype.flip = function () {
  29554. this.normal.scaleInPlace(-1);
  29555. this.w = -this.w;
  29556. };
  29557. // Split `polygon` by this plane if needed, then put the polygon or polygon
  29558. // fragments in the appropriate lists. Coplanar polygons go into either
  29559. // `coplanarFront` or `coplanarBack` depending on their orientation with
  29560. // respect to this plane. Polygons in front or in back of this plane go into
  29561. // either `front` or `back`.
  29562. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  29563. var COPLANAR = 0;
  29564. var FRONT = 1;
  29565. var BACK = 2;
  29566. var SPANNING = 3;
  29567. // Classify each point as well as the entire polygon into one of the above
  29568. // four classes.
  29569. var polygonType = 0;
  29570. var types = [];
  29571. var i;
  29572. var t;
  29573. for (i = 0; i < polygon.vertices.length; i++) {
  29574. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  29575. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  29576. polygonType |= type;
  29577. types.push(type);
  29578. }
  29579. // Put the polygon in the correct list, splitting it when necessary.
  29580. switch (polygonType) {
  29581. case COPLANAR:
  29582. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  29583. break;
  29584. case FRONT:
  29585. front.push(polygon);
  29586. break;
  29587. case BACK:
  29588. back.push(polygon);
  29589. break;
  29590. case SPANNING:
  29591. var f = [], b = [];
  29592. for (i = 0; i < polygon.vertices.length; i++) {
  29593. var j = (i + 1) % polygon.vertices.length;
  29594. var ti = types[i], tj = types[j];
  29595. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  29596. if (ti !== BACK)
  29597. f.push(vi);
  29598. if (ti !== FRONT)
  29599. b.push(ti !== BACK ? vi.clone() : vi);
  29600. if ((ti | tj) === SPANNING) {
  29601. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  29602. var v = vi.interpolate(vj, t);
  29603. f.push(v);
  29604. b.push(v.clone());
  29605. }
  29606. }
  29607. var poly;
  29608. if (f.length >= 3) {
  29609. poly = new Polygon(f, polygon.shared);
  29610. if (poly.plane)
  29611. front.push(poly);
  29612. }
  29613. if (b.length >= 3) {
  29614. poly = new Polygon(b, polygon.shared);
  29615. if (poly.plane)
  29616. back.push(poly);
  29617. }
  29618. break;
  29619. }
  29620. };
  29621. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  29622. // point is on the plane.
  29623. Plane.EPSILON = 1e-5;
  29624. return Plane;
  29625. })();
  29626. // # class Polygon
  29627. // Represents a convex polygon. The vertices used to initialize a polygon must
  29628. // be coplanar and form a convex loop.
  29629. //
  29630. // Each convex polygon has a `shared` property, which is shared between all
  29631. // polygons that are clones of each other or were split from the same polygon.
  29632. // This can be used to define per-polygon properties (such as surface color).
  29633. var Polygon = (function () {
  29634. function Polygon(vertices, shared) {
  29635. this.vertices = vertices;
  29636. this.shared = shared;
  29637. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  29638. }
  29639. Polygon.prototype.clone = function () {
  29640. var vertices = this.vertices.map(function (v) { return v.clone(); });
  29641. return new Polygon(vertices, this.shared);
  29642. };
  29643. Polygon.prototype.flip = function () {
  29644. this.vertices.reverse().map(function (v) { v.flip(); });
  29645. this.plane.flip();
  29646. };
  29647. return Polygon;
  29648. })();
  29649. // # class Node
  29650. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  29651. // by picking a polygon to split along. That polygon (and all other coplanar
  29652. // polygons) are added directly to that node and the other polygons are added to
  29653. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  29654. // no distinction between internal and leaf nodes.
  29655. var Node = (function () {
  29656. function Node(polygons) {
  29657. this.plane = null;
  29658. this.front = null;
  29659. this.back = null;
  29660. this.polygons = [];
  29661. if (polygons) {
  29662. this.build(polygons);
  29663. }
  29664. }
  29665. Node.prototype.clone = function () {
  29666. var node = new Node();
  29667. node.plane = this.plane && this.plane.clone();
  29668. node.front = this.front && this.front.clone();
  29669. node.back = this.back && this.back.clone();
  29670. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  29671. return node;
  29672. };
  29673. // Convert solid space to empty space and empty space to solid space.
  29674. Node.prototype.invert = function () {
  29675. for (var i = 0; i < this.polygons.length; i++) {
  29676. this.polygons[i].flip();
  29677. }
  29678. if (this.plane) {
  29679. this.plane.flip();
  29680. }
  29681. if (this.front) {
  29682. this.front.invert();
  29683. }
  29684. if (this.back) {
  29685. this.back.invert();
  29686. }
  29687. var temp = this.front;
  29688. this.front = this.back;
  29689. this.back = temp;
  29690. };
  29691. // Recursively remove all polygons in `polygons` that are inside this BSP
  29692. // tree.
  29693. Node.prototype.clipPolygons = function (polygons) {
  29694. if (!this.plane)
  29695. return polygons.slice();
  29696. var front = [], back = [];
  29697. for (var i = 0; i < polygons.length; i++) {
  29698. this.plane.splitPolygon(polygons[i], front, back, front, back);
  29699. }
  29700. if (this.front) {
  29701. front = this.front.clipPolygons(front);
  29702. }
  29703. if (this.back) {
  29704. back = this.back.clipPolygons(back);
  29705. }
  29706. else {
  29707. back = [];
  29708. }
  29709. return front.concat(back);
  29710. };
  29711. // Remove all polygons in this BSP tree that are inside the other BSP tree
  29712. // `bsp`.
  29713. Node.prototype.clipTo = function (bsp) {
  29714. this.polygons = bsp.clipPolygons(this.polygons);
  29715. if (this.front)
  29716. this.front.clipTo(bsp);
  29717. if (this.back)
  29718. this.back.clipTo(bsp);
  29719. };
  29720. // Return a list of all polygons in this BSP tree.
  29721. Node.prototype.allPolygons = function () {
  29722. var polygons = this.polygons.slice();
  29723. if (this.front)
  29724. polygons = polygons.concat(this.front.allPolygons());
  29725. if (this.back)
  29726. polygons = polygons.concat(this.back.allPolygons());
  29727. return polygons;
  29728. };
  29729. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  29730. // new polygons are filtered down to the bottom of the tree and become new
  29731. // nodes there. Each set of polygons is partitioned using the first polygon
  29732. // (no heuristic is used to pick a good split).
  29733. Node.prototype.build = function (polygons) {
  29734. if (!polygons.length)
  29735. return;
  29736. if (!this.plane)
  29737. this.plane = polygons[0].plane.clone();
  29738. var front = [], back = [];
  29739. for (var i = 0; i < polygons.length; i++) {
  29740. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  29741. }
  29742. if (front.length) {
  29743. if (!this.front)
  29744. this.front = new Node();
  29745. this.front.build(front);
  29746. }
  29747. if (back.length) {
  29748. if (!this.back)
  29749. this.back = new Node();
  29750. this.back.build(back);
  29751. }
  29752. };
  29753. return Node;
  29754. })();
  29755. var CSG = (function () {
  29756. function CSG() {
  29757. this.polygons = new Array();
  29758. }
  29759. // Convert BABYLON.Mesh to BABYLON.CSG
  29760. CSG.FromMesh = function (mesh) {
  29761. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  29762. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  29763. if (mesh instanceof BABYLON.Mesh) {
  29764. mesh.computeWorldMatrix(true);
  29765. matrix = mesh.getWorldMatrix();
  29766. meshPosition = mesh.position.clone();
  29767. meshRotation = mesh.rotation.clone();
  29768. if (mesh.rotationQuaternion) {
  29769. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  29770. }
  29771. meshScaling = mesh.scaling.clone();
  29772. }
  29773. else {
  29774. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  29775. }
  29776. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29777. var subMeshes = mesh.subMeshes;
  29778. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  29779. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  29780. vertices = [];
  29781. for (var j = 0; j < 3; j++) {
  29782. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  29783. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  29784. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  29785. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  29786. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  29787. vertex = new Vertex(position, normal, uv);
  29788. vertices.push(vertex);
  29789. }
  29790. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  29791. // To handle the case of degenerated triangle
  29792. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  29793. if (polygon.plane)
  29794. polygons.push(polygon);
  29795. }
  29796. }
  29797. var csg = CSG.FromPolygons(polygons);
  29798. csg.matrix = matrix;
  29799. csg.position = meshPosition;
  29800. csg.rotation = meshRotation;
  29801. csg.scaling = meshScaling;
  29802. csg.rotationQuaternion = meshRotationQuaternion;
  29803. currentCSGMeshId++;
  29804. return csg;
  29805. };
  29806. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  29807. CSG.FromPolygons = function (polygons) {
  29808. var csg = new CSG();
  29809. csg.polygons = polygons;
  29810. return csg;
  29811. };
  29812. CSG.prototype.clone = function () {
  29813. var csg = new CSG();
  29814. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  29815. csg.copyTransformAttributes(this);
  29816. return csg;
  29817. };
  29818. CSG.prototype.toPolygons = function () {
  29819. return this.polygons;
  29820. };
  29821. CSG.prototype.union = function (csg) {
  29822. var a = new Node(this.clone().polygons);
  29823. var b = new Node(csg.clone().polygons);
  29824. a.clipTo(b);
  29825. b.clipTo(a);
  29826. b.invert();
  29827. b.clipTo(a);
  29828. b.invert();
  29829. a.build(b.allPolygons());
  29830. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  29831. };
  29832. CSG.prototype.unionInPlace = function (csg) {
  29833. var a = new Node(this.polygons);
  29834. var b = new Node(csg.polygons);
  29835. a.clipTo(b);
  29836. b.clipTo(a);
  29837. b.invert();
  29838. b.clipTo(a);
  29839. b.invert();
  29840. a.build(b.allPolygons());
  29841. this.polygons = a.allPolygons();
  29842. };
  29843. CSG.prototype.subtract = function (csg) {
  29844. var a = new Node(this.clone().polygons);
  29845. var b = new Node(csg.clone().polygons);
  29846. a.invert();
  29847. a.clipTo(b);
  29848. b.clipTo(a);
  29849. b.invert();
  29850. b.clipTo(a);
  29851. b.invert();
  29852. a.build(b.allPolygons());
  29853. a.invert();
  29854. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  29855. };
  29856. CSG.prototype.subtractInPlace = function (csg) {
  29857. var a = new Node(this.polygons);
  29858. var b = new Node(csg.polygons);
  29859. a.invert();
  29860. a.clipTo(b);
  29861. b.clipTo(a);
  29862. b.invert();
  29863. b.clipTo(a);
  29864. b.invert();
  29865. a.build(b.allPolygons());
  29866. a.invert();
  29867. this.polygons = a.allPolygons();
  29868. };
  29869. CSG.prototype.intersect = function (csg) {
  29870. var a = new Node(this.clone().polygons);
  29871. var b = new Node(csg.clone().polygons);
  29872. a.invert();
  29873. b.clipTo(a);
  29874. b.invert();
  29875. a.clipTo(b);
  29876. b.clipTo(a);
  29877. a.build(b.allPolygons());
  29878. a.invert();
  29879. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  29880. };
  29881. CSG.prototype.intersectInPlace = function (csg) {
  29882. var a = new Node(this.polygons);
  29883. var b = new Node(csg.polygons);
  29884. a.invert();
  29885. b.clipTo(a);
  29886. b.invert();
  29887. a.clipTo(b);
  29888. b.clipTo(a);
  29889. a.build(b.allPolygons());
  29890. a.invert();
  29891. this.polygons = a.allPolygons();
  29892. };
  29893. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  29894. // not modified.
  29895. CSG.prototype.inverse = function () {
  29896. var csg = this.clone();
  29897. csg.inverseInPlace();
  29898. return csg;
  29899. };
  29900. CSG.prototype.inverseInPlace = function () {
  29901. this.polygons.map(function (p) { p.flip(); });
  29902. };
  29903. // This is used to keep meshes transformations so they can be restored
  29904. // when we build back a Babylon Mesh
  29905. // NB : All CSG operations are performed in world coordinates
  29906. CSG.prototype.copyTransformAttributes = function (csg) {
  29907. this.matrix = csg.matrix;
  29908. this.position = csg.position;
  29909. this.rotation = csg.rotation;
  29910. this.scaling = csg.scaling;
  29911. this.rotationQuaternion = csg.rotationQuaternion;
  29912. return this;
  29913. };
  29914. // Build Raw mesh from CSG
  29915. // Coordinates here are in world space
  29916. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  29917. var matrix = this.matrix.clone();
  29918. matrix.invert();
  29919. 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;
  29920. if (keepSubMeshes) {
  29921. // Sort Polygons, since subMeshes are indices range
  29922. polygons.sort(function (a, b) {
  29923. if (a.shared.meshId === b.shared.meshId) {
  29924. return a.shared.subMeshId - b.shared.subMeshId;
  29925. }
  29926. else {
  29927. return a.shared.meshId - b.shared.meshId;
  29928. }
  29929. });
  29930. }
  29931. for (var i = 0, il = polygons.length; i < il; i++) {
  29932. polygon = polygons[i];
  29933. // Building SubMeshes
  29934. if (!subMesh_dict[polygon.shared.meshId]) {
  29935. subMesh_dict[polygon.shared.meshId] = {};
  29936. }
  29937. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  29938. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  29939. indexStart: +Infinity,
  29940. indexEnd: -Infinity,
  29941. materialIndex: polygon.shared.materialIndex
  29942. };
  29943. }
  29944. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  29945. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  29946. polygonIndices[0] = 0;
  29947. polygonIndices[1] = j - 1;
  29948. polygonIndices[2] = j;
  29949. for (var k = 0; k < 3; k++) {
  29950. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  29951. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  29952. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  29953. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  29954. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  29955. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  29956. // Check if 2 points can be merged
  29957. if (!(typeof vertex_idx !== 'undefined' &&
  29958. normals[vertex_idx * 3] === localNormal.x &&
  29959. normals[vertex_idx * 3 + 1] === localNormal.y &&
  29960. normals[vertex_idx * 3 + 2] === localNormal.z &&
  29961. uvs[vertex_idx * 2] === uv.x &&
  29962. uvs[vertex_idx * 2 + 1] === uv.y)) {
  29963. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  29964. uvs.push(uv.x, uv.y);
  29965. normals.push(normal.x, normal.y, normal.z);
  29966. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  29967. }
  29968. indices.push(vertex_idx);
  29969. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  29970. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  29971. currentIndex++;
  29972. }
  29973. }
  29974. }
  29975. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  29976. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29977. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  29978. mesh.setIndices(indices);
  29979. if (keepSubMeshes) {
  29980. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  29981. var materialIndexOffset = 0, materialMaxIndex;
  29982. mesh.subMeshes = new Array();
  29983. for (var m in subMesh_dict) {
  29984. materialMaxIndex = -1;
  29985. for (var sm in subMesh_dict[m]) {
  29986. subMesh_obj = subMesh_dict[m][sm];
  29987. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  29988. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  29989. }
  29990. materialIndexOffset += ++materialMaxIndex;
  29991. }
  29992. }
  29993. return mesh;
  29994. };
  29995. // Build Mesh from CSG taking material and transforms into account
  29996. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  29997. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  29998. mesh.material = material;
  29999. mesh.position.copyFrom(this.position);
  30000. mesh.rotation.copyFrom(this.rotation);
  30001. if (this.rotationQuaternion) {
  30002. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30003. }
  30004. mesh.scaling.copyFrom(this.scaling);
  30005. mesh.computeWorldMatrix(true);
  30006. return mesh;
  30007. };
  30008. return CSG;
  30009. })();
  30010. BABYLON.CSG = CSG;
  30011. })(BABYLON || (BABYLON = {}));
  30012. var BABYLON;
  30013. (function (BABYLON) {
  30014. var VRDistortionCorrectionPostProcess = (function (_super) {
  30015. __extends(VRDistortionCorrectionPostProcess, _super);
  30016. //ANY
  30017. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30018. var _this = this;
  30019. _super.call(this, name, "vrDistortionCorrection", [
  30020. 'LensCenter',
  30021. 'Scale',
  30022. 'ScaleIn',
  30023. 'HmdWarpParam'
  30024. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30025. this._isRightEye = isRightEye;
  30026. this._distortionFactors = vrMetrics.distortionK;
  30027. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30028. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30029. this.onSizeChanged = function () {
  30030. _this.aspectRatio = _this.width * .5 / _this.height;
  30031. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30032. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30033. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30034. };
  30035. this.onApply = function (effect) {
  30036. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30037. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30038. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30039. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30040. };
  30041. }
  30042. return VRDistortionCorrectionPostProcess;
  30043. })(BABYLON.PostProcess);
  30044. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30045. })(BABYLON || (BABYLON = {}));
  30046. // Mainly based on these 2 articles :
  30047. // 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
  30048. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30049. var BABYLON;
  30050. (function (BABYLON) {
  30051. (function (JoystickAxis) {
  30052. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30053. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30054. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30055. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30056. var JoystickAxis = BABYLON.JoystickAxis;
  30057. var VirtualJoystick = (function () {
  30058. function VirtualJoystick(leftJoystick) {
  30059. var _this = this;
  30060. if (leftJoystick) {
  30061. this._leftJoystick = true;
  30062. }
  30063. else {
  30064. this._leftJoystick = false;
  30065. }
  30066. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30067. VirtualJoystick._globalJoystickIndex++;
  30068. // By default left & right arrow keys are moving the X
  30069. // and up & down keys are moving the Y
  30070. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30071. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30072. this.reverseLeftRight = false;
  30073. this.reverseUpDown = false;
  30074. // collections of pointers
  30075. this._touches = new BABYLON.SmartCollection();
  30076. this.deltaPosition = BABYLON.Vector3.Zero();
  30077. this._joystickSensibility = 25;
  30078. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30079. this._rotationSpeed = 25;
  30080. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30081. this._rotateOnAxisRelativeToMesh = false;
  30082. this._onResize = function (evt) {
  30083. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30084. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30085. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30086. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30087. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30088. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30089. };
  30090. // injecting a canvas element on top of the canvas 3D game
  30091. if (!VirtualJoystick.vjCanvas) {
  30092. window.addEventListener("resize", this._onResize, false);
  30093. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30094. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30095. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30096. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30097. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30098. VirtualJoystick.vjCanvas.style.width = "100%";
  30099. VirtualJoystick.vjCanvas.style.height = "100%";
  30100. VirtualJoystick.vjCanvas.style.position = "absolute";
  30101. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30102. VirtualJoystick.vjCanvas.style.top = "0px";
  30103. VirtualJoystick.vjCanvas.style.left = "0px";
  30104. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30105. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30106. // Support for jQuery PEP polyfill
  30107. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30108. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30109. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30110. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30111. document.body.appendChild(VirtualJoystick.vjCanvas);
  30112. }
  30113. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30114. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30115. this.pressed = false;
  30116. // default joystick color
  30117. this._joystickColor = "cyan";
  30118. this._joystickPointerID = -1;
  30119. // current joystick position
  30120. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30121. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30122. // origin joystick position
  30123. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30124. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30125. this._onPointerDownHandlerRef = function (evt) {
  30126. _this._onPointerDown(evt);
  30127. };
  30128. this._onPointerMoveHandlerRef = function (evt) {
  30129. _this._onPointerMove(evt);
  30130. };
  30131. this._onPointerOutHandlerRef = function (evt) {
  30132. _this._onPointerUp(evt);
  30133. };
  30134. this._onPointerUpHandlerRef = function (evt) {
  30135. _this._onPointerUp(evt);
  30136. };
  30137. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30138. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30139. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30140. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30141. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30142. evt.preventDefault(); // Disables system menu
  30143. }, false);
  30144. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30145. }
  30146. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30147. this._joystickSensibility = newJoystickSensibility;
  30148. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30149. };
  30150. VirtualJoystick.prototype._onPointerDown = function (e) {
  30151. var positionOnScreenCondition;
  30152. e.preventDefault();
  30153. if (this._leftJoystick === true) {
  30154. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30155. }
  30156. else {
  30157. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30158. }
  30159. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30160. // First contact will be dedicated to the virtual joystick
  30161. this._joystickPointerID = e.pointerId;
  30162. this._joystickPointerStartPos.x = e.clientX;
  30163. this._joystickPointerStartPos.y = e.clientY;
  30164. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30165. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30166. this._deltaJoystickVector.x = 0;
  30167. this._deltaJoystickVector.y = 0;
  30168. this.pressed = true;
  30169. this._touches.add(e.pointerId.toString(), e);
  30170. }
  30171. else {
  30172. // You can only trigger the action buttons with a joystick declared
  30173. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30174. this._action();
  30175. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30176. }
  30177. }
  30178. };
  30179. VirtualJoystick.prototype._onPointerMove = function (e) {
  30180. // If the current pointer is the one associated to the joystick (first touch contact)
  30181. if (this._joystickPointerID == e.pointerId) {
  30182. this._joystickPointerPos.x = e.clientX;
  30183. this._joystickPointerPos.y = e.clientY;
  30184. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30185. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30186. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30187. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30188. switch (this._axisTargetedByLeftAndRight) {
  30189. case JoystickAxis.X:
  30190. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30191. break;
  30192. case JoystickAxis.Y:
  30193. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30194. break;
  30195. case JoystickAxis.Z:
  30196. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30197. break;
  30198. }
  30199. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30200. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30201. switch (this._axisTargetedByUpAndDown) {
  30202. case JoystickAxis.X:
  30203. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30204. break;
  30205. case JoystickAxis.Y:
  30206. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30207. break;
  30208. case JoystickAxis.Z:
  30209. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30210. break;
  30211. }
  30212. }
  30213. else {
  30214. if (this._touches.item(e.pointerId.toString())) {
  30215. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30216. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30217. }
  30218. }
  30219. };
  30220. VirtualJoystick.prototype._onPointerUp = function (e) {
  30221. if (this._joystickPointerID == e.pointerId) {
  30222. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30223. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30224. this._joystickPointerID = -1;
  30225. this.pressed = false;
  30226. }
  30227. else {
  30228. var touch = this._touches.item(e.pointerId.toString());
  30229. if (touch) {
  30230. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30231. }
  30232. }
  30233. this._deltaJoystickVector.x = 0;
  30234. this._deltaJoystickVector.y = 0;
  30235. this._touches.remove(e.pointerId.toString());
  30236. };
  30237. /**
  30238. * Change the color of the virtual joystick
  30239. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30240. */
  30241. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30242. this._joystickColor = newColor;
  30243. };
  30244. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30245. this._action = action;
  30246. };
  30247. // Define which axis you'd like to control for left & right
  30248. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30249. switch (axis) {
  30250. case JoystickAxis.X:
  30251. case JoystickAxis.Y:
  30252. case JoystickAxis.Z:
  30253. this._axisTargetedByLeftAndRight = axis;
  30254. break;
  30255. default:
  30256. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30257. break;
  30258. }
  30259. };
  30260. // Define which axis you'd like to control for up & down
  30261. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30262. switch (axis) {
  30263. case JoystickAxis.X:
  30264. case JoystickAxis.Y:
  30265. case JoystickAxis.Z:
  30266. this._axisTargetedByUpAndDown = axis;
  30267. break;
  30268. default:
  30269. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30270. break;
  30271. }
  30272. };
  30273. VirtualJoystick.prototype._clearCanvas = function () {
  30274. if (this._leftJoystick) {
  30275. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30276. }
  30277. else {
  30278. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30279. }
  30280. };
  30281. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30282. var _this = this;
  30283. if (this.pressed) {
  30284. this._touches.forEach(function (touch) {
  30285. if (touch.pointerId === _this._joystickPointerID) {
  30286. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30287. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30288. VirtualJoystick.vjCanvasContext.beginPath();
  30289. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30290. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30291. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30292. VirtualJoystick.vjCanvasContext.stroke();
  30293. VirtualJoystick.vjCanvasContext.closePath();
  30294. VirtualJoystick.vjCanvasContext.beginPath();
  30295. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30296. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30297. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30298. VirtualJoystick.vjCanvasContext.stroke();
  30299. VirtualJoystick.vjCanvasContext.closePath();
  30300. VirtualJoystick.vjCanvasContext.beginPath();
  30301. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30302. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30303. VirtualJoystick.vjCanvasContext.stroke();
  30304. VirtualJoystick.vjCanvasContext.closePath();
  30305. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30306. }
  30307. else {
  30308. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30309. VirtualJoystick.vjCanvasContext.beginPath();
  30310. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30311. VirtualJoystick.vjCanvasContext.beginPath();
  30312. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30313. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30314. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30315. VirtualJoystick.vjCanvasContext.stroke();
  30316. VirtualJoystick.vjCanvasContext.closePath();
  30317. touch.prevX = touch.x;
  30318. touch.prevY = touch.y;
  30319. }
  30320. ;
  30321. });
  30322. }
  30323. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30324. };
  30325. VirtualJoystick.prototype.releaseCanvas = function () {
  30326. if (VirtualJoystick.vjCanvas) {
  30327. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30328. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30329. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30330. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30331. window.removeEventListener("resize", this._onResize);
  30332. document.body.removeChild(VirtualJoystick.vjCanvas);
  30333. VirtualJoystick.vjCanvas = null;
  30334. }
  30335. };
  30336. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30337. VirtualJoystick._globalJoystickIndex = 0;
  30338. return VirtualJoystick;
  30339. })();
  30340. BABYLON.VirtualJoystick = VirtualJoystick;
  30341. })(BABYLON || (BABYLON = {}));
  30342. var BABYLON;
  30343. (function (BABYLON) {
  30344. // We're mainly based on the logic defined into the FreeCamera code
  30345. var VirtualJoysticksCamera = (function (_super) {
  30346. __extends(VirtualJoysticksCamera, _super);
  30347. function VirtualJoysticksCamera(name, position, scene) {
  30348. _super.call(this, name, position, scene);
  30349. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30350. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30351. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30352. this._leftjoystick.setJoystickSensibility(0.15);
  30353. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30354. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30355. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30356. this._rightjoystick.reverseUpDown = true;
  30357. this._rightjoystick.setJoystickSensibility(0.05);
  30358. this._rightjoystick.setJoystickColor("yellow");
  30359. }
  30360. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  30361. return this._leftjoystick;
  30362. };
  30363. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  30364. return this._rightjoystick;
  30365. };
  30366. VirtualJoysticksCamera.prototype._checkInputs = function () {
  30367. var speed = this._computeLocalCameraSpeed() * 50;
  30368. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  30369. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  30370. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  30371. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  30372. if (!this._leftjoystick.pressed) {
  30373. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  30374. }
  30375. if (!this._rightjoystick.pressed) {
  30376. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  30377. }
  30378. _super.prototype._checkInputs.call(this);
  30379. };
  30380. VirtualJoysticksCamera.prototype.dispose = function () {
  30381. this._leftjoystick.releaseCanvas();
  30382. _super.prototype.dispose.call(this);
  30383. };
  30384. return VirtualJoysticksCamera;
  30385. })(BABYLON.FreeCamera);
  30386. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  30387. })(BABYLON || (BABYLON = {}));
  30388. var BABYLON;
  30389. (function (BABYLON) {
  30390. var AnaglyphPostProcess = (function (_super) {
  30391. __extends(AnaglyphPostProcess, _super);
  30392. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30393. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  30394. }
  30395. return AnaglyphPostProcess;
  30396. })(BABYLON.PostProcess);
  30397. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  30398. })(BABYLON || (BABYLON = {}));
  30399. var BABYLON;
  30400. (function (BABYLON) {
  30401. var OutlineRenderer = (function () {
  30402. function OutlineRenderer(scene) {
  30403. this._scene = scene;
  30404. }
  30405. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  30406. var _this = this;
  30407. if (useOverlay === void 0) { useOverlay = false; }
  30408. var scene = this._scene;
  30409. var engine = this._scene.getEngine();
  30410. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  30411. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  30412. return;
  30413. }
  30414. var mesh = subMesh.getRenderingMesh();
  30415. var material = subMesh.getMaterial();
  30416. engine.enableEffect(this._effect);
  30417. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  30418. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  30419. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30420. // Bones
  30421. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30422. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30423. }
  30424. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  30425. // Alpha test
  30426. if (material && material.needAlphaTesting()) {
  30427. var alphaTexture = material.getAlphaTestTexture();
  30428. this._effect.setTexture("diffuseSampler", alphaTexture);
  30429. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30430. }
  30431. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  30432. };
  30433. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  30434. var defines = [];
  30435. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  30436. var mesh = subMesh.getMesh();
  30437. var material = subMesh.getMaterial();
  30438. // Alpha test
  30439. if (material && material.needAlphaTesting()) {
  30440. defines.push("#define ALPHATEST");
  30441. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30442. attribs.push(BABYLON.VertexBuffer.UVKind);
  30443. defines.push("#define UV1");
  30444. }
  30445. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30446. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30447. defines.push("#define UV2");
  30448. }
  30449. }
  30450. // Bones
  30451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30454. defines.push("#define BONES");
  30455. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30456. }
  30457. // Instances
  30458. if (useInstances) {
  30459. defines.push("#define INSTANCES");
  30460. attribs.push("world0");
  30461. attribs.push("world1");
  30462. attribs.push("world2");
  30463. attribs.push("world3");
  30464. }
  30465. // Get correct effect
  30466. var join = defines.join("\n");
  30467. if (this._cachedDefines !== join) {
  30468. this._cachedDefines = join;
  30469. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  30470. }
  30471. return this._effect.isReady();
  30472. };
  30473. return OutlineRenderer;
  30474. })();
  30475. BABYLON.OutlineRenderer = OutlineRenderer;
  30476. })(BABYLON || (BABYLON = {}));
  30477. var BABYLON;
  30478. (function (BABYLON) {
  30479. var MeshAssetTask = (function () {
  30480. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  30481. this.name = name;
  30482. this.meshesNames = meshesNames;
  30483. this.rootUrl = rootUrl;
  30484. this.sceneFilename = sceneFilename;
  30485. this.isCompleted = false;
  30486. }
  30487. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30488. var _this = this;
  30489. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  30490. _this.loadedMeshes = meshes;
  30491. _this.loadedParticleSystems = particleSystems;
  30492. _this.loadedSkeletons = skeletons;
  30493. _this.isCompleted = true;
  30494. if (_this.onSuccess) {
  30495. _this.onSuccess(_this);
  30496. }
  30497. onSuccess();
  30498. }, null, function () {
  30499. if (_this.onError) {
  30500. _this.onError(_this);
  30501. }
  30502. onError();
  30503. });
  30504. };
  30505. return MeshAssetTask;
  30506. })();
  30507. BABYLON.MeshAssetTask = MeshAssetTask;
  30508. var TextFileAssetTask = (function () {
  30509. function TextFileAssetTask(name, url) {
  30510. this.name = name;
  30511. this.url = url;
  30512. this.isCompleted = false;
  30513. }
  30514. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30515. var _this = this;
  30516. BABYLON.Tools.LoadFile(this.url, function (data) {
  30517. _this.text = data;
  30518. _this.isCompleted = true;
  30519. if (_this.onSuccess) {
  30520. _this.onSuccess(_this);
  30521. }
  30522. onSuccess();
  30523. }, null, scene.database, false, function () {
  30524. if (_this.onError) {
  30525. _this.onError(_this);
  30526. }
  30527. onError();
  30528. });
  30529. };
  30530. return TextFileAssetTask;
  30531. })();
  30532. BABYLON.TextFileAssetTask = TextFileAssetTask;
  30533. var BinaryFileAssetTask = (function () {
  30534. function BinaryFileAssetTask(name, url) {
  30535. this.name = name;
  30536. this.url = url;
  30537. this.isCompleted = false;
  30538. }
  30539. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30540. var _this = this;
  30541. BABYLON.Tools.LoadFile(this.url, function (data) {
  30542. _this.data = data;
  30543. _this.isCompleted = true;
  30544. if (_this.onSuccess) {
  30545. _this.onSuccess(_this);
  30546. }
  30547. onSuccess();
  30548. }, null, scene.database, true, function () {
  30549. if (_this.onError) {
  30550. _this.onError(_this);
  30551. }
  30552. onError();
  30553. });
  30554. };
  30555. return BinaryFileAssetTask;
  30556. })();
  30557. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  30558. var ImageAssetTask = (function () {
  30559. function ImageAssetTask(name, url) {
  30560. this.name = name;
  30561. this.url = url;
  30562. this.isCompleted = false;
  30563. }
  30564. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30565. var _this = this;
  30566. var img = new Image();
  30567. img.onload = function () {
  30568. _this.image = img;
  30569. _this.isCompleted = true;
  30570. if (_this.onSuccess) {
  30571. _this.onSuccess(_this);
  30572. }
  30573. onSuccess();
  30574. };
  30575. img.onerror = function () {
  30576. if (_this.onError) {
  30577. _this.onError(_this);
  30578. }
  30579. onError();
  30580. };
  30581. img.src = this.url;
  30582. };
  30583. return ImageAssetTask;
  30584. })();
  30585. BABYLON.ImageAssetTask = ImageAssetTask;
  30586. var TextureAssetTask = (function () {
  30587. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  30588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30589. this.name = name;
  30590. this.url = url;
  30591. this.noMipmap = noMipmap;
  30592. this.invertY = invertY;
  30593. this.samplingMode = samplingMode;
  30594. this.isCompleted = false;
  30595. }
  30596. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30597. var _this = this;
  30598. var onload = function () {
  30599. _this.isCompleted = true;
  30600. if (_this.onSuccess) {
  30601. _this.onSuccess(_this);
  30602. }
  30603. onSuccess();
  30604. };
  30605. var onerror = function () {
  30606. if (_this.onError) {
  30607. _this.onError(_this);
  30608. }
  30609. onError();
  30610. };
  30611. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  30612. };
  30613. return TextureAssetTask;
  30614. })();
  30615. BABYLON.TextureAssetTask = TextureAssetTask;
  30616. var AssetsManager = (function () {
  30617. function AssetsManager(scene) {
  30618. this._tasks = new Array();
  30619. this._waitingTasksCount = 0;
  30620. this.useDefaultLoadingScreen = true;
  30621. this._scene = scene;
  30622. }
  30623. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  30624. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  30625. this._tasks.push(task);
  30626. return task;
  30627. };
  30628. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  30629. var task = new TextFileAssetTask(taskName, url);
  30630. this._tasks.push(task);
  30631. return task;
  30632. };
  30633. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  30634. var task = new BinaryFileAssetTask(taskName, url);
  30635. this._tasks.push(task);
  30636. return task;
  30637. };
  30638. AssetsManager.prototype.addImageTask = function (taskName, url) {
  30639. var task = new ImageAssetTask(taskName, url);
  30640. this._tasks.push(task);
  30641. return task;
  30642. };
  30643. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  30644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30645. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  30646. this._tasks.push(task);
  30647. return task;
  30648. };
  30649. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  30650. this._waitingTasksCount--;
  30651. if (this._waitingTasksCount === 0) {
  30652. if (this.onFinish) {
  30653. this.onFinish(this._tasks);
  30654. }
  30655. this._scene.getEngine().hideLoadingUI();
  30656. }
  30657. };
  30658. AssetsManager.prototype._runTask = function (task) {
  30659. var _this = this;
  30660. task.run(this._scene, function () {
  30661. if (_this.onTaskSuccess) {
  30662. _this.onTaskSuccess(task);
  30663. }
  30664. _this._decreaseWaitingTasksCount();
  30665. }, function () {
  30666. if (_this.onTaskError) {
  30667. _this.onTaskError(task);
  30668. }
  30669. _this._decreaseWaitingTasksCount();
  30670. });
  30671. };
  30672. AssetsManager.prototype.reset = function () {
  30673. this._tasks = new Array();
  30674. return this;
  30675. };
  30676. AssetsManager.prototype.load = function () {
  30677. this._waitingTasksCount = this._tasks.length;
  30678. if (this._waitingTasksCount === 0) {
  30679. if (this.onFinish) {
  30680. this.onFinish(this._tasks);
  30681. }
  30682. return this;
  30683. }
  30684. if (this.useDefaultLoadingScreen) {
  30685. this._scene.getEngine().displayLoadingUI();
  30686. }
  30687. for (var index = 0; index < this._tasks.length; index++) {
  30688. var task = this._tasks[index];
  30689. this._runTask(task);
  30690. }
  30691. return this;
  30692. };
  30693. return AssetsManager;
  30694. })();
  30695. BABYLON.AssetsManager = AssetsManager;
  30696. })(BABYLON || (BABYLON = {}));
  30697. var BABYLON;
  30698. (function (BABYLON) {
  30699. var VRDeviceOrientationFreeCamera = (function (_super) {
  30700. __extends(VRDeviceOrientationFreeCamera, _super);
  30701. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  30702. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30703. _super.call(this, name, position, scene);
  30704. this._alpha = 0;
  30705. this._beta = 0;
  30706. this._gamma = 0;
  30707. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30708. metrics.compensateDistortion = compensateDistortion;
  30709. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30710. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30711. }
  30712. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30713. this._alpha = +evt.alpha | 0;
  30714. this._beta = +evt.beta | 0;
  30715. this._gamma = +evt.gamma | 0;
  30716. if (this._gamma < 0) {
  30717. this._gamma = 90 + this._gamma;
  30718. }
  30719. else {
  30720. // Incline it in the correct angle.
  30721. this._gamma = 270 - this._gamma;
  30722. }
  30723. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30724. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30725. this.rotation.z = this._beta / 180.0 * Math.PI;
  30726. };
  30727. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30728. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30729. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30730. };
  30731. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  30732. _super.prototype.detachControl.call(this, element);
  30733. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  30734. };
  30735. return VRDeviceOrientationFreeCamera;
  30736. })(BABYLON.FreeCamera);
  30737. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  30738. })(BABYLON || (BABYLON = {}));
  30739. var BABYLON;
  30740. (function (BABYLON) {
  30741. var WebVRFreeCamera = (function (_super) {
  30742. __extends(WebVRFreeCamera, _super);
  30743. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  30744. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30745. _super.call(this, name, position, scene);
  30746. this._hmdDevice = null;
  30747. this._sensorDevice = null;
  30748. this._cacheState = null;
  30749. this._cacheQuaternion = new BABYLON.Quaternion();
  30750. this._cacheRotation = BABYLON.Vector3.Zero();
  30751. this._vrEnabled = false;
  30752. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30753. metrics.compensateDistortion = compensateDistortion;
  30754. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30755. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  30756. }
  30757. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  30758. var size = devices.length;
  30759. var i = 0;
  30760. // Reset devices.
  30761. this._sensorDevice = null;
  30762. this._hmdDevice = null;
  30763. // Search for a HmdDevice.
  30764. while (i < size && this._hmdDevice === null) {
  30765. if (devices[i] instanceof HMDVRDevice) {
  30766. this._hmdDevice = devices[i];
  30767. }
  30768. i++;
  30769. }
  30770. i = 0;
  30771. while (i < size && this._sensorDevice === null) {
  30772. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  30773. this._sensorDevice = devices[i];
  30774. }
  30775. i++;
  30776. }
  30777. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  30778. };
  30779. WebVRFreeCamera.prototype._checkInputs = function () {
  30780. if (this._vrEnabled) {
  30781. this._cacheState = this._sensorDevice.getState();
  30782. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  30783. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  30784. this.rotation.x = -this._cacheRotation.z;
  30785. this.rotation.y = -this._cacheRotation.y;
  30786. this.rotation.z = this._cacheRotation.x;
  30787. }
  30788. _super.prototype._checkInputs.call(this);
  30789. };
  30790. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30791. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30792. if (navigator.getVRDevices) {
  30793. navigator.getVRDevices().then(this._getWebVRDevices);
  30794. }
  30795. else if (navigator.mozGetVRDevices) {
  30796. navigator.mozGetVRDevices(this._getWebVRDevices);
  30797. }
  30798. };
  30799. WebVRFreeCamera.prototype.detachControl = function (element) {
  30800. _super.prototype.detachControl.call(this, element);
  30801. this._vrEnabled = false;
  30802. };
  30803. return WebVRFreeCamera;
  30804. })(BABYLON.FreeCamera);
  30805. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  30806. })(BABYLON || (BABYLON = {}));
  30807. var BABYLON;
  30808. (function (BABYLON) {
  30809. // Standard optimizations
  30810. var SceneOptimization = (function () {
  30811. function SceneOptimization(priority) {
  30812. if (priority === void 0) { priority = 0; }
  30813. this.priority = priority;
  30814. this.apply = function (scene) {
  30815. return true; // Return true if everything that can be done was applied
  30816. };
  30817. }
  30818. return SceneOptimization;
  30819. })();
  30820. BABYLON.SceneOptimization = SceneOptimization;
  30821. var TextureOptimization = (function (_super) {
  30822. __extends(TextureOptimization, _super);
  30823. function TextureOptimization(priority, maximumSize) {
  30824. var _this = this;
  30825. if (priority === void 0) { priority = 0; }
  30826. if (maximumSize === void 0) { maximumSize = 1024; }
  30827. _super.call(this, priority);
  30828. this.priority = priority;
  30829. this.maximumSize = maximumSize;
  30830. this.apply = function (scene) {
  30831. var allDone = true;
  30832. for (var index = 0; index < scene.textures.length; index++) {
  30833. var texture = scene.textures[index];
  30834. if (!texture.canRescale) {
  30835. continue;
  30836. }
  30837. var currentSize = texture.getSize();
  30838. var maxDimension = Math.max(currentSize.width, currentSize.height);
  30839. if (maxDimension > _this.maximumSize) {
  30840. texture.scale(0.5);
  30841. allDone = false;
  30842. }
  30843. }
  30844. return allDone;
  30845. };
  30846. }
  30847. return TextureOptimization;
  30848. })(SceneOptimization);
  30849. BABYLON.TextureOptimization = TextureOptimization;
  30850. var HardwareScalingOptimization = (function (_super) {
  30851. __extends(HardwareScalingOptimization, _super);
  30852. function HardwareScalingOptimization(priority, maximumScale) {
  30853. var _this = this;
  30854. if (priority === void 0) { priority = 0; }
  30855. if (maximumScale === void 0) { maximumScale = 2; }
  30856. _super.call(this, priority);
  30857. this.priority = priority;
  30858. this.maximumScale = maximumScale;
  30859. this._currentScale = 1;
  30860. this.apply = function (scene) {
  30861. _this._currentScale++;
  30862. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  30863. return _this._currentScale >= _this.maximumScale;
  30864. };
  30865. }
  30866. return HardwareScalingOptimization;
  30867. })(SceneOptimization);
  30868. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  30869. var ShadowsOptimization = (function (_super) {
  30870. __extends(ShadowsOptimization, _super);
  30871. function ShadowsOptimization() {
  30872. _super.apply(this, arguments);
  30873. this.apply = function (scene) {
  30874. scene.shadowsEnabled = false;
  30875. return true;
  30876. };
  30877. }
  30878. return ShadowsOptimization;
  30879. })(SceneOptimization);
  30880. BABYLON.ShadowsOptimization = ShadowsOptimization;
  30881. var PostProcessesOptimization = (function (_super) {
  30882. __extends(PostProcessesOptimization, _super);
  30883. function PostProcessesOptimization() {
  30884. _super.apply(this, arguments);
  30885. this.apply = function (scene) {
  30886. scene.postProcessesEnabled = false;
  30887. return true;
  30888. };
  30889. }
  30890. return PostProcessesOptimization;
  30891. })(SceneOptimization);
  30892. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  30893. var LensFlaresOptimization = (function (_super) {
  30894. __extends(LensFlaresOptimization, _super);
  30895. function LensFlaresOptimization() {
  30896. _super.apply(this, arguments);
  30897. this.apply = function (scene) {
  30898. scene.lensFlaresEnabled = false;
  30899. return true;
  30900. };
  30901. }
  30902. return LensFlaresOptimization;
  30903. })(SceneOptimization);
  30904. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  30905. var ParticlesOptimization = (function (_super) {
  30906. __extends(ParticlesOptimization, _super);
  30907. function ParticlesOptimization() {
  30908. _super.apply(this, arguments);
  30909. this.apply = function (scene) {
  30910. scene.particlesEnabled = false;
  30911. return true;
  30912. };
  30913. }
  30914. return ParticlesOptimization;
  30915. })(SceneOptimization);
  30916. BABYLON.ParticlesOptimization = ParticlesOptimization;
  30917. var RenderTargetsOptimization = (function (_super) {
  30918. __extends(RenderTargetsOptimization, _super);
  30919. function RenderTargetsOptimization() {
  30920. _super.apply(this, arguments);
  30921. this.apply = function (scene) {
  30922. scene.renderTargetsEnabled = false;
  30923. return true;
  30924. };
  30925. }
  30926. return RenderTargetsOptimization;
  30927. })(SceneOptimization);
  30928. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  30929. var MergeMeshesOptimization = (function (_super) {
  30930. __extends(MergeMeshesOptimization, _super);
  30931. function MergeMeshesOptimization() {
  30932. var _this = this;
  30933. _super.apply(this, arguments);
  30934. this._canBeMerged = function (abstractMesh) {
  30935. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  30936. return false;
  30937. }
  30938. var mesh = abstractMesh;
  30939. if (!mesh.isVisible || !mesh.isEnabled()) {
  30940. return false;
  30941. }
  30942. if (mesh.instances.length > 0) {
  30943. return false;
  30944. }
  30945. if (mesh.skeleton || mesh.hasLODLevels) {
  30946. return false;
  30947. }
  30948. return true;
  30949. };
  30950. this.apply = function (scene, updateSelectionTree) {
  30951. var globalPool = scene.meshes.slice(0);
  30952. var globalLength = globalPool.length;
  30953. for (var index = 0; index < globalLength; index++) {
  30954. var currentPool = new Array();
  30955. var current = globalPool[index];
  30956. // Checks
  30957. if (!_this._canBeMerged(current)) {
  30958. continue;
  30959. }
  30960. currentPool.push(current);
  30961. // Find compatible meshes
  30962. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  30963. var otherMesh = globalPool[subIndex];
  30964. if (!_this._canBeMerged(otherMesh)) {
  30965. continue;
  30966. }
  30967. if (otherMesh.material !== current.material) {
  30968. continue;
  30969. }
  30970. if (otherMesh.checkCollisions !== current.checkCollisions) {
  30971. continue;
  30972. }
  30973. currentPool.push(otherMesh);
  30974. globalLength--;
  30975. globalPool.splice(subIndex, 1);
  30976. subIndex--;
  30977. }
  30978. if (currentPool.length < 2) {
  30979. continue;
  30980. }
  30981. // Merge meshes
  30982. BABYLON.Mesh.MergeMeshes(currentPool);
  30983. }
  30984. if (updateSelectionTree != undefined) {
  30985. if (updateSelectionTree) {
  30986. scene.createOrUpdateSelectionOctree();
  30987. }
  30988. }
  30989. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  30990. scene.createOrUpdateSelectionOctree();
  30991. }
  30992. return true;
  30993. };
  30994. }
  30995. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  30996. get: function () {
  30997. return MergeMeshesOptimization._UpdateSelectionTree;
  30998. },
  30999. set: function (value) {
  31000. MergeMeshesOptimization._UpdateSelectionTree = value;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. MergeMeshesOptimization._UpdateSelectionTree = false;
  31006. return MergeMeshesOptimization;
  31007. })(SceneOptimization);
  31008. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31009. // Options
  31010. var SceneOptimizerOptions = (function () {
  31011. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31012. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31013. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31014. this.targetFrameRate = targetFrameRate;
  31015. this.trackerDuration = trackerDuration;
  31016. this.optimizations = new Array();
  31017. }
  31018. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31019. var result = new SceneOptimizerOptions(targetFrameRate);
  31020. var priority = 0;
  31021. result.optimizations.push(new MergeMeshesOptimization(priority));
  31022. result.optimizations.push(new ShadowsOptimization(priority));
  31023. result.optimizations.push(new LensFlaresOptimization(priority));
  31024. // Next priority
  31025. priority++;
  31026. result.optimizations.push(new PostProcessesOptimization(priority));
  31027. result.optimizations.push(new ParticlesOptimization(priority));
  31028. // Next priority
  31029. priority++;
  31030. result.optimizations.push(new TextureOptimization(priority, 1024));
  31031. return result;
  31032. };
  31033. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31034. var result = new SceneOptimizerOptions(targetFrameRate);
  31035. var priority = 0;
  31036. result.optimizations.push(new MergeMeshesOptimization(priority));
  31037. result.optimizations.push(new ShadowsOptimization(priority));
  31038. result.optimizations.push(new LensFlaresOptimization(priority));
  31039. // Next priority
  31040. priority++;
  31041. result.optimizations.push(new PostProcessesOptimization(priority));
  31042. result.optimizations.push(new ParticlesOptimization(priority));
  31043. // Next priority
  31044. priority++;
  31045. result.optimizations.push(new TextureOptimization(priority, 512));
  31046. // Next priority
  31047. priority++;
  31048. result.optimizations.push(new RenderTargetsOptimization(priority));
  31049. // Next priority
  31050. priority++;
  31051. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31052. return result;
  31053. };
  31054. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31055. var result = new SceneOptimizerOptions(targetFrameRate);
  31056. var priority = 0;
  31057. result.optimizations.push(new MergeMeshesOptimization(priority));
  31058. result.optimizations.push(new ShadowsOptimization(priority));
  31059. result.optimizations.push(new LensFlaresOptimization(priority));
  31060. // Next priority
  31061. priority++;
  31062. result.optimizations.push(new PostProcessesOptimization(priority));
  31063. result.optimizations.push(new ParticlesOptimization(priority));
  31064. // Next priority
  31065. priority++;
  31066. result.optimizations.push(new TextureOptimization(priority, 256));
  31067. // Next priority
  31068. priority++;
  31069. result.optimizations.push(new RenderTargetsOptimization(priority));
  31070. // Next priority
  31071. priority++;
  31072. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31073. return result;
  31074. };
  31075. return SceneOptimizerOptions;
  31076. })();
  31077. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31078. // Scene optimizer tool
  31079. var SceneOptimizer = (function () {
  31080. function SceneOptimizer() {
  31081. }
  31082. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31083. // TODO: add an epsilon
  31084. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31085. if (onSuccess) {
  31086. onSuccess();
  31087. }
  31088. return;
  31089. }
  31090. // Apply current level of optimizations
  31091. var allDone = true;
  31092. var noOptimizationApplied = true;
  31093. for (var index = 0; index < options.optimizations.length; index++) {
  31094. var optimization = options.optimizations[index];
  31095. if (optimization.priority === currentPriorityLevel) {
  31096. noOptimizationApplied = false;
  31097. allDone = allDone && optimization.apply(scene);
  31098. }
  31099. }
  31100. // If no optimization was applied, this is a failure :(
  31101. if (noOptimizationApplied) {
  31102. if (onFailure) {
  31103. onFailure();
  31104. }
  31105. return;
  31106. }
  31107. // If all optimizations were done, move to next level
  31108. if (allDone) {
  31109. currentPriorityLevel++;
  31110. }
  31111. // Let's the system running for a specific amount of time before checking FPS
  31112. scene.executeWhenReady(function () {
  31113. setTimeout(function () {
  31114. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31115. }, options.trackerDuration);
  31116. });
  31117. };
  31118. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31119. if (!options) {
  31120. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31121. }
  31122. // Let's the system running for a specific amount of time before checking FPS
  31123. scene.executeWhenReady(function () {
  31124. setTimeout(function () {
  31125. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31126. }, options.trackerDuration);
  31127. });
  31128. };
  31129. return SceneOptimizer;
  31130. })();
  31131. BABYLON.SceneOptimizer = SceneOptimizer;
  31132. })(BABYLON || (BABYLON = {}));
  31133. var BABYLON;
  31134. (function (BABYLON) {
  31135. var Internals;
  31136. (function (Internals) {
  31137. var MeshLODLevel = (function () {
  31138. function MeshLODLevel(distance, mesh) {
  31139. this.distance = distance;
  31140. this.mesh = mesh;
  31141. }
  31142. return MeshLODLevel;
  31143. })();
  31144. Internals.MeshLODLevel = MeshLODLevel;
  31145. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31146. })(BABYLON || (BABYLON = {}));
  31147. var BABYLON;
  31148. (function (BABYLON) {
  31149. var RawTexture = (function (_super) {
  31150. __extends(RawTexture, _super);
  31151. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31152. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31153. if (invertY === void 0) { invertY = false; }
  31154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31155. _super.call(this, null, scene, !generateMipMaps, invertY);
  31156. this.format = format;
  31157. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31158. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31159. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31160. }
  31161. RawTexture.prototype.update = function (data) {
  31162. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31163. };
  31164. // Statics
  31165. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31166. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31167. if (invertY === void 0) { invertY = false; }
  31168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31169. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31170. };
  31171. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31173. if (invertY === void 0) { invertY = false; }
  31174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31175. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31176. };
  31177. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31178. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31179. if (invertY === void 0) { invertY = false; }
  31180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31181. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31182. };
  31183. RawTexture.CreateRGBTexture = 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_RGB, scene, generateMipMaps, invertY, samplingMode);
  31188. };
  31189. RawTexture.CreateRGBATexture = 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_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31194. };
  31195. return RawTexture;
  31196. })(BABYLON.Texture);
  31197. BABYLON.RawTexture = RawTexture;
  31198. })(BABYLON || (BABYLON = {}));
  31199. var BABYLON;
  31200. (function (BABYLON) {
  31201. var IndexedVector2 = (function (_super) {
  31202. __extends(IndexedVector2, _super);
  31203. function IndexedVector2(original, index) {
  31204. _super.call(this, original.x, original.y);
  31205. this.index = index;
  31206. }
  31207. return IndexedVector2;
  31208. })(BABYLON.Vector2);
  31209. var PolygonPoints = (function () {
  31210. function PolygonPoints() {
  31211. this.elements = new Array();
  31212. }
  31213. PolygonPoints.prototype.add = function (originalPoints) {
  31214. var _this = this;
  31215. var result = new Array();
  31216. originalPoints.forEach(function (point) {
  31217. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31218. var newPoint = new IndexedVector2(point, _this.elements.length);
  31219. result.push(newPoint);
  31220. _this.elements.push(newPoint);
  31221. }
  31222. });
  31223. return result;
  31224. };
  31225. PolygonPoints.prototype.computeBounds = function () {
  31226. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31227. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31228. this.elements.forEach(function (point) {
  31229. // x
  31230. if (point.x < lmin.x) {
  31231. lmin.x = point.x;
  31232. }
  31233. else if (point.x > lmax.x) {
  31234. lmax.x = point.x;
  31235. }
  31236. // y
  31237. if (point.y < lmin.y) {
  31238. lmin.y = point.y;
  31239. }
  31240. else if (point.y > lmax.y) {
  31241. lmax.y = point.y;
  31242. }
  31243. });
  31244. return {
  31245. min: lmin,
  31246. max: lmax,
  31247. width: lmax.x - lmin.x,
  31248. height: lmax.y - lmin.y
  31249. };
  31250. };
  31251. return PolygonPoints;
  31252. })();
  31253. var Polygon = (function () {
  31254. function Polygon() {
  31255. }
  31256. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31257. return [
  31258. new BABYLON.Vector2(xmin, ymin),
  31259. new BABYLON.Vector2(xmax, ymin),
  31260. new BABYLON.Vector2(xmax, ymax),
  31261. new BABYLON.Vector2(xmin, ymax)
  31262. ];
  31263. };
  31264. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31265. if (cx === void 0) { cx = 0; }
  31266. if (cy === void 0) { cy = 0; }
  31267. if (numberOfSides === void 0) { numberOfSides = 32; }
  31268. var result = new Array();
  31269. var angle = 0;
  31270. var increment = (Math.PI * 2) / numberOfSides;
  31271. for (var i = 0; i < numberOfSides; i++) {
  31272. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31273. angle -= increment;
  31274. }
  31275. return result;
  31276. };
  31277. Polygon.Parse = function (input) {
  31278. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31279. var i, result = [];
  31280. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31281. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31282. }
  31283. return result;
  31284. };
  31285. Polygon.StartingAt = function (x, y) {
  31286. return BABYLON.Path2.StartingAt(x, y);
  31287. };
  31288. return Polygon;
  31289. })();
  31290. BABYLON.Polygon = Polygon;
  31291. var PolygonMeshBuilder = (function () {
  31292. function PolygonMeshBuilder(name, contours, scene) {
  31293. this._points = new PolygonPoints();
  31294. this._outlinepoints = new PolygonPoints();
  31295. this._holes = [];
  31296. if (!("poly2tri" in window)) {
  31297. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31298. }
  31299. this._name = name;
  31300. this._scene = scene;
  31301. var points;
  31302. if (contours instanceof BABYLON.Path2) {
  31303. points = contours.getPoints();
  31304. }
  31305. else {
  31306. points = contours;
  31307. }
  31308. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31309. this._outlinepoints.add(points);
  31310. }
  31311. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31312. this._swctx.addHole(this._points.add(hole));
  31313. var holepoints = new PolygonPoints();
  31314. holepoints.add(hole);
  31315. this._holes.push(holepoints);
  31316. return this;
  31317. };
  31318. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31319. var _this = this;
  31320. if (updatable === void 0) { updatable = false; }
  31321. var result = new BABYLON.Mesh(this._name, this._scene);
  31322. var normals = [];
  31323. var positions = [];
  31324. var uvs = [];
  31325. var bounds = this._points.computeBounds();
  31326. this._points.elements.forEach(function (p) {
  31327. normals.push(0, 1.0, 0);
  31328. positions.push(p.x, 0, p.y);
  31329. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31330. });
  31331. var indices = [];
  31332. this._swctx.triangulate();
  31333. this._swctx.getTriangles().forEach(function (triangle) {
  31334. triangle.getPoints().forEach(function (point) {
  31335. indices.push(point.index);
  31336. });
  31337. });
  31338. if (depth > 0) {
  31339. var positionscount = (positions.length / 3); //get the current pointcount
  31340. this._points.elements.forEach(function (p) {
  31341. normals.push(0, -1.0, 0);
  31342. positions.push(p.x, -depth, p.y);
  31343. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31344. });
  31345. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31346. var p2;
  31347. var poscounter = 0;
  31348. this._swctx.getTriangles().forEach(function (triangle) {
  31349. triangle.getPoints().forEach(function (point) {
  31350. switch (poscounter) {
  31351. case 0:
  31352. p1 = point;
  31353. break;
  31354. case 1:
  31355. p2 = point;
  31356. break;
  31357. case 2:
  31358. indices.push(point.index + positionscount);
  31359. indices.push(p2.index + positionscount);
  31360. indices.push(p1.index + positionscount);
  31361. poscounter = -1;
  31362. break;
  31363. }
  31364. poscounter++;
  31365. //indices.push((<IndexedVector2>point).index + positionscount);
  31366. });
  31367. });
  31368. //Add the sides
  31369. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31370. this._holes.forEach(function (hole) {
  31371. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31372. });
  31373. }
  31374. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31375. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31376. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31377. result.setIndices(indices);
  31378. return result;
  31379. };
  31380. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31381. var StartIndex = positions.length / 3;
  31382. var ulength = 0;
  31383. for (var i = 0; i < points.elements.length; i++) {
  31384. var p = points.elements[i];
  31385. var p1;
  31386. if ((i + 1) > points.elements.length - 1) {
  31387. p1 = points.elements[0];
  31388. }
  31389. else {
  31390. p1 = points.elements[i + 1];
  31391. }
  31392. positions.push(p.x, 0, p.y);
  31393. positions.push(p.x, -depth, p.y);
  31394. positions.push(p1.x, 0, p1.y);
  31395. positions.push(p1.x, -depth, p1.y);
  31396. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31397. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31398. var v3 = v2.subtract(v1);
  31399. var v4 = new BABYLON.Vector3(0, 1, 0);
  31400. var vn = BABYLON.Vector3.Cross(v3, v4);
  31401. vn = vn.normalize();
  31402. uvs.push(ulength / bounds.width, 0);
  31403. uvs.push(ulength / bounds.width, 1);
  31404. ulength += v3.length();
  31405. uvs.push((ulength / bounds.width), 0);
  31406. uvs.push((ulength / bounds.width), 1);
  31407. if (!flip) {
  31408. normals.push(-vn.x, -vn.y, -vn.z);
  31409. normals.push(-vn.x, -vn.y, -vn.z);
  31410. normals.push(-vn.x, -vn.y, -vn.z);
  31411. normals.push(-vn.x, -vn.y, -vn.z);
  31412. indices.push(StartIndex);
  31413. indices.push(StartIndex + 1);
  31414. indices.push(StartIndex + 2);
  31415. indices.push(StartIndex + 1);
  31416. indices.push(StartIndex + 3);
  31417. indices.push(StartIndex + 2);
  31418. }
  31419. else {
  31420. normals.push(vn.x, vn.y, vn.z);
  31421. normals.push(vn.x, vn.y, vn.z);
  31422. normals.push(vn.x, vn.y, vn.z);
  31423. normals.push(vn.x, vn.y, vn.z);
  31424. indices.push(StartIndex);
  31425. indices.push(StartIndex + 2);
  31426. indices.push(StartIndex + 1);
  31427. indices.push(StartIndex + 1);
  31428. indices.push(StartIndex + 2);
  31429. indices.push(StartIndex + 3);
  31430. }
  31431. StartIndex += 4;
  31432. }
  31433. ;
  31434. };
  31435. return PolygonMeshBuilder;
  31436. })();
  31437. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31438. })(BABYLON || (BABYLON = {}));
  31439. var BABYLON;
  31440. (function (BABYLON) {
  31441. var Octree = (function () {
  31442. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  31443. if (maxDepth === void 0) { maxDepth = 2; }
  31444. this.maxDepth = maxDepth;
  31445. this.dynamicContent = new Array();
  31446. this._maxBlockCapacity = maxBlockCapacity || 64;
  31447. this._selectionContent = new BABYLON.SmartArray(1024);
  31448. this._creationFunc = creationFunc;
  31449. }
  31450. // Methods
  31451. Octree.prototype.update = function (worldMin, worldMax, entries) {
  31452. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  31453. };
  31454. Octree.prototype.addMesh = function (entry) {
  31455. for (var index = 0; index < this.blocks.length; index++) {
  31456. var block = this.blocks[index];
  31457. block.addEntry(entry);
  31458. }
  31459. };
  31460. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  31461. this._selectionContent.reset();
  31462. for (var index = 0; index < this.blocks.length; index++) {
  31463. var block = this.blocks[index];
  31464. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  31465. }
  31466. if (allowDuplicate) {
  31467. this._selectionContent.concat(this.dynamicContent);
  31468. }
  31469. else {
  31470. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31471. }
  31472. return this._selectionContent;
  31473. };
  31474. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  31475. this._selectionContent.reset();
  31476. for (var index = 0; index < this.blocks.length; index++) {
  31477. var block = this.blocks[index];
  31478. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  31479. }
  31480. if (allowDuplicate) {
  31481. this._selectionContent.concat(this.dynamicContent);
  31482. }
  31483. else {
  31484. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31485. }
  31486. return this._selectionContent;
  31487. };
  31488. Octree.prototype.intersectsRay = function (ray) {
  31489. this._selectionContent.reset();
  31490. for (var index = 0; index < this.blocks.length; index++) {
  31491. var block = this.blocks[index];
  31492. block.intersectsRay(ray, this._selectionContent);
  31493. }
  31494. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31495. return this._selectionContent;
  31496. };
  31497. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  31498. target.blocks = new Array();
  31499. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  31500. // Segmenting space
  31501. for (var x = 0; x < 2; x++) {
  31502. for (var y = 0; y < 2; y++) {
  31503. for (var z = 0; z < 2; z++) {
  31504. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  31505. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  31506. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  31507. block.addEntries(entries);
  31508. target.blocks.push(block);
  31509. }
  31510. }
  31511. }
  31512. };
  31513. Octree.CreationFuncForMeshes = function (entry, block) {
  31514. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31515. block.entries.push(entry);
  31516. }
  31517. };
  31518. Octree.CreationFuncForSubMeshes = function (entry, block) {
  31519. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31520. block.entries.push(entry);
  31521. }
  31522. };
  31523. return Octree;
  31524. })();
  31525. BABYLON.Octree = Octree;
  31526. })(BABYLON || (BABYLON = {}));
  31527. var BABYLON;
  31528. (function (BABYLON) {
  31529. var OctreeBlock = (function () {
  31530. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  31531. this.entries = new Array();
  31532. this._boundingVectors = new Array();
  31533. this._capacity = capacity;
  31534. this._depth = depth;
  31535. this._maxDepth = maxDepth;
  31536. this._creationFunc = creationFunc;
  31537. this._minPoint = minPoint;
  31538. this._maxPoint = maxPoint;
  31539. this._boundingVectors.push(minPoint.clone());
  31540. this._boundingVectors.push(maxPoint.clone());
  31541. this._boundingVectors.push(minPoint.clone());
  31542. this._boundingVectors[2].x = maxPoint.x;
  31543. this._boundingVectors.push(minPoint.clone());
  31544. this._boundingVectors[3].y = maxPoint.y;
  31545. this._boundingVectors.push(minPoint.clone());
  31546. this._boundingVectors[4].z = maxPoint.z;
  31547. this._boundingVectors.push(maxPoint.clone());
  31548. this._boundingVectors[5].z = minPoint.z;
  31549. this._boundingVectors.push(maxPoint.clone());
  31550. this._boundingVectors[6].x = minPoint.x;
  31551. this._boundingVectors.push(maxPoint.clone());
  31552. this._boundingVectors[7].y = minPoint.y;
  31553. }
  31554. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  31555. // Property
  31556. get: function () {
  31557. return this._capacity;
  31558. },
  31559. enumerable: true,
  31560. configurable: true
  31561. });
  31562. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  31563. get: function () {
  31564. return this._minPoint;
  31565. },
  31566. enumerable: true,
  31567. configurable: true
  31568. });
  31569. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  31570. get: function () {
  31571. return this._maxPoint;
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. // Methods
  31577. OctreeBlock.prototype.addEntry = function (entry) {
  31578. if (this.blocks) {
  31579. for (var index = 0; index < this.blocks.length; index++) {
  31580. var block = this.blocks[index];
  31581. block.addEntry(entry);
  31582. }
  31583. return;
  31584. }
  31585. this._creationFunc(entry, this);
  31586. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  31587. this.createInnerBlocks();
  31588. }
  31589. };
  31590. OctreeBlock.prototype.addEntries = function (entries) {
  31591. for (var index = 0; index < entries.length; index++) {
  31592. var mesh = entries[index];
  31593. this.addEntry(mesh);
  31594. }
  31595. };
  31596. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  31597. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  31598. if (this.blocks) {
  31599. for (var index = 0; index < this.blocks.length; index++) {
  31600. var block = this.blocks[index];
  31601. block.select(frustumPlanes, selection, allowDuplicate);
  31602. }
  31603. return;
  31604. }
  31605. if (allowDuplicate) {
  31606. selection.concat(this.entries);
  31607. }
  31608. else {
  31609. selection.concatWithNoDuplicate(this.entries);
  31610. }
  31611. }
  31612. };
  31613. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  31614. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  31615. if (this.blocks) {
  31616. for (var index = 0; index < this.blocks.length; index++) {
  31617. var block = this.blocks[index];
  31618. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  31619. }
  31620. return;
  31621. }
  31622. if (allowDuplicate) {
  31623. selection.concat(this.entries);
  31624. }
  31625. else {
  31626. selection.concatWithNoDuplicate(this.entries);
  31627. }
  31628. }
  31629. };
  31630. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  31631. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  31632. if (this.blocks) {
  31633. for (var index = 0; index < this.blocks.length; index++) {
  31634. var block = this.blocks[index];
  31635. block.intersectsRay(ray, selection);
  31636. }
  31637. return;
  31638. }
  31639. selection.concatWithNoDuplicate(this.entries);
  31640. }
  31641. };
  31642. OctreeBlock.prototype.createInnerBlocks = function () {
  31643. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  31644. };
  31645. return OctreeBlock;
  31646. })();
  31647. BABYLON.OctreeBlock = OctreeBlock;
  31648. })(BABYLON || (BABYLON = {}));
  31649. var BABYLON;
  31650. (function (BABYLON) {
  31651. var BlurPostProcess = (function (_super) {
  31652. __extends(BlurPostProcess, _super);
  31653. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  31654. var _this = this;
  31655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31656. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  31657. this.direction = direction;
  31658. this.blurWidth = blurWidth;
  31659. this.onApply = function (effect) {
  31660. effect.setFloat2("screenSize", _this.width, _this.height);
  31661. effect.setVector2("direction", _this.direction);
  31662. effect.setFloat("blurWidth", _this.blurWidth);
  31663. };
  31664. }
  31665. return BlurPostProcess;
  31666. })(BABYLON.PostProcess);
  31667. BABYLON.BlurPostProcess = BlurPostProcess;
  31668. })(BABYLON || (BABYLON = {}));
  31669. var BABYLON;
  31670. (function (BABYLON) {
  31671. var RefractionPostProcess = (function (_super) {
  31672. __extends(RefractionPostProcess, _super);
  31673. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  31674. var _this = this;
  31675. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  31676. this.color = color;
  31677. this.depth = depth;
  31678. this.colorLevel = colorLevel;
  31679. this.onActivate = function (cam) {
  31680. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  31681. };
  31682. this.onApply = function (effect) {
  31683. effect.setColor3("baseColor", _this.color);
  31684. effect.setFloat("depth", _this.depth);
  31685. effect.setFloat("colorLevel", _this.colorLevel);
  31686. effect.setTexture("refractionSampler", _this._refRexture);
  31687. };
  31688. }
  31689. // Methods
  31690. RefractionPostProcess.prototype.dispose = function (camera) {
  31691. if (this._refRexture) {
  31692. this._refRexture.dispose();
  31693. }
  31694. _super.prototype.dispose.call(this, camera);
  31695. };
  31696. return RefractionPostProcess;
  31697. })(BABYLON.PostProcess);
  31698. BABYLON.RefractionPostProcess = RefractionPostProcess;
  31699. })(BABYLON || (BABYLON = {}));
  31700. var BABYLON;
  31701. (function (BABYLON) {
  31702. var BlackAndWhitePostProcess = (function (_super) {
  31703. __extends(BlackAndWhitePostProcess, _super);
  31704. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31705. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  31706. }
  31707. return BlackAndWhitePostProcess;
  31708. })(BABYLON.PostProcess);
  31709. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  31710. })(BABYLON || (BABYLON = {}));
  31711. var BABYLON;
  31712. (function (BABYLON) {
  31713. var ConvolutionPostProcess = (function (_super) {
  31714. __extends(ConvolutionPostProcess, _super);
  31715. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  31716. var _this = this;
  31717. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  31718. this.kernel = kernel;
  31719. this.onApply = function (effect) {
  31720. effect.setFloat2("screenSize", _this.width, _this.height);
  31721. effect.setArray("kernel", _this.kernel);
  31722. };
  31723. }
  31724. // Statics
  31725. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  31726. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  31727. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  31728. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  31729. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  31730. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  31731. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  31732. return ConvolutionPostProcess;
  31733. })(BABYLON.PostProcess);
  31734. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  31735. })(BABYLON || (BABYLON = {}));
  31736. var BABYLON;
  31737. (function (BABYLON) {
  31738. var FilterPostProcess = (function (_super) {
  31739. __extends(FilterPostProcess, _super);
  31740. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  31741. var _this = this;
  31742. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  31743. this.kernelMatrix = kernelMatrix;
  31744. this.onApply = function (effect) {
  31745. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  31746. };
  31747. }
  31748. return FilterPostProcess;
  31749. })(BABYLON.PostProcess);
  31750. BABYLON.FilterPostProcess = FilterPostProcess;
  31751. })(BABYLON || (BABYLON = {}));
  31752. var BABYLON;
  31753. (function (BABYLON) {
  31754. var FxaaPostProcess = (function (_super) {
  31755. __extends(FxaaPostProcess, _super);
  31756. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31757. var _this = this;
  31758. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  31759. this.onSizeChanged = function () {
  31760. _this.texelWidth = 1.0 / _this.width;
  31761. _this.texelHeight = 1.0 / _this.height;
  31762. };
  31763. this.onApply = function (effect) {
  31764. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  31765. };
  31766. }
  31767. return FxaaPostProcess;
  31768. })(BABYLON.PostProcess);
  31769. BABYLON.FxaaPostProcess = FxaaPostProcess;
  31770. })(BABYLON || (BABYLON = {}));
  31771. var BABYLON;
  31772. (function (BABYLON) {
  31773. var StereoscopicInterlacePostProcess = (function (_super) {
  31774. __extends(StereoscopicInterlacePostProcess, _super);
  31775. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  31776. var _this = this;
  31777. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  31778. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  31779. this.onSizeChanged = function () {
  31780. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  31781. };
  31782. this.onApply = function (effect) {
  31783. effect.setTextureFromPostProcess("camASampler", postProcessA);
  31784. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  31785. };
  31786. }
  31787. return StereoscopicInterlacePostProcess;
  31788. })(BABYLON.PostProcess);
  31789. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  31790. })(BABYLON || (BABYLON = {}));
  31791. var BABYLON;
  31792. (function (BABYLON) {
  31793. var LensFlare = (function () {
  31794. function LensFlare(size, position, color, imgUrl, system) {
  31795. this.size = size;
  31796. this.position = position;
  31797. this.dispose = function () {
  31798. if (this.texture) {
  31799. this.texture.dispose();
  31800. }
  31801. // Remove from scene
  31802. var index = this._system.lensFlares.indexOf(this);
  31803. this._system.lensFlares.splice(index, 1);
  31804. };
  31805. this.color = color || new BABYLON.Color3(1, 1, 1);
  31806. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  31807. this._system = system;
  31808. system.lensFlares.push(this);
  31809. }
  31810. return LensFlare;
  31811. })();
  31812. BABYLON.LensFlare = LensFlare;
  31813. })(BABYLON || (BABYLON = {}));
  31814. var BABYLON;
  31815. (function (BABYLON) {
  31816. var LensFlareSystem = (function () {
  31817. function LensFlareSystem(name, emitter, scene) {
  31818. this.name = name;
  31819. this.lensFlares = new Array();
  31820. this.borderLimit = 300;
  31821. this.layerMask = 0x0FFFFFFF;
  31822. this._vertexDeclaration = [2];
  31823. this._vertexStrideSize = 2 * 4;
  31824. this._isEnabled = true;
  31825. this._scene = scene;
  31826. this._emitter = emitter;
  31827. scene.lensFlareSystems.push(this);
  31828. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  31829. // VBO
  31830. var vertices = [];
  31831. vertices.push(1, 1);
  31832. vertices.push(-1, 1);
  31833. vertices.push(-1, -1);
  31834. vertices.push(1, -1);
  31835. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  31836. // Indices
  31837. var indices = [];
  31838. indices.push(0);
  31839. indices.push(1);
  31840. indices.push(2);
  31841. indices.push(0);
  31842. indices.push(2);
  31843. indices.push(3);
  31844. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31845. // Effects
  31846. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  31847. }
  31848. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  31849. get: function () {
  31850. return this._isEnabled;
  31851. },
  31852. set: function (value) {
  31853. this._isEnabled = value;
  31854. },
  31855. enumerable: true,
  31856. configurable: true
  31857. });
  31858. LensFlareSystem.prototype.getScene = function () {
  31859. return this._scene;
  31860. };
  31861. LensFlareSystem.prototype.getEmitter = function () {
  31862. return this._emitter;
  31863. };
  31864. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  31865. this._emitter = newEmitter;
  31866. };
  31867. LensFlareSystem.prototype.getEmitterPosition = function () {
  31868. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  31869. };
  31870. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  31871. var position = this.getEmitterPosition();
  31872. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  31873. this._positionX = position.x;
  31874. this._positionY = position.y;
  31875. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  31876. if (position.z > 0) {
  31877. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  31878. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  31879. return true;
  31880. }
  31881. }
  31882. return false;
  31883. };
  31884. LensFlareSystem.prototype._isVisible = function () {
  31885. if (!this._isEnabled) {
  31886. return false;
  31887. }
  31888. var emitterPosition = this.getEmitterPosition();
  31889. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  31890. var distance = direction.length();
  31891. direction.normalize();
  31892. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  31893. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  31894. return !pickInfo.hit || pickInfo.distance > distance;
  31895. };
  31896. LensFlareSystem.prototype.render = function () {
  31897. if (!this._effect.isReady())
  31898. return false;
  31899. var engine = this._scene.getEngine();
  31900. var viewport = this._scene.activeCamera.viewport;
  31901. var globalViewport = viewport.toGlobal(engine);
  31902. // Position
  31903. if (!this.computeEffectivePosition(globalViewport)) {
  31904. return false;
  31905. }
  31906. // Visibility
  31907. if (!this._isVisible()) {
  31908. return false;
  31909. }
  31910. // Intensity
  31911. var awayX;
  31912. var awayY;
  31913. if (this._positionX < this.borderLimit + globalViewport.x) {
  31914. awayX = this.borderLimit + globalViewport.x - this._positionX;
  31915. }
  31916. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  31917. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  31918. }
  31919. else {
  31920. awayX = 0;
  31921. }
  31922. if (this._positionY < this.borderLimit + globalViewport.y) {
  31923. awayY = this.borderLimit + globalViewport.y - this._positionY;
  31924. }
  31925. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  31926. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  31927. }
  31928. else {
  31929. awayY = 0;
  31930. }
  31931. var away = (awayX > awayY) ? awayX : awayY;
  31932. if (away > this.borderLimit) {
  31933. away = this.borderLimit;
  31934. }
  31935. var intensity = 1.0 - (away / this.borderLimit);
  31936. if (intensity < 0) {
  31937. return false;
  31938. }
  31939. if (intensity > 1.0) {
  31940. intensity = 1.0;
  31941. }
  31942. // Position
  31943. var centerX = globalViewport.x + globalViewport.width / 2;
  31944. var centerY = globalViewport.y + globalViewport.height / 2;
  31945. var distX = centerX - this._positionX;
  31946. var distY = centerY - this._positionY;
  31947. // Effects
  31948. engine.enableEffect(this._effect);
  31949. engine.setState(false);
  31950. engine.setDepthBuffer(false);
  31951. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  31952. // VBOs
  31953. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  31954. // Flares
  31955. for (var index = 0; index < this.lensFlares.length; index++) {
  31956. var flare = this.lensFlares[index];
  31957. var x = centerX - (distX * flare.position);
  31958. var y = centerY - (distY * flare.position);
  31959. var cw = flare.size;
  31960. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  31961. var cx = 2 * (x / globalViewport.width) - 1.0;
  31962. var cy = 1.0 - 2 * (y / globalViewport.height);
  31963. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  31964. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  31965. // Texture
  31966. this._effect.setTexture("textureSampler", flare.texture);
  31967. // Color
  31968. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  31969. // Draw order
  31970. engine.draw(true, 0, 6);
  31971. }
  31972. engine.setDepthBuffer(true);
  31973. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31974. return true;
  31975. };
  31976. LensFlareSystem.prototype.dispose = function () {
  31977. if (this._vertexBuffer) {
  31978. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  31979. this._vertexBuffer = null;
  31980. }
  31981. if (this._indexBuffer) {
  31982. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31983. this._indexBuffer = null;
  31984. }
  31985. while (this.lensFlares.length) {
  31986. this.lensFlares[0].dispose();
  31987. }
  31988. // Remove from scene
  31989. var index = this._scene.lensFlareSystems.indexOf(this);
  31990. this._scene.lensFlareSystems.splice(index, 1);
  31991. };
  31992. return LensFlareSystem;
  31993. })();
  31994. BABYLON.LensFlareSystem = LensFlareSystem;
  31995. })(BABYLON || (BABYLON = {}));
  31996. var BABYLON;
  31997. (function (BABYLON) {
  31998. // We're mainly based on the logic defined into the FreeCamera code
  31999. var DeviceOrientationCamera = (function (_super) {
  32000. __extends(DeviceOrientationCamera, _super);
  32001. function DeviceOrientationCamera(name, position, scene) {
  32002. var _this = this;
  32003. _super.call(this, name, position, scene);
  32004. this._offsetX = null;
  32005. this._offsetY = null;
  32006. this._orientationGamma = 0;
  32007. this._orientationBeta = 0;
  32008. this._initialOrientationGamma = 0;
  32009. this._initialOrientationBeta = 0;
  32010. this.angularSensibility = 10000.0;
  32011. this.moveSensibility = 50.0;
  32012. window.addEventListener("resize", function () {
  32013. _this._initialOrientationGamma = null;
  32014. }, false);
  32015. }
  32016. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32017. var _this = this;
  32018. if (this._attachedCanvas) {
  32019. return;
  32020. }
  32021. this._attachedCanvas = canvas;
  32022. if (!this._orientationChanged) {
  32023. this._orientationChanged = function (evt) {
  32024. if (!_this._initialOrientationGamma) {
  32025. _this._initialOrientationGamma = evt.gamma;
  32026. _this._initialOrientationBeta = evt.beta;
  32027. }
  32028. _this._orientationGamma = evt.gamma;
  32029. _this._orientationBeta = evt.beta;
  32030. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32031. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32032. };
  32033. }
  32034. window.addEventListener("deviceorientation", this._orientationChanged);
  32035. };
  32036. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32037. if (this._attachedCanvas != canvas) {
  32038. return;
  32039. }
  32040. window.removeEventListener("deviceorientation", this._orientationChanged);
  32041. this._attachedCanvas = null;
  32042. this._orientationGamma = 0;
  32043. this._orientationBeta = 0;
  32044. this._initialOrientationGamma = 0;
  32045. this._initialOrientationBeta = 0;
  32046. };
  32047. DeviceOrientationCamera.prototype._checkInputs = function () {
  32048. if (!this._offsetX) {
  32049. return;
  32050. }
  32051. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32052. var speed = this._computeLocalCameraSpeed();
  32053. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32054. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32055. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32056. _super.prototype._checkInputs.call(this);
  32057. };
  32058. return DeviceOrientationCamera;
  32059. })(BABYLON.FreeCamera);
  32060. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32061. })(BABYLON || (BABYLON = {}));
  32062. var BABYLON;
  32063. (function (BABYLON) {
  32064. var Gamepads = (function () {
  32065. function Gamepads(ongamedpadconnected) {
  32066. var _this = this;
  32067. this.babylonGamepads = [];
  32068. this.oneGamepadConnected = false;
  32069. this.isMonitoring = false;
  32070. this.gamepadEventSupported = 'GamepadEvent' in window;
  32071. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32072. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32073. 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=";
  32074. this._callbackGamepadConnected = ongamedpadconnected;
  32075. if (this.gamepadSupportAvailable) {
  32076. // Checking if the gamepad connected event is supported (like in Firefox)
  32077. if (this.gamepadEventSupported) {
  32078. window.addEventListener('gamepadconnected', function (evt) {
  32079. _this._onGamepadConnected(evt);
  32080. }, false);
  32081. window.addEventListener('gamepaddisconnected', function (evt) {
  32082. _this._onGamepadDisconnected(evt);
  32083. }, false);
  32084. }
  32085. else {
  32086. this._startMonitoringGamepads();
  32087. }
  32088. if (!this.oneGamepadConnected) {
  32089. this._insertGamepadDOMInstructions();
  32090. }
  32091. }
  32092. else {
  32093. this._insertGamepadDOMNotSupported();
  32094. }
  32095. }
  32096. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32097. Gamepads.gamepadDOMInfo = document.createElement("div");
  32098. var buttonAImage = document.createElement("img");
  32099. buttonAImage.src = this.buttonADataURL;
  32100. var spanMessage = document.createElement("span");
  32101. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32102. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32103. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32104. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32105. Gamepads.gamepadDOMInfo.style.width = "100%";
  32106. Gamepads.gamepadDOMInfo.style.height = "48px";
  32107. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32108. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32109. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32110. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32111. buttonAImage.style.position = "relative";
  32112. buttonAImage.style.bottom = "8px";
  32113. spanMessage.style.position = "relative";
  32114. spanMessage.style.fontSize = "32px";
  32115. spanMessage.style.bottom = "32px";
  32116. spanMessage.style.color = "green";
  32117. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32118. };
  32119. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32120. Gamepads.gamepadDOMInfo = document.createElement("div");
  32121. var spanMessage = document.createElement("span");
  32122. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32123. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32124. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32125. Gamepads.gamepadDOMInfo.style.width = "100%";
  32126. Gamepads.gamepadDOMInfo.style.height = "40px";
  32127. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32128. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32129. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32130. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32131. spanMessage.style.position = "relative";
  32132. spanMessage.style.fontSize = "32px";
  32133. spanMessage.style.color = "red";
  32134. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32135. };
  32136. Gamepads.prototype.dispose = function () {
  32137. if (Gamepads.gamepadDOMInfo) {
  32138. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32139. }
  32140. };
  32141. Gamepads.prototype._onGamepadConnected = function (evt) {
  32142. var newGamepad = this._addNewGamepad(evt.gamepad);
  32143. if (this._callbackGamepadConnected)
  32144. this._callbackGamepadConnected(newGamepad);
  32145. this._startMonitoringGamepads();
  32146. };
  32147. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32148. if (!this.oneGamepadConnected) {
  32149. this.oneGamepadConnected = true;
  32150. if (Gamepads.gamepadDOMInfo) {
  32151. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32152. Gamepads.gamepadDOMInfo = null;
  32153. }
  32154. }
  32155. var newGamepad;
  32156. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32157. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32158. }
  32159. else {
  32160. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32161. }
  32162. this.babylonGamepads.push(newGamepad);
  32163. return newGamepad;
  32164. };
  32165. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32166. // Remove the gamepad from the list of gamepads to monitor.
  32167. for (var i in this.babylonGamepads) {
  32168. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32169. this.babylonGamepads.splice(i, 1);
  32170. break;
  32171. }
  32172. }
  32173. // If no gamepads are left, stop the polling loop.
  32174. if (this.babylonGamepads.length == 0) {
  32175. this._stopMonitoringGamepads();
  32176. }
  32177. };
  32178. Gamepads.prototype._startMonitoringGamepads = function () {
  32179. if (!this.isMonitoring) {
  32180. this.isMonitoring = true;
  32181. this._checkGamepadsStatus();
  32182. }
  32183. };
  32184. Gamepads.prototype._stopMonitoringGamepads = function () {
  32185. this.isMonitoring = false;
  32186. };
  32187. Gamepads.prototype._checkGamepadsStatus = function () {
  32188. var _this = this;
  32189. // updating gamepad objects
  32190. this._updateGamepadObjects();
  32191. for (var i in this.babylonGamepads) {
  32192. this.babylonGamepads[i].update();
  32193. }
  32194. if (this.isMonitoring) {
  32195. if (window.requestAnimationFrame) {
  32196. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32197. }
  32198. else if (window.mozRequestAnimationFrame) {
  32199. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32200. }
  32201. else if (window.webkitRequestAnimationFrame) {
  32202. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32203. }
  32204. }
  32205. };
  32206. // This function is called only on Chrome, which does not yet support
  32207. // connection/disconnection events, but requires you to monitor
  32208. // an array for changes.
  32209. Gamepads.prototype._updateGamepadObjects = function () {
  32210. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32211. for (var i = 0; i < gamepads.length; i++) {
  32212. if (gamepads[i]) {
  32213. if (!(gamepads[i].index in this.babylonGamepads)) {
  32214. var newGamepad = this._addNewGamepad(gamepads[i]);
  32215. if (this._callbackGamepadConnected) {
  32216. this._callbackGamepadConnected(newGamepad);
  32217. }
  32218. }
  32219. else {
  32220. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32221. }
  32222. }
  32223. }
  32224. };
  32225. return Gamepads;
  32226. })();
  32227. BABYLON.Gamepads = Gamepads;
  32228. var StickValues = (function () {
  32229. function StickValues(x, y) {
  32230. this.x = x;
  32231. this.y = y;
  32232. }
  32233. return StickValues;
  32234. })();
  32235. BABYLON.StickValues = StickValues;
  32236. var Gamepad = (function () {
  32237. function Gamepad(id, index, browserGamepad) {
  32238. this.id = id;
  32239. this.index = index;
  32240. this.browserGamepad = browserGamepad;
  32241. if (this.browserGamepad.axes.length >= 2) {
  32242. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32243. }
  32244. if (this.browserGamepad.axes.length >= 4) {
  32245. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32246. }
  32247. }
  32248. Gamepad.prototype.onleftstickchanged = function (callback) {
  32249. this._onleftstickchanged = callback;
  32250. };
  32251. Gamepad.prototype.onrightstickchanged = function (callback) {
  32252. this._onrightstickchanged = callback;
  32253. };
  32254. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32255. get: function () {
  32256. return this._leftStick;
  32257. },
  32258. set: function (newValues) {
  32259. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32260. this._onleftstickchanged(newValues);
  32261. }
  32262. this._leftStick = newValues;
  32263. },
  32264. enumerable: true,
  32265. configurable: true
  32266. });
  32267. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32268. get: function () {
  32269. return this._rightStick;
  32270. },
  32271. set: function (newValues) {
  32272. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32273. this._onrightstickchanged(newValues);
  32274. }
  32275. this._rightStick = newValues;
  32276. },
  32277. enumerable: true,
  32278. configurable: true
  32279. });
  32280. Gamepad.prototype.update = function () {
  32281. if (this._leftStick) {
  32282. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32283. }
  32284. if (this._rightStick) {
  32285. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32286. }
  32287. };
  32288. return Gamepad;
  32289. })();
  32290. BABYLON.Gamepad = Gamepad;
  32291. var GenericPad = (function (_super) {
  32292. __extends(GenericPad, _super);
  32293. function GenericPad(id, index, gamepad) {
  32294. _super.call(this, id, index, gamepad);
  32295. this.id = id;
  32296. this.index = index;
  32297. this.gamepad = gamepad;
  32298. this._buttons = new Array(gamepad.buttons.length);
  32299. }
  32300. GenericPad.prototype.onbuttondown = function (callback) {
  32301. this._onbuttondown = callback;
  32302. };
  32303. GenericPad.prototype.onbuttonup = function (callback) {
  32304. this._onbuttonup = callback;
  32305. };
  32306. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32307. if (newValue !== currentValue) {
  32308. if (this._onbuttondown && newValue === 1) {
  32309. this._onbuttondown(buttonIndex);
  32310. }
  32311. if (this._onbuttonup && newValue === 0) {
  32312. this._onbuttonup(buttonIndex);
  32313. }
  32314. }
  32315. return newValue;
  32316. };
  32317. GenericPad.prototype.update = function () {
  32318. _super.prototype.update.call(this);
  32319. for (var index = 0; index < this._buttons.length; index++) {
  32320. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32321. }
  32322. };
  32323. return GenericPad;
  32324. })(Gamepad);
  32325. BABYLON.GenericPad = GenericPad;
  32326. (function (Xbox360Button) {
  32327. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32328. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32329. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  32330. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  32331. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  32332. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  32333. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  32334. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  32335. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  32336. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  32337. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  32338. var Xbox360Button = BABYLON.Xbox360Button;
  32339. (function (Xbox360Dpad) {
  32340. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  32341. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  32342. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  32343. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  32344. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  32345. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  32346. var Xbox360Pad = (function (_super) {
  32347. __extends(Xbox360Pad, _super);
  32348. function Xbox360Pad() {
  32349. _super.apply(this, arguments);
  32350. this._leftTrigger = 0;
  32351. this._rightTrigger = 0;
  32352. this._buttonA = 0;
  32353. this._buttonB = 0;
  32354. this._buttonX = 0;
  32355. this._buttonY = 0;
  32356. this._buttonBack = 0;
  32357. this._buttonStart = 0;
  32358. this._buttonLB = 0;
  32359. this._buttonRB = 0;
  32360. this._buttonLeftStick = 0;
  32361. this._buttonRightStick = 0;
  32362. this._dPadUp = 0;
  32363. this._dPadDown = 0;
  32364. this._dPadLeft = 0;
  32365. this._dPadRight = 0;
  32366. }
  32367. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  32368. this._onlefttriggerchanged = callback;
  32369. };
  32370. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  32371. this._onrighttriggerchanged = callback;
  32372. };
  32373. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  32374. get: function () {
  32375. return this._leftTrigger;
  32376. },
  32377. set: function (newValue) {
  32378. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  32379. this._onlefttriggerchanged(newValue);
  32380. }
  32381. this._leftTrigger = newValue;
  32382. },
  32383. enumerable: true,
  32384. configurable: true
  32385. });
  32386. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  32387. get: function () {
  32388. return this._rightTrigger;
  32389. },
  32390. set: function (newValue) {
  32391. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  32392. this._onrighttriggerchanged(newValue);
  32393. }
  32394. this._rightTrigger = newValue;
  32395. },
  32396. enumerable: true,
  32397. configurable: true
  32398. });
  32399. Xbox360Pad.prototype.onbuttondown = function (callback) {
  32400. this._onbuttondown = callback;
  32401. };
  32402. Xbox360Pad.prototype.onbuttonup = function (callback) {
  32403. this._onbuttonup = callback;
  32404. };
  32405. Xbox360Pad.prototype.ondpaddown = function (callback) {
  32406. this._ondpaddown = callback;
  32407. };
  32408. Xbox360Pad.prototype.ondpadup = function (callback) {
  32409. this._ondpadup = callback;
  32410. };
  32411. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  32412. if (newValue !== currentValue) {
  32413. if (this._onbuttondown && newValue === 1) {
  32414. this._onbuttondown(buttonType);
  32415. }
  32416. if (this._onbuttonup && newValue === 0) {
  32417. this._onbuttonup(buttonType);
  32418. }
  32419. }
  32420. return newValue;
  32421. };
  32422. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  32423. if (newValue !== currentValue) {
  32424. if (this._ondpaddown && newValue === 1) {
  32425. this._ondpaddown(buttonType);
  32426. }
  32427. if (this._ondpadup && newValue === 0) {
  32428. this._ondpadup(buttonType);
  32429. }
  32430. }
  32431. return newValue;
  32432. };
  32433. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  32434. get: function () {
  32435. return this._buttonA;
  32436. },
  32437. set: function (value) {
  32438. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  32439. },
  32440. enumerable: true,
  32441. configurable: true
  32442. });
  32443. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  32444. get: function () {
  32445. return this._buttonB;
  32446. },
  32447. set: function (value) {
  32448. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  32449. },
  32450. enumerable: true,
  32451. configurable: true
  32452. });
  32453. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  32454. get: function () {
  32455. return this._buttonX;
  32456. },
  32457. set: function (value) {
  32458. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  32459. },
  32460. enumerable: true,
  32461. configurable: true
  32462. });
  32463. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  32464. get: function () {
  32465. return this._buttonY;
  32466. },
  32467. set: function (value) {
  32468. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  32469. },
  32470. enumerable: true,
  32471. configurable: true
  32472. });
  32473. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  32474. get: function () {
  32475. return this._buttonStart;
  32476. },
  32477. set: function (value) {
  32478. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  32479. },
  32480. enumerable: true,
  32481. configurable: true
  32482. });
  32483. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  32484. get: function () {
  32485. return this._buttonBack;
  32486. },
  32487. set: function (value) {
  32488. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  32489. },
  32490. enumerable: true,
  32491. configurable: true
  32492. });
  32493. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  32494. get: function () {
  32495. return this._buttonLB;
  32496. },
  32497. set: function (value) {
  32498. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  32499. },
  32500. enumerable: true,
  32501. configurable: true
  32502. });
  32503. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  32504. get: function () {
  32505. return this._buttonRB;
  32506. },
  32507. set: function (value) {
  32508. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  32509. },
  32510. enumerable: true,
  32511. configurable: true
  32512. });
  32513. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  32514. get: function () {
  32515. return this._buttonLeftStick;
  32516. },
  32517. set: function (value) {
  32518. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  32519. },
  32520. enumerable: true,
  32521. configurable: true
  32522. });
  32523. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  32524. get: function () {
  32525. return this._buttonRightStick;
  32526. },
  32527. set: function (value) {
  32528. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  32529. },
  32530. enumerable: true,
  32531. configurable: true
  32532. });
  32533. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  32534. get: function () {
  32535. return this._dPadUp;
  32536. },
  32537. set: function (value) {
  32538. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  32539. },
  32540. enumerable: true,
  32541. configurable: true
  32542. });
  32543. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  32544. get: function () {
  32545. return this._dPadDown;
  32546. },
  32547. set: function (value) {
  32548. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  32554. get: function () {
  32555. return this._dPadLeft;
  32556. },
  32557. set: function (value) {
  32558. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  32559. },
  32560. enumerable: true,
  32561. configurable: true
  32562. });
  32563. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  32564. get: function () {
  32565. return this._dPadRight;
  32566. },
  32567. set: function (value) {
  32568. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  32569. },
  32570. enumerable: true,
  32571. configurable: true
  32572. });
  32573. Xbox360Pad.prototype.update = function () {
  32574. _super.prototype.update.call(this);
  32575. this.buttonA = this.browserGamepad.buttons[0].value;
  32576. this.buttonB = this.browserGamepad.buttons[1].value;
  32577. this.buttonX = this.browserGamepad.buttons[2].value;
  32578. this.buttonY = this.browserGamepad.buttons[3].value;
  32579. this.buttonLB = this.browserGamepad.buttons[4].value;
  32580. this.buttonRB = this.browserGamepad.buttons[5].value;
  32581. this.leftTrigger = this.browserGamepad.buttons[6].value;
  32582. this.rightTrigger = this.browserGamepad.buttons[7].value;
  32583. this.buttonBack = this.browserGamepad.buttons[8].value;
  32584. this.buttonStart = this.browserGamepad.buttons[9].value;
  32585. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  32586. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  32587. this.dPadUp = this.browserGamepad.buttons[12].value;
  32588. this.dPadDown = this.browserGamepad.buttons[13].value;
  32589. this.dPadLeft = this.browserGamepad.buttons[14].value;
  32590. this.dPadRight = this.browserGamepad.buttons[15].value;
  32591. };
  32592. return Xbox360Pad;
  32593. })(Gamepad);
  32594. BABYLON.Xbox360Pad = Xbox360Pad;
  32595. })(BABYLON || (BABYLON = {}));
  32596. var BABYLON;
  32597. (function (BABYLON) {
  32598. // We're mainly based on the logic defined into the FreeCamera code
  32599. var GamepadCamera = (function (_super) {
  32600. __extends(GamepadCamera, _super);
  32601. function GamepadCamera(name, position, scene) {
  32602. var _this = this;
  32603. _super.call(this, name, position, scene);
  32604. this.angularSensibility = 200;
  32605. this.moveSensibility = 75;
  32606. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  32607. }
  32608. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  32609. // Only the first gamepad can control the camera
  32610. if (gamepad.index === 0) {
  32611. this._gamepad = gamepad;
  32612. }
  32613. };
  32614. GamepadCamera.prototype._checkInputs = function () {
  32615. if (this._gamepad) {
  32616. var LSValues = this._gamepad.leftStick;
  32617. var normalizedLX = LSValues.x / this.moveSensibility;
  32618. var normalizedLY = LSValues.y / this.moveSensibility;
  32619. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  32620. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  32621. var RSValues = this._gamepad.rightStick;
  32622. var normalizedRX = RSValues.x / this.angularSensibility;
  32623. var normalizedRY = RSValues.y / this.angularSensibility;
  32624. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  32625. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  32626. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32627. var speed = this._computeLocalCameraSpeed() * 50.0;
  32628. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  32629. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32630. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  32631. }
  32632. _super.prototype._checkInputs.call(this);
  32633. };
  32634. GamepadCamera.prototype.dispose = function () {
  32635. this._gamepads.dispose();
  32636. _super.prototype.dispose.call(this);
  32637. };
  32638. return GamepadCamera;
  32639. })(BABYLON.FreeCamera);
  32640. BABYLON.GamepadCamera = GamepadCamera;
  32641. })(BABYLON || (BABYLON = {}));
  32642. var BABYLON;
  32643. (function (BABYLON) {
  32644. var Analyser = (function () {
  32645. function Analyser(scene) {
  32646. this.SMOOTHING = 0.75;
  32647. this.FFT_SIZE = 512;
  32648. this.BARGRAPHAMPLITUDE = 256;
  32649. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32650. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32651. this._scene = scene;
  32652. this._audioEngine = BABYLON.Engine.audioEngine;
  32653. if (this._audioEngine.canUseWebAudio) {
  32654. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32655. this._webAudioAnalyser.minDecibels = -140;
  32656. this._webAudioAnalyser.maxDecibels = 0;
  32657. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32658. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32659. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32660. }
  32661. }
  32662. Analyser.prototype.getFrequencyBinCount = function () {
  32663. if (this._audioEngine.canUseWebAudio) {
  32664. return this._webAudioAnalyser.frequencyBinCount;
  32665. }
  32666. else {
  32667. return 0;
  32668. }
  32669. };
  32670. Analyser.prototype.getByteFrequencyData = function () {
  32671. if (this._audioEngine.canUseWebAudio) {
  32672. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32673. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32674. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32675. }
  32676. return this._byteFreqs;
  32677. };
  32678. Analyser.prototype.getByteTimeDomainData = function () {
  32679. if (this._audioEngine.canUseWebAudio) {
  32680. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32681. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32682. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32683. }
  32684. return this._byteTime;
  32685. };
  32686. Analyser.prototype.getFloatFrequencyData = function () {
  32687. if (this._audioEngine.canUseWebAudio) {
  32688. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32689. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32690. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32691. }
  32692. return this._floatFreqs;
  32693. };
  32694. Analyser.prototype.drawDebugCanvas = function () {
  32695. var _this = this;
  32696. if (this._audioEngine.canUseWebAudio) {
  32697. if (!this._debugCanvas) {
  32698. this._debugCanvas = document.createElement("canvas");
  32699. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32700. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32701. this._debugCanvas.style.position = "absolute";
  32702. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32703. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32704. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32705. document.body.appendChild(this._debugCanvas);
  32706. this._registerFunc = function () {
  32707. _this.drawDebugCanvas();
  32708. };
  32709. this._scene.registerBeforeRender(this._registerFunc);
  32710. }
  32711. if (this._registerFunc) {
  32712. var workingArray = this.getByteFrequencyData();
  32713. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32714. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32715. // Draw the frequency domain chart.
  32716. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32717. var value = workingArray[i];
  32718. var percent = value / this.BARGRAPHAMPLITUDE;
  32719. var height = this.DEBUGCANVASSIZE.height * percent;
  32720. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32721. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32722. var hue = i / this.getFrequencyBinCount() * 360;
  32723. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32724. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32725. }
  32726. }
  32727. }
  32728. };
  32729. Analyser.prototype.stopDebugCanvas = function () {
  32730. if (this._debugCanvas) {
  32731. this._scene.unregisterBeforeRender(this._registerFunc);
  32732. this._registerFunc = null;
  32733. document.body.removeChild(this._debugCanvas);
  32734. this._debugCanvas = null;
  32735. this._debugCanvasContext = null;
  32736. }
  32737. };
  32738. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32739. if (this._audioEngine.canUseWebAudio) {
  32740. inputAudioNode.connect(this._webAudioAnalyser);
  32741. this._webAudioAnalyser.connect(outputAudioNode);
  32742. }
  32743. };
  32744. Analyser.prototype.dispose = function () {
  32745. if (this._audioEngine.canUseWebAudio) {
  32746. this._webAudioAnalyser.disconnect();
  32747. }
  32748. };
  32749. return Analyser;
  32750. })();
  32751. BABYLON.Analyser = Analyser;
  32752. })(BABYLON || (BABYLON = {}));
  32753. var BABYLON;
  32754. (function (BABYLON) {
  32755. var AudioEngine = (function () {
  32756. function AudioEngine() {
  32757. this._audioContext = null;
  32758. this._audioContextInitialized = false;
  32759. this.canUseWebAudio = false;
  32760. this.WarnedWebAudioUnsupported = false;
  32761. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32762. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32763. this.canUseWebAudio = true;
  32764. }
  32765. }
  32766. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32767. get: function () {
  32768. if (!this._audioContextInitialized) {
  32769. this._initializeAudioContext();
  32770. }
  32771. return this._audioContext;
  32772. },
  32773. enumerable: true,
  32774. configurable: true
  32775. });
  32776. AudioEngine.prototype._initializeAudioContext = function () {
  32777. try {
  32778. if (this.canUseWebAudio) {
  32779. this._audioContext = new AudioContext();
  32780. // create a global volume gain node
  32781. this.masterGain = this._audioContext.createGain();
  32782. this.masterGain.gain.value = 1;
  32783. this.masterGain.connect(this._audioContext.destination);
  32784. this._audioContextInitialized = true;
  32785. }
  32786. }
  32787. catch (e) {
  32788. this.canUseWebAudio = false;
  32789. BABYLON.Tools.Error("Web Audio: " + e.message);
  32790. }
  32791. };
  32792. AudioEngine.prototype.dispose = function () {
  32793. if (this.canUseWebAudio && this._audioContextInitialized) {
  32794. if (this._connectedAnalyser) {
  32795. this._connectedAnalyser.stopDebugCanvas();
  32796. this._connectedAnalyser.dispose();
  32797. this.masterGain.disconnect();
  32798. this.masterGain.connect(this._audioContext.destination);
  32799. this._connectedAnalyser = null;
  32800. }
  32801. this.masterGain.gain.value = 1;
  32802. }
  32803. this.WarnedWebAudioUnsupported = false;
  32804. };
  32805. AudioEngine.prototype.getGlobalVolume = function () {
  32806. if (this.canUseWebAudio && this._audioContextInitialized) {
  32807. return this.masterGain.gain.value;
  32808. }
  32809. else {
  32810. return -1;
  32811. }
  32812. };
  32813. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  32814. if (this.canUseWebAudio && this._audioContextInitialized) {
  32815. this.masterGain.gain.value = newVolume;
  32816. }
  32817. };
  32818. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  32819. if (this._connectedAnalyser) {
  32820. this._connectedAnalyser.stopDebugCanvas();
  32821. }
  32822. if (this.canUseWebAudio && this._audioContextInitialized) {
  32823. this._connectedAnalyser = analyser;
  32824. this.masterGain.disconnect();
  32825. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  32826. }
  32827. };
  32828. return AudioEngine;
  32829. })();
  32830. BABYLON.AudioEngine = AudioEngine;
  32831. })(BABYLON || (BABYLON = {}));
  32832. var BABYLON;
  32833. (function (BABYLON) {
  32834. var Sound = (function () {
  32835. /**
  32836. * Create a sound and attach it to a scene
  32837. * @param name Name of your sound
  32838. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  32839. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  32840. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  32841. */
  32842. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  32843. var _this = this;
  32844. this.autoplay = false;
  32845. this.loop = false;
  32846. this.useCustomAttenuation = false;
  32847. this.spatialSound = false;
  32848. this.refDistance = 1;
  32849. this.rolloffFactor = 1;
  32850. this.maxDistance = 100;
  32851. this.distanceModel = "linear";
  32852. this._panningModel = "equalpower";
  32853. this._playbackRate = 1;
  32854. this._startTime = 0;
  32855. this._startOffset = 0;
  32856. this._position = BABYLON.Vector3.Zero();
  32857. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  32858. this._volume = 1;
  32859. this._isLoaded = false;
  32860. this._isReadyToPlay = false;
  32861. this.isPlaying = false;
  32862. this.isPaused = false;
  32863. this._isDirectional = false;
  32864. // Used if you'd like to create a directional sound.
  32865. // If not set, the sound will be omnidirectional
  32866. this._coneInnerAngle = 360;
  32867. this._coneOuterAngle = 360;
  32868. this._coneOuterGain = 0;
  32869. this._isOutputConnected = false;
  32870. this.name = name;
  32871. this._scene = scene;
  32872. this._readyToPlayCallback = readyToPlayCallback;
  32873. // Default custom attenuation function is a linear attenuation
  32874. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  32875. if (currentDistance < maxDistance) {
  32876. return currentVolume * (1 - currentDistance / maxDistance);
  32877. }
  32878. else {
  32879. return 0;
  32880. }
  32881. };
  32882. if (options) {
  32883. this.autoplay = options.autoplay || false;
  32884. this.loop = options.loop || false;
  32885. // if volume === 0, we need another way to check this option
  32886. if (options.volume !== undefined) {
  32887. this._volume = options.volume;
  32888. }
  32889. this.spatialSound = options.spatialSound || false;
  32890. this.maxDistance = options.maxDistance || 100;
  32891. this.useCustomAttenuation = options.useCustomAttenuation || false;
  32892. this.rolloffFactor = options.rolloffFactor || 1;
  32893. this.refDistance = options.refDistance || 1;
  32894. this.distanceModel = options.distanceModel || "linear";
  32895. this._playbackRate = options.playbackRate || 1;
  32896. }
  32897. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32898. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  32899. this._soundGain.gain.value = this._volume;
  32900. this._inputAudioNode = this._soundGain;
  32901. this._ouputAudioNode = this._soundGain;
  32902. if (this.spatialSound) {
  32903. this._createSpatialParameters();
  32904. }
  32905. this._scene.mainSoundTrack.AddSound(this);
  32906. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  32907. if (urlOrArrayBuffer) {
  32908. // If it's an URL
  32909. if (typeof (urlOrArrayBuffer) === "string") {
  32910. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  32911. }
  32912. else {
  32913. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  32914. this._soundLoaded(urlOrArrayBuffer);
  32915. }
  32916. else {
  32917. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  32918. }
  32919. }
  32920. }
  32921. }
  32922. else {
  32923. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  32924. this._scene.mainSoundTrack.AddSound(this);
  32925. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  32926. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  32927. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  32928. }
  32929. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  32930. if (this._readyToPlayCallback) {
  32931. window.setTimeout(function () {
  32932. _this._readyToPlayCallback();
  32933. }, 1000);
  32934. }
  32935. }
  32936. }
  32937. Sound.prototype.dispose = function () {
  32938. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  32939. if (this.isPlaying) {
  32940. this.stop();
  32941. }
  32942. this._isReadyToPlay = false;
  32943. if (this.soundTrackId === -1) {
  32944. this._scene.mainSoundTrack.RemoveSound(this);
  32945. }
  32946. else {
  32947. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  32948. }
  32949. if (this._soundGain) {
  32950. this._soundGain.disconnect();
  32951. this._soundGain = null;
  32952. }
  32953. if (this._soundPanner) {
  32954. this._soundPanner.disconnect();
  32955. this._soundPanner = null;
  32956. }
  32957. if (this._soundSource) {
  32958. this._soundSource.disconnect();
  32959. this._soundSource = null;
  32960. }
  32961. this._audioBuffer = null;
  32962. if (this._connectedMesh) {
  32963. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  32964. this._connectedMesh = null;
  32965. }
  32966. }
  32967. };
  32968. Sound.prototype._soundLoaded = function (audioData) {
  32969. var _this = this;
  32970. this._isLoaded = true;
  32971. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  32972. _this._audioBuffer = buffer;
  32973. _this._isReadyToPlay = true;
  32974. if (_this.autoplay) {
  32975. _this.play();
  32976. }
  32977. if (_this._readyToPlayCallback) {
  32978. _this._readyToPlayCallback();
  32979. }
  32980. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  32981. };
  32982. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  32983. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32984. this._audioBuffer = audioBuffer;
  32985. this._isReadyToPlay = true;
  32986. }
  32987. };
  32988. Sound.prototype.updateOptions = function (options) {
  32989. if (options) {
  32990. this.loop = options.loop || this.loop;
  32991. this.maxDistance = options.maxDistance || this.maxDistance;
  32992. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  32993. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  32994. this.refDistance = options.refDistance || this.refDistance;
  32995. this.distanceModel = options.distanceModel || this.distanceModel;
  32996. this._playbackRate = options.playbackRate || this._playbackRate;
  32997. this._updateSpatialParameters();
  32998. if (this.isPlaying) {
  32999. this._soundSource.playbackRate.value = this._playbackRate;
  33000. }
  33001. }
  33002. };
  33003. Sound.prototype._createSpatialParameters = function () {
  33004. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33005. if (this._scene.headphone) {
  33006. this._panningModel = "HRTF";
  33007. }
  33008. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33009. this._updateSpatialParameters();
  33010. this._soundPanner.connect(this._ouputAudioNode);
  33011. this._inputAudioNode = this._soundPanner;
  33012. }
  33013. };
  33014. Sound.prototype._updateSpatialParameters = function () {
  33015. if (this.spatialSound) {
  33016. if (this.useCustomAttenuation) {
  33017. // Tricks to disable in a way embedded Web Audio attenuation
  33018. this._soundPanner.distanceModel = "linear";
  33019. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33020. this._soundPanner.refDistance = 1;
  33021. this._soundPanner.rolloffFactor = 1;
  33022. this._soundPanner.panningModel = this._panningModel;
  33023. }
  33024. else {
  33025. this._soundPanner.distanceModel = this.distanceModel;
  33026. this._soundPanner.maxDistance = this.maxDistance;
  33027. this._soundPanner.refDistance = this.refDistance;
  33028. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33029. this._soundPanner.panningModel = this._panningModel;
  33030. }
  33031. }
  33032. };
  33033. Sound.prototype.switchPanningModelToHRTF = function () {
  33034. this._panningModel = "HRTF";
  33035. this._switchPanningModel();
  33036. };
  33037. Sound.prototype.switchPanningModelToEqualPower = function () {
  33038. this._panningModel = "equalpower";
  33039. this._switchPanningModel();
  33040. };
  33041. Sound.prototype._switchPanningModel = function () {
  33042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33043. this._soundPanner.panningModel = this._panningModel;
  33044. }
  33045. };
  33046. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33047. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33048. if (this._isOutputConnected) {
  33049. this._ouputAudioNode.disconnect();
  33050. }
  33051. this._ouputAudioNode.connect(soundTrackAudioNode);
  33052. this._isOutputConnected = true;
  33053. }
  33054. };
  33055. /**
  33056. * Transform this sound into a directional source
  33057. * @param coneInnerAngle Size of the inner cone in degree
  33058. * @param coneOuterAngle Size of the outer cone in degree
  33059. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33060. */
  33061. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33062. if (coneOuterAngle < coneInnerAngle) {
  33063. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33064. return;
  33065. }
  33066. this._coneInnerAngle = coneInnerAngle;
  33067. this._coneOuterAngle = coneOuterAngle;
  33068. this._coneOuterGain = coneOuterGain;
  33069. this._isDirectional = true;
  33070. if (this.isPlaying && this.loop) {
  33071. this.stop();
  33072. this.play();
  33073. }
  33074. };
  33075. Sound.prototype.setPosition = function (newPosition) {
  33076. this._position = newPosition;
  33077. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33078. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33079. }
  33080. };
  33081. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33082. this._localDirection = newLocalDirection;
  33083. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33084. this._updateDirection();
  33085. }
  33086. };
  33087. Sound.prototype._updateDirection = function () {
  33088. var mat = this._connectedMesh.getWorldMatrix();
  33089. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33090. direction.normalize();
  33091. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33092. };
  33093. Sound.prototype.updateDistanceFromListener = function () {
  33094. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33095. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33096. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33097. }
  33098. };
  33099. Sound.prototype.setAttenuationFunction = function (callback) {
  33100. this._customAttenuationFunction = callback;
  33101. };
  33102. /**
  33103. * Play the sound
  33104. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33105. */
  33106. Sound.prototype.play = function (time) {
  33107. var _this = this;
  33108. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33109. try {
  33110. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33111. if (!this._soundSource) {
  33112. if (this.spatialSound) {
  33113. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33114. if (this._isDirectional) {
  33115. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33116. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33117. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33118. if (this._connectedMesh) {
  33119. this._updateDirection();
  33120. }
  33121. else {
  33122. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33123. }
  33124. }
  33125. }
  33126. }
  33127. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33128. this._soundSource.buffer = this._audioBuffer;
  33129. this._soundSource.connect(this._inputAudioNode);
  33130. this._soundSource.loop = this.loop;
  33131. this._soundSource.playbackRate.value = this._playbackRate;
  33132. this._startTime = startTime;
  33133. this._soundSource.onended = function () { _this._onended(); };
  33134. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33135. this.isPlaying = true;
  33136. this.isPaused = false;
  33137. }
  33138. catch (ex) {
  33139. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33140. }
  33141. }
  33142. };
  33143. Sound.prototype._onended = function () {
  33144. this.isPlaying = false;
  33145. if (this.onended) {
  33146. this.onended();
  33147. }
  33148. };
  33149. /**
  33150. * Stop the sound
  33151. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33152. */
  33153. Sound.prototype.stop = function (time) {
  33154. if (this.isPlaying) {
  33155. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33156. this._soundSource.stop(stopTime);
  33157. this.isPlaying = false;
  33158. }
  33159. };
  33160. Sound.prototype.pause = function () {
  33161. if (this.isPlaying) {
  33162. this.stop(0);
  33163. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33164. this.isPaused = true;
  33165. }
  33166. };
  33167. Sound.prototype.setVolume = function (newVolume, time) {
  33168. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33169. if (time) {
  33170. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33171. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33172. }
  33173. else {
  33174. this._soundGain.gain.value = newVolume;
  33175. }
  33176. }
  33177. this._volume = newVolume;
  33178. };
  33179. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33180. this._playbackRate = newPlaybackRate;
  33181. if (this.isPlaying) {
  33182. this._soundSource.playbackRate.value = this._playbackRate;
  33183. }
  33184. };
  33185. Sound.prototype.getVolume = function () {
  33186. return this._volume;
  33187. };
  33188. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33189. var _this = this;
  33190. this._connectedMesh = meshToConnectTo;
  33191. if (!this.spatialSound) {
  33192. this.spatialSound = true;
  33193. this._createSpatialParameters();
  33194. if (this.isPlaying && this.loop) {
  33195. this.stop();
  33196. this.play();
  33197. }
  33198. }
  33199. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33200. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33201. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33202. };
  33203. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33204. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33205. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33206. this._updateDirection();
  33207. }
  33208. };
  33209. return Sound;
  33210. })();
  33211. BABYLON.Sound = Sound;
  33212. })(BABYLON || (BABYLON = {}));
  33213. var BABYLON;
  33214. (function (BABYLON) {
  33215. var SoundTrack = (function () {
  33216. function SoundTrack(scene, options) {
  33217. this.id = -1;
  33218. this._isMainTrack = false;
  33219. this._isInitialized = false;
  33220. this._scene = scene;
  33221. this.soundCollection = new Array();
  33222. this._options = options;
  33223. if (!this._isMainTrack) {
  33224. this._scene.soundTracks.push(this);
  33225. this.id = this._scene.soundTracks.length - 1;
  33226. }
  33227. }
  33228. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33230. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33231. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33232. if (this._options) {
  33233. if (this._options.volume) {
  33234. this._outputAudioNode.gain.value = this._options.volume;
  33235. }
  33236. if (this._options.mainTrack) {
  33237. this._isMainTrack = this._options.mainTrack;
  33238. }
  33239. }
  33240. this._isInitialized = true;
  33241. }
  33242. };
  33243. SoundTrack.prototype.dispose = function () {
  33244. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33245. if (this._connectedAnalyser) {
  33246. this._connectedAnalyser.stopDebugCanvas();
  33247. }
  33248. while (this.soundCollection.length) {
  33249. this.soundCollection[0].dispose();
  33250. }
  33251. if (this._outputAudioNode) {
  33252. this._outputAudioNode.disconnect();
  33253. }
  33254. this._outputAudioNode = null;
  33255. }
  33256. };
  33257. SoundTrack.prototype.AddSound = function (sound) {
  33258. if (!this._isInitialized) {
  33259. this._initializeSoundTrackAudioGraph();
  33260. }
  33261. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33262. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33263. }
  33264. if (sound.soundTrackId) {
  33265. if (sound.soundTrackId === -1) {
  33266. this._scene.mainSoundTrack.RemoveSound(sound);
  33267. }
  33268. else {
  33269. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33270. }
  33271. }
  33272. this.soundCollection.push(sound);
  33273. sound.soundTrackId = this.id;
  33274. };
  33275. SoundTrack.prototype.RemoveSound = function (sound) {
  33276. var index = this.soundCollection.indexOf(sound);
  33277. if (index !== -1) {
  33278. this.soundCollection.splice(index, 1);
  33279. }
  33280. };
  33281. SoundTrack.prototype.setVolume = function (newVolume) {
  33282. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33283. this._outputAudioNode.gain.value = newVolume;
  33284. }
  33285. };
  33286. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33288. for (var i = 0; i < this.soundCollection.length; i++) {
  33289. this.soundCollection[i].switchPanningModelToHRTF();
  33290. }
  33291. }
  33292. };
  33293. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33294. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33295. for (var i = 0; i < this.soundCollection.length; i++) {
  33296. this.soundCollection[i].switchPanningModelToEqualPower();
  33297. }
  33298. }
  33299. };
  33300. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33301. if (this._connectedAnalyser) {
  33302. this._connectedAnalyser.stopDebugCanvas();
  33303. }
  33304. this._connectedAnalyser = analyser;
  33305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33306. this._outputAudioNode.disconnect();
  33307. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33308. }
  33309. };
  33310. return SoundTrack;
  33311. })();
  33312. BABYLON.SoundTrack = SoundTrack;
  33313. })(BABYLON || (BABYLON = {}));
  33314. var BABYLON;
  33315. (function (BABYLON) {
  33316. var DepthRenderer = (function () {
  33317. function DepthRenderer(scene, type) {
  33318. var _this = this;
  33319. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  33320. this._viewMatrix = BABYLON.Matrix.Zero();
  33321. this._projectionMatrix = BABYLON.Matrix.Zero();
  33322. this._transformMatrix = BABYLON.Matrix.Zero();
  33323. this._worldViewProjection = BABYLON.Matrix.Zero();
  33324. this._scene = scene;
  33325. var engine = scene.getEngine();
  33326. // Render target
  33327. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  33328. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33329. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33330. this._depthMap.refreshRate = 1;
  33331. this._depthMap.renderParticles = false;
  33332. this._depthMap.renderList = null;
  33333. // set default depth value to 1.0 (far away)
  33334. this._depthMap.onClear = function (engine) {
  33335. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  33336. };
  33337. // Custom render function
  33338. var renderSubMesh = function (subMesh) {
  33339. var mesh = subMesh.getRenderingMesh();
  33340. var scene = _this._scene;
  33341. var engine = scene.getEngine();
  33342. // Culling
  33343. engine.setState(subMesh.getMaterial().backFaceCulling);
  33344. // Managing instances
  33345. var batch = mesh._getInstancesRenderList(subMesh._id);
  33346. if (batch.mustReturn) {
  33347. return;
  33348. }
  33349. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33350. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33351. engine.enableEffect(_this._effect);
  33352. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  33353. var material = subMesh.getMaterial();
  33354. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33355. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  33356. // Alpha test
  33357. if (material && material.needAlphaTesting()) {
  33358. var alphaTexture = material.getAlphaTestTexture();
  33359. _this._effect.setTexture("diffuseSampler", alphaTexture);
  33360. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33361. }
  33362. // Bones
  33363. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33364. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33365. }
  33366. // Draw
  33367. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33368. }
  33369. };
  33370. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  33371. var index;
  33372. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33373. renderSubMesh(opaqueSubMeshes.data[index]);
  33374. }
  33375. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33376. renderSubMesh(alphaTestSubMeshes.data[index]);
  33377. }
  33378. };
  33379. }
  33380. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  33381. var defines = [];
  33382. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33383. var mesh = subMesh.getMesh();
  33384. var scene = mesh.getScene();
  33385. var material = subMesh.getMaterial();
  33386. // Alpha test
  33387. if (material && material.needAlphaTesting()) {
  33388. defines.push("#define ALPHATEST");
  33389. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33390. attribs.push(BABYLON.VertexBuffer.UVKind);
  33391. defines.push("#define UV1");
  33392. }
  33393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33394. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33395. defines.push("#define UV2");
  33396. }
  33397. }
  33398. // Bones
  33399. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33400. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33401. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33402. defines.push("#define BONES");
  33403. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33404. }
  33405. // Instances
  33406. if (useInstances) {
  33407. defines.push("#define INSTANCES");
  33408. attribs.push("world0");
  33409. attribs.push("world1");
  33410. attribs.push("world2");
  33411. attribs.push("world3");
  33412. }
  33413. // Get correct effect
  33414. var join = defines.join("\n");
  33415. if (this._cachedDefines !== join) {
  33416. this._cachedDefines = join;
  33417. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  33418. }
  33419. return this._effect.isReady();
  33420. };
  33421. DepthRenderer.prototype.getDepthMap = function () {
  33422. return this._depthMap;
  33423. };
  33424. // Methods
  33425. DepthRenderer.prototype.dispose = function () {
  33426. this._depthMap.dispose();
  33427. };
  33428. return DepthRenderer;
  33429. })();
  33430. BABYLON.DepthRenderer = DepthRenderer;
  33431. })(BABYLON || (BABYLON = {}));
  33432. var BABYLON;
  33433. (function (BABYLON) {
  33434. var SSAORenderingPipeline = (function (_super) {
  33435. __extends(SSAORenderingPipeline, _super);
  33436. /**
  33437. * @constructor
  33438. * @param {string} name - The rendering pipeline name
  33439. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33440. * @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 }
  33441. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33442. */
  33443. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  33444. var _this = this;
  33445. _super.call(this, scene.getEngine(), name);
  33446. // Members
  33447. /**
  33448. * The PassPostProcess id in the pipeline that contains the original scene color
  33449. * @type {string}
  33450. */
  33451. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  33452. /**
  33453. * The SSAO PostProcess id in the pipeline
  33454. * @type {string}
  33455. */
  33456. this.SSAORenderEffect = "SSAORenderEffect";
  33457. /**
  33458. * The horizontal blur PostProcess id in the pipeline
  33459. * @type {string}
  33460. */
  33461. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  33462. /**
  33463. * The vertical blur PostProcess id in the pipeline
  33464. * @type {string}
  33465. */
  33466. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  33467. /**
  33468. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  33469. * @type {string}
  33470. */
  33471. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  33472. /**
  33473. * The output strength of the SSAO post-process. Default value is 1.0.
  33474. * @type {number}
  33475. */
  33476. this.totalStrength = 1.0;
  33477. /**
  33478. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  33479. * @type {number}
  33480. */
  33481. this.radius = 0.0002;
  33482. /**
  33483. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  33484. * Must not be equal to fallOff and superior to fallOff.
  33485. * Default value is 0.0075
  33486. * @type {number}
  33487. */
  33488. this.area = 0.0075;
  33489. /**
  33490. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  33491. * Must not be equal to area and inferior to area.
  33492. * Default value is 0.0002
  33493. * @type {number}
  33494. */
  33495. this.fallOff = 0.0002;
  33496. this._firstUpdate = true;
  33497. this._scene = scene;
  33498. // Set up assets
  33499. this._createRandomTexture();
  33500. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33501. var ssaoRatio = ratio.ssaoRatio || ratio;
  33502. var combineRatio = ratio.combineRatio || ratio;
  33503. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33504. this._createSSAOPostProcess(ssaoRatio);
  33505. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33506. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33507. this._createSSAOCombinePostProcess(combineRatio);
  33508. // Set up pipeline
  33509. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  33510. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  33511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  33512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  33513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  33514. // Finish
  33515. scene.postProcessRenderPipelineManager.addPipeline(this);
  33516. if (cameras)
  33517. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33518. }
  33519. // Public Methods
  33520. /**
  33521. * Returns the horizontal blur PostProcess
  33522. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  33523. */
  33524. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  33525. return this._blurHPostProcess;
  33526. };
  33527. /**
  33528. * Returns the vertical blur PostProcess
  33529. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  33530. */
  33531. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  33532. return this._blurVPostProcess;
  33533. };
  33534. /**
  33535. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  33536. */
  33537. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33538. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33539. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33540. this._originalColorPostProcess = undefined;
  33541. this._ssaoPostProcess = undefined;
  33542. this._blurHPostProcess = undefined;
  33543. this._blurVPostProcess = undefined;
  33544. this._ssaoCombinePostProcess = undefined;
  33545. this._randomTexture.dispose();
  33546. if (disableDepthRender)
  33547. this._scene.disableDepthRenderer();
  33548. };
  33549. // Private Methods
  33550. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  33551. var _this = this;
  33552. var sampleSphere = [
  33553. 0.5381, 0.1856, -0.4319,
  33554. 0.1379, 0.2486, 0.4430,
  33555. 0.3371, 0.5679, -0.0057,
  33556. -0.6999, -0.0451, -0.0019,
  33557. 0.0689, -0.1598, -0.8547,
  33558. 0.0560, 0.0069, -0.1843,
  33559. -0.0146, 0.1402, 0.0762,
  33560. 0.0100, -0.1924, -0.0344,
  33561. -0.3577, -0.5301, -0.4358,
  33562. -0.3169, 0.1063, 0.0158,
  33563. 0.0103, -0.5869, 0.0046,
  33564. -0.0897, -0.4940, 0.3287,
  33565. 0.7119, -0.0154, -0.0918,
  33566. -0.0533, 0.0596, -0.5411,
  33567. 0.0352, -0.0631, 0.5460,
  33568. -0.4776, 0.2847, -0.0271
  33569. ];
  33570. var samplesFactor = 1.0 / 16.0;
  33571. 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);
  33572. this._ssaoPostProcess.onApply = function (effect) {
  33573. if (_this._firstUpdate) {
  33574. effect.setArray3("sampleSphere", sampleSphere);
  33575. effect.setFloat("samplesFactor", samplesFactor);
  33576. effect.setFloat("randTextureTiles", 4.0 / ratio);
  33577. _this._firstUpdate = false;
  33578. }
  33579. effect.setFloat("totalStrength", _this.totalStrength);
  33580. effect.setFloat("radius", _this.radius);
  33581. effect.setFloat("area", _this.area);
  33582. effect.setFloat("fallOff", _this.fallOff);
  33583. effect.setTexture("textureSampler", _this._depthTexture);
  33584. effect.setTexture("randomSampler", _this._randomTexture);
  33585. };
  33586. };
  33587. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  33588. var _this = this;
  33589. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33590. this._ssaoCombinePostProcess.onApply = function (effect) {
  33591. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  33592. };
  33593. };
  33594. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  33595. var size = 512;
  33596. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33597. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33598. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33599. var context = this._randomTexture.getContext();
  33600. var rand = function (min, max) {
  33601. return Math.random() * (max - min) + min;
  33602. };
  33603. for (var x = 0; x < size; x++) {
  33604. for (var y = 0; y < size; y++) {
  33605. var randVector = BABYLON.Vector3.Zero();
  33606. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33607. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33608. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33609. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33610. context.fillRect(x, y, 1, 1);
  33611. }
  33612. }
  33613. this._randomTexture.update(false);
  33614. };
  33615. return SSAORenderingPipeline;
  33616. })(BABYLON.PostProcessRenderPipeline);
  33617. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33618. })(BABYLON || (BABYLON = {}));
  33619. var BABYLON;
  33620. (function (BABYLON) {
  33621. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33622. var VolumetricLightScatteringPostProcess = (function (_super) {
  33623. __extends(VolumetricLightScatteringPostProcess, _super);
  33624. /**
  33625. * @constructor
  33626. * @param {string} name - The post-process name
  33627. * @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)
  33628. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33629. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33630. * @param {number} samples - The post-process quality, default 100
  33631. * @param {number} samplingMode - The post-process filtering mode
  33632. * @param {BABYLON.Engine} engine - The babylon engine
  33633. * @param {boolean} reusable - If the post-process is reusable
  33634. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33635. */
  33636. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33637. var _this = this;
  33638. if (samples === void 0) { samples = 100; }
  33639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33640. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33641. this._screenCoordinates = BABYLON.Vector2.Zero();
  33642. /**
  33643. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33644. * @type {boolean}
  33645. */
  33646. this.useCustomMeshPosition = false;
  33647. /**
  33648. * If the post-process should inverse the light scattering direction
  33649. * @type {boolean}
  33650. */
  33651. this.invert = true;
  33652. /**
  33653. * Set to true to use the diffuseColor instead of the diffuseTexture
  33654. * @type {boolean}
  33655. */
  33656. this.useDiffuseColor = false;
  33657. /**
  33658. * Array containing the excluded meshes not rendered in the internal pass
  33659. */
  33660. this.excludedMeshes = new Array();
  33661. /**
  33662. * Controls the overall intensity of the post-process
  33663. * @type {number}
  33664. */
  33665. this.exposure = 0.3;
  33666. /**
  33667. * Dissipates each sample's contribution in range [0, 1]
  33668. * @type {number}
  33669. */
  33670. this.decay = 0.96815;
  33671. /**
  33672. * Controls the overall intensity of each sample
  33673. * @type {number}
  33674. */
  33675. this.weight = 0.58767;
  33676. /**
  33677. * Controls the density of each sample
  33678. * @type {number}
  33679. */
  33680. this.density = 0.926;
  33681. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33682. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33683. // Configure mesh
  33684. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33685. // Configure
  33686. this._createPass(scene, ratio.passRatio || ratio);
  33687. this.onApply = function (effect) {
  33688. _this._updateMeshScreenCoordinates(scene);
  33689. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33690. effect.setFloat("exposure", _this.exposure);
  33691. effect.setFloat("decay", _this.decay);
  33692. effect.setFloat("weight", _this.weight);
  33693. effect.setFloat("density", _this.density);
  33694. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33695. };
  33696. }
  33697. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33698. var mesh = subMesh.getMesh();
  33699. var defines = [];
  33700. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33701. var material = subMesh.getMaterial();
  33702. var needUV = false;
  33703. // Render this.mesh as default
  33704. if (mesh === this.mesh) {
  33705. if (this.useDiffuseColor) {
  33706. defines.push("#define DIFFUSE_COLOR_RENDER");
  33707. }
  33708. else if (material) {
  33709. if (material.diffuseTexture !== undefined) {
  33710. defines.push("#define BASIC_RENDER");
  33711. }
  33712. else {
  33713. defines.push("#define DIFFUSE_COLOR_RENDER");
  33714. }
  33715. }
  33716. defines.push("#define NEED_UV");
  33717. needUV = true;
  33718. }
  33719. // Alpha test
  33720. if (material) {
  33721. if (material.needAlphaTesting()) {
  33722. defines.push("#define ALPHATEST");
  33723. }
  33724. if (material.opacityTexture !== undefined) {
  33725. defines.push("#define OPACITY");
  33726. if (material.opacityTexture.getAlphaFromRGB) {
  33727. defines.push("#define OPACITYRGB");
  33728. }
  33729. if (!needUV) {
  33730. defines.push("#define NEED_UV");
  33731. }
  33732. }
  33733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33734. attribs.push(BABYLON.VertexBuffer.UVKind);
  33735. defines.push("#define UV1");
  33736. }
  33737. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33738. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33739. defines.push("#define UV2");
  33740. }
  33741. }
  33742. // Bones
  33743. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33746. defines.push("#define BONES");
  33747. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33748. }
  33749. // Instances
  33750. if (useInstances) {
  33751. defines.push("#define INSTANCES");
  33752. attribs.push("world0");
  33753. attribs.push("world1");
  33754. attribs.push("world2");
  33755. attribs.push("world3");
  33756. }
  33757. // Get correct effect
  33758. var join = defines.join("\n");
  33759. if (this._cachedDefines !== join) {
  33760. this._cachedDefines = join;
  33761. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33762. }
  33763. return this._volumetricLightScatteringPass.isReady();
  33764. };
  33765. /**
  33766. * Sets the new light position for light scattering effect
  33767. * @param {BABYLON.Vector3} The new custom light position
  33768. */
  33769. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33770. this._customMeshPosition = position;
  33771. };
  33772. /**
  33773. * Returns the light position for light scattering effect
  33774. * @return {BABYLON.Vector3} The custom light position
  33775. */
  33776. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33777. return this._customMeshPosition;
  33778. };
  33779. /**
  33780. * Disposes the internal assets and detaches the post-process from the camera
  33781. */
  33782. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33783. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33784. if (rttIndex !== -1) {
  33785. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33786. }
  33787. this._volumetricLightScatteringRTT.dispose();
  33788. _super.prototype.dispose.call(this, camera);
  33789. };
  33790. /**
  33791. * Returns the render target texture used by the post-process
  33792. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33793. */
  33794. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33795. return this._volumetricLightScatteringRTT;
  33796. };
  33797. // Private methods
  33798. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33799. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33800. return true;
  33801. }
  33802. return false;
  33803. };
  33804. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33805. var _this = this;
  33806. var engine = scene.getEngine();
  33807. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33808. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33809. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33810. this._volumetricLightScatteringRTT.renderList = null;
  33811. this._volumetricLightScatteringRTT.renderParticles = false;
  33812. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33813. // Custom render function for submeshes
  33814. var renderSubMesh = function (subMesh) {
  33815. var mesh = subMesh.getRenderingMesh();
  33816. if (_this._meshExcluded(mesh)) {
  33817. return;
  33818. }
  33819. var scene = mesh.getScene();
  33820. var engine = scene.getEngine();
  33821. // Culling
  33822. engine.setState(subMesh.getMaterial().backFaceCulling);
  33823. // Managing instances
  33824. var batch = mesh._getInstancesRenderList(subMesh._id);
  33825. if (batch.mustReturn) {
  33826. return;
  33827. }
  33828. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33829. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33830. engine.enableEffect(_this._volumetricLightScatteringPass);
  33831. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33832. var material = subMesh.getMaterial();
  33833. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33834. // Alpha test
  33835. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33836. var alphaTexture = material.getAlphaTestTexture();
  33837. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33838. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33839. }
  33840. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33841. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33842. if (alphaTexture) {
  33843. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33844. }
  33845. }
  33846. if (material.opacityTexture !== undefined) {
  33847. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33848. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33849. }
  33850. }
  33851. // Bones
  33852. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33853. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33854. }
  33855. // Draw
  33856. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33857. }
  33858. };
  33859. // Render target texture callbacks
  33860. var savedSceneClearColor;
  33861. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33862. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33863. savedSceneClearColor = scene.clearColor;
  33864. scene.clearColor = sceneClearColor;
  33865. };
  33866. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33867. scene.clearColor = savedSceneClearColor;
  33868. };
  33869. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33870. var engine = scene.getEngine();
  33871. var index;
  33872. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33873. renderSubMesh(opaqueSubMeshes.data[index]);
  33874. }
  33875. engine.setAlphaTesting(true);
  33876. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33877. renderSubMesh(alphaTestSubMeshes.data[index]);
  33878. }
  33879. engine.setAlphaTesting(false);
  33880. if (transparentSubMeshes.length) {
  33881. // Sort sub meshes
  33882. for (index = 0; index < transparentSubMeshes.length; index++) {
  33883. var submesh = transparentSubMeshes.data[index];
  33884. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33885. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33886. }
  33887. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33888. sortedArray.sort(function (a, b) {
  33889. // Alpha index first
  33890. if (a._alphaIndex > b._alphaIndex) {
  33891. return 1;
  33892. }
  33893. if (a._alphaIndex < b._alphaIndex) {
  33894. return -1;
  33895. }
  33896. // Then distance to camera
  33897. if (a._distanceToCamera < b._distanceToCamera) {
  33898. return 1;
  33899. }
  33900. if (a._distanceToCamera > b._distanceToCamera) {
  33901. return -1;
  33902. }
  33903. return 0;
  33904. });
  33905. // Render sub meshes
  33906. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33907. for (index = 0; index < sortedArray.length; index++) {
  33908. renderSubMesh(sortedArray[index]);
  33909. }
  33910. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33911. }
  33912. };
  33913. };
  33914. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  33915. var transform = scene.getTransformMatrix();
  33916. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  33917. this._screenCoordinates.x = pos.x / this._viewPort.width;
  33918. this._screenCoordinates.y = pos.y / this._viewPort.height;
  33919. if (this.invert)
  33920. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  33921. };
  33922. // Static methods
  33923. /**
  33924. * Creates a default mesh for the Volumeric Light Scattering post-process
  33925. * @param {string} The mesh name
  33926. * @param {BABYLON.Scene} The scene where to create the mesh
  33927. * @return {BABYLON.Mesh} the default mesh
  33928. */
  33929. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  33930. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  33931. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  33932. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  33933. return mesh;
  33934. };
  33935. return VolumetricLightScatteringPostProcess;
  33936. })(BABYLON.PostProcess);
  33937. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  33938. })(BABYLON || (BABYLON = {}));
  33939. var BABYLON;
  33940. (function (BABYLON) {
  33941. var LensRenderingPipeline = (function (_super) {
  33942. __extends(LensRenderingPipeline, _super);
  33943. /**
  33944. * @constructor
  33945. *
  33946. * Effect parameters are as follow:
  33947. * {
  33948. * chromatic_aberration: number; // from 0 to x (1 for realism)
  33949. * edge_blur: number; // from 0 to x (1 for realism)
  33950. * distortion: number; // from 0 to x (1 for realism)
  33951. * grain_amount: number; // from 0 to 1
  33952. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  33953. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  33954. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  33955. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  33956. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  33957. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  33958. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  33959. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  33960. * }
  33961. * Note: if an effect parameter is unset, effect is disabled
  33962. *
  33963. * @param {string} name - The rendering pipeline name
  33964. * @param {object} parameters - An object containing all parameters (see above)
  33965. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33966. * @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)
  33967. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33968. */
  33969. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  33970. var _this = this;
  33971. if (ratio === void 0) { ratio = 1.0; }
  33972. _super.call(this, scene.getEngine(), name);
  33973. // Lens effects can be of the following:
  33974. // - chromatic aberration (slight shift of RGB colors)
  33975. // - blur on the edge of the lens
  33976. // - lens distortion
  33977. // - depth-of-field blur & highlights enhancing
  33978. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  33979. // - grain effect (noise or custom texture)
  33980. // Two additional texture samplers are needed:
  33981. // - depth map (for depth-of-field)
  33982. // - grain texture
  33983. /**
  33984. * The chromatic aberration PostProcess id in the pipeline
  33985. * @type {string}
  33986. */
  33987. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  33988. /**
  33989. * The highlights enhancing PostProcess id in the pipeline
  33990. * @type {string}
  33991. */
  33992. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  33993. /**
  33994. * The depth-of-field PostProcess id in the pipeline
  33995. * @type {string}
  33996. */
  33997. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  33998. this._scene = scene;
  33999. // Fetch texture samplers
  34000. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34001. if (parameters.grain_texture) {
  34002. this._grainTexture = parameters.grain_texture;
  34003. }
  34004. else {
  34005. this._createGrainTexture();
  34006. }
  34007. // save parameters
  34008. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34009. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34010. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34011. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34012. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34013. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34014. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34015. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34016. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34017. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34018. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34019. // Create effects
  34020. this._createChromaticAberrationPostProcess(ratio);
  34021. this._createHighlightsPostProcess(ratio);
  34022. this._createDepthOfFieldPostProcess(ratio / 4);
  34023. // Set up pipeline
  34024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34027. if (this._highlightsGain == -1) {
  34028. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34029. }
  34030. // Finish
  34031. scene.postProcessRenderPipelineManager.addPipeline(this);
  34032. if (cameras) {
  34033. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34034. }
  34035. }
  34036. // public methods (self explanatory)
  34037. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34038. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34039. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34040. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34041. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34042. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34043. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34044. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34045. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34046. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34047. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34048. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34049. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  34050. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  34051. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34052. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34053. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34054. this._highlightsGain = amount;
  34055. };
  34056. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34057. if (this._highlightsGain == -1) {
  34058. this._highlightsGain = 1.0;
  34059. }
  34060. this._highlightsThreshold = amount;
  34061. };
  34062. LensRenderingPipeline.prototype.disableHighlights = function () {
  34063. this._highlightsGain = -1;
  34064. };
  34065. /**
  34066. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34067. */
  34068. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34069. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34070. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34071. this._chromaticAberrationPostProcess = undefined;
  34072. this._highlightsPostProcess = undefined;
  34073. this._depthOfFieldPostProcess = undefined;
  34074. this._grainTexture.dispose();
  34075. if (disableDepthRender)
  34076. this._scene.disableDepthRenderer();
  34077. };
  34078. // colors shifting and distortion
  34079. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34080. var _this = this;
  34081. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34082. [], // samplers
  34083. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34084. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34085. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34086. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34087. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34088. };
  34089. };
  34090. // highlights enhancing
  34091. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34092. var _this = this;
  34093. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  34094. [], // samplers
  34095. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34096. this._highlightsPostProcess.onApply = function (effect) {
  34097. effect.setFloat('gain', _this._highlightsGain);
  34098. effect.setFloat('threshold', _this._highlightsThreshold);
  34099. effect.setBool('pentagon', _this._dofPentagon);
  34100. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34101. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34102. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34103. };
  34104. };
  34105. // colors shifting and distortion
  34106. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34107. var _this = this;
  34108. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34109. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34110. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34111. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34112. this._depthOfFieldPostProcess.onApply = function (effect) {
  34113. effect.setTexture("depthSampler", _this._depthTexture);
  34114. effect.setTexture("grainSampler", _this._grainTexture);
  34115. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34116. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34117. effect.setFloat('grain_amount', _this._grainAmount);
  34118. effect.setBool('blur_noise', _this._blurNoise);
  34119. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34120. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34121. effect.setFloat('distortion', _this._distortion);
  34122. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  34123. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34124. effect.setFloat('aperture', _this._dofAperture);
  34125. effect.setFloat('darken', _this._dofDarken);
  34126. effect.setFloat('edge_blur', _this._edgeBlur);
  34127. effect.setBool('highlights', (_this._highlightsGain != -1));
  34128. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34129. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34130. };
  34131. };
  34132. // creates a black and white random noise texture, 512x512
  34133. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34134. var size = 512;
  34135. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34136. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34137. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34138. var context = this._grainTexture.getContext();
  34139. var rand = function (min, max) {
  34140. return Math.random() * (max - min) + min;
  34141. };
  34142. var value;
  34143. for (var x = 0; x < size; x++) {
  34144. for (var y = 0; y < size; y++) {
  34145. value = Math.floor(rand(0.42, 0.58) * 255);
  34146. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34147. context.fillRect(x, y, 1, 1);
  34148. }
  34149. }
  34150. this._grainTexture.update(false);
  34151. };
  34152. return LensRenderingPipeline;
  34153. })(BABYLON.PostProcessRenderPipeline);
  34154. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34155. })(BABYLON || (BABYLON = {}));
  34156. //
  34157. // This post-process allows the modification of rendered colors by using
  34158. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34159. //
  34160. // The object needs to be provided an url to a texture containing the color
  34161. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34162. // Use an image editing software to tweak the LUT to match your needs.
  34163. //
  34164. // For an example of a color LUT, see here:
  34165. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34166. // For explanations on color grading, see here:
  34167. // http://udn.epicgames.com/Three/ColorGrading.html
  34168. //
  34169. var BABYLON;
  34170. (function (BABYLON) {
  34171. var ColorCorrectionPostProcess = (function (_super) {
  34172. __extends(ColorCorrectionPostProcess, _super);
  34173. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34174. var _this = this;
  34175. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34176. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34177. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34178. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34179. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34180. this.onApply = function (effect) {
  34181. effect.setTexture("colorTable", _this._colorTableTexture);
  34182. };
  34183. }
  34184. return ColorCorrectionPostProcess;
  34185. })(BABYLON.PostProcess);
  34186. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34187. })(BABYLON || (BABYLON = {}));
  34188. var BABYLON;
  34189. (function (BABYLON) {
  34190. var AnaglyphFreeCamera = (function (_super) {
  34191. __extends(AnaglyphFreeCamera, _super);
  34192. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34193. _super.call(this, name, position, scene);
  34194. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34195. }
  34196. return AnaglyphFreeCamera;
  34197. })(BABYLON.FreeCamera);
  34198. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  34199. var AnaglyphArcRotateCamera = (function (_super) {
  34200. __extends(AnaglyphArcRotateCamera, _super);
  34201. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  34202. _super.call(this, name, alpha, beta, radius, target, scene);
  34203. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34204. }
  34205. return AnaglyphArcRotateCamera;
  34206. })(BABYLON.ArcRotateCamera);
  34207. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  34208. var AnaglyphGamepadCamera = (function (_super) {
  34209. __extends(AnaglyphGamepadCamera, _super);
  34210. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  34211. _super.call(this, name, position, scene);
  34212. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34213. }
  34214. return AnaglyphGamepadCamera;
  34215. })(BABYLON.GamepadCamera);
  34216. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  34217. var StereoscopicFreeCamera = (function (_super) {
  34218. __extends(StereoscopicFreeCamera, _super);
  34219. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34220. _super.call(this, name, position, scene);
  34221. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34222. }
  34223. return StereoscopicFreeCamera;
  34224. })(BABYLON.FreeCamera);
  34225. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  34226. var StereoscopicArcRotateCamera = (function (_super) {
  34227. __extends(StereoscopicArcRotateCamera, _super);
  34228. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  34229. _super.call(this, name, alpha, beta, radius, target, scene);
  34230. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34231. }
  34232. return StereoscopicArcRotateCamera;
  34233. })(BABYLON.ArcRotateCamera);
  34234. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  34235. var StereoscopicGamepadCamera = (function (_super) {
  34236. __extends(StereoscopicGamepadCamera, _super);
  34237. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34238. _super.call(this, name, position, scene);
  34239. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34240. }
  34241. return StereoscopicGamepadCamera;
  34242. })(BABYLON.GamepadCamera);
  34243. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  34244. })(BABYLON || (BABYLON = {}));
  34245. var BABYLON;
  34246. (function (BABYLON) {
  34247. var HDRRenderingPipeline = (function (_super) {
  34248. __extends(HDRRenderingPipeline, _super);
  34249. /**
  34250. * @constructor
  34251. * @param {string} name - The rendering pipeline name
  34252. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34253. * @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)
  34254. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  34255. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34256. */
  34257. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  34258. var _this = this;
  34259. if (originalPostProcess === void 0) { originalPostProcess = null; }
  34260. _super.call(this, scene.getEngine(), name);
  34261. /**
  34262. * Public members
  34263. */
  34264. // Gaussian Blur
  34265. /**
  34266. * Gaussian blur coefficient
  34267. * @type {number}
  34268. */
  34269. this.gaussCoeff = 0.3;
  34270. /**
  34271. * Gaussian blur mean
  34272. * @type {number}
  34273. */
  34274. this.gaussMean = 1.0;
  34275. /**
  34276. * Gaussian blur standard deviation
  34277. * @type {number}
  34278. */
  34279. this.gaussStandDev = 0.8;
  34280. // HDR
  34281. /**
  34282. * Exposure, controls the overall intensity of the pipeline
  34283. * @type {number}
  34284. */
  34285. this.exposure = 1.0;
  34286. /**
  34287. * Minimum luminance that the post-process can output. Luminance is >= 0
  34288. * @type {number}
  34289. */
  34290. this.minimumLuminance = 1.0;
  34291. /**
  34292. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  34293. * @type {number}
  34294. */
  34295. this.maximumLuminance = 1e20;
  34296. /**
  34297. * Increase rate for luminance: eye adaptation speed to dark
  34298. * @type {number}
  34299. */
  34300. this.luminanceIncreaserate = 0.5;
  34301. /**
  34302. * Decrease rate for luminance: eye adaptation speed to bright
  34303. * @type {number}
  34304. */
  34305. this.luminanceDecreaseRate = 0.5;
  34306. // Bright pass
  34307. /**
  34308. * Minimum luminance needed to compute HDR
  34309. * @type {number}
  34310. */
  34311. this.brightThreshold = 0.8;
  34312. this._needUpdate = true;
  34313. this._scene = scene;
  34314. // Bright pass
  34315. this._createBrightPassPostProcess(scene, ratio);
  34316. // Down sample X4
  34317. this._createDownSampleX4PostProcess(scene, ratio);
  34318. // Create gaussian blur post-processes
  34319. this._createGaussianBlurPostProcess(scene, ratio);
  34320. // Texture adder
  34321. this._createTextureAdderPostProcess(scene, ratio);
  34322. // Luminance generator
  34323. this._createLuminanceGeneratorPostProcess(scene);
  34324. // HDR
  34325. this._createHDRPostProcess(scene, ratio);
  34326. // Pass postprocess
  34327. if (originalPostProcess === null) {
  34328. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34329. }
  34330. else {
  34331. this._originalPostProcess = originalPostProcess;
  34332. }
  34333. // Configure pipeline
  34334. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  34335. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  34336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  34337. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  34338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  34339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  34340. var addDownSamplerPostProcess = function (id) {
  34341. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  34342. };
  34343. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34344. addDownSamplerPostProcess(i);
  34345. }
  34346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  34347. // Finish
  34348. scene.postProcessRenderPipelineManager.addPipeline(this);
  34349. if (cameras !== null) {
  34350. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34351. }
  34352. this.update();
  34353. }
  34354. /**
  34355. * Tells the pipeline to update its post-processes
  34356. */
  34357. HDRRenderingPipeline.prototype.update = function () {
  34358. this._needUpdate = true;
  34359. };
  34360. /**
  34361. * Returns the current calculated luminance
  34362. */
  34363. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  34364. return this._hdrCurrentLuminance;
  34365. };
  34366. /**
  34367. * Returns the currently drawn luminance
  34368. */
  34369. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  34370. return this._hdrOutputLuminance;
  34371. };
  34372. /**
  34373. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  34374. */
  34375. HDRRenderingPipeline.prototype.dispose = function () {
  34376. this._originalPostProcess = undefined;
  34377. this._brightPassPostProcess = undefined;
  34378. this._downSampleX4PostProcess = undefined;
  34379. this._guassianBlurHPostProcess = undefined;
  34380. this._guassianBlurVPostProcess = undefined;
  34381. this._textureAdderPostProcess = undefined;
  34382. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34383. this._downSamplePostProcesses[i] = undefined;
  34384. }
  34385. this._hdrPostProcess = undefined;
  34386. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34387. };
  34388. /**
  34389. * Creates the HDR post-process and computes the luminance adaptation
  34390. */
  34391. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  34392. var _this = this;
  34393. var hdrLastLuminance = 0.0;
  34394. this._hdrOutputLuminance = -1.0;
  34395. this._hdrCurrentLuminance = 1.0;
  34396. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  34397. this._hdrPostProcess.onApply = function (effect) {
  34398. if (_this._hdrOutputLuminance < 0.0) {
  34399. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34400. }
  34401. else {
  34402. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  34403. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  34404. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  34405. }
  34406. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  34407. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  34408. }
  34409. else {
  34410. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34411. }
  34412. }
  34413. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  34414. hdrLastLuminance += scene.getEngine().getDeltaTime();
  34415. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34416. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34417. effect.setFloat("exposure", _this.exposure);
  34418. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  34419. _this._needUpdate = false;
  34420. };
  34421. };
  34422. /**
  34423. * Texture Adder post-process
  34424. */
  34425. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  34426. var _this = this;
  34427. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  34428. this._textureAdderPostProcess.onApply = function (effect) {
  34429. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34430. };
  34431. };
  34432. /**
  34433. * Down sample X4 post-process
  34434. */
  34435. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  34436. var _this = this;
  34437. var downSampleX4Offsets = new Array(32);
  34438. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  34439. this._downSampleX4PostProcess.onApply = function (effect) {
  34440. if (_this._needUpdate) {
  34441. var id = 0;
  34442. for (var i = -2; i < 2; i++) {
  34443. for (var j = -2; j < 2; j++) {
  34444. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  34445. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  34446. id += 2;
  34447. }
  34448. }
  34449. }
  34450. effect.setArray2("dsOffsets", downSampleX4Offsets);
  34451. };
  34452. };
  34453. /**
  34454. * Bright pass post-process
  34455. */
  34456. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  34457. var _this = this;
  34458. var brightOffsets = new Array(8);
  34459. var brightPassCallback = function (effect) {
  34460. if (_this._needUpdate) {
  34461. var sU = (1.0 / _this._brightPassPostProcess.width);
  34462. var sV = (1.0 / _this._brightPassPostProcess.height);
  34463. brightOffsets[0] = -0.5 * sU;
  34464. brightOffsets[1] = 0.5 * sV;
  34465. brightOffsets[2] = 0.5 * sU;
  34466. brightOffsets[3] = 0.5 * sV;
  34467. brightOffsets[4] = -0.5 * sU;
  34468. brightOffsets[5] = -0.5 * sV;
  34469. brightOffsets[6] = 0.5 * sU;
  34470. brightOffsets[7] = -0.5 * sV;
  34471. }
  34472. effect.setArray2("dsOffsets", brightOffsets);
  34473. effect.setFloat("brightThreshold", _this.brightThreshold);
  34474. };
  34475. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  34476. this._brightPassPostProcess.onApply = brightPassCallback;
  34477. };
  34478. /**
  34479. * Luminance generator. Creates the luminance post-process and down sample post-processes
  34480. */
  34481. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  34482. var _this = this;
  34483. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  34484. var luminanceOffsets = new Array(8);
  34485. var downSampleOffsets = new Array(18);
  34486. var halfDestPixelSize;
  34487. this._downSamplePostProcesses = new Array(lumSteps);
  34488. // Utils for luminance
  34489. var luminanceUpdateSourceOffsets = function (width, height) {
  34490. var sU = (1.0 / width);
  34491. var sV = (1.0 / height);
  34492. luminanceOffsets[0] = -0.5 * sU;
  34493. luminanceOffsets[1] = 0.5 * sV;
  34494. luminanceOffsets[2] = 0.5 * sU;
  34495. luminanceOffsets[3] = 0.5 * sV;
  34496. luminanceOffsets[4] = -0.5 * sU;
  34497. luminanceOffsets[5] = -0.5 * sV;
  34498. luminanceOffsets[6] = 0.5 * sU;
  34499. luminanceOffsets[7] = -0.5 * sV;
  34500. };
  34501. var luminanceUpdateDestOffsets = function (width, height) {
  34502. var id = 0;
  34503. for (var x = -1; x < 2; x++) {
  34504. for (var y = -1; y < 2; y++) {
  34505. downSampleOffsets[id] = (x) / width;
  34506. downSampleOffsets[id + 1] = (y) / height;
  34507. id += 2;
  34508. }
  34509. }
  34510. };
  34511. // Luminance callback
  34512. var luminanceCallback = function (effect) {
  34513. if (_this._needUpdate) {
  34514. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  34515. }
  34516. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34517. effect.setArray2("lumOffsets", luminanceOffsets);
  34518. };
  34519. // Down sample callbacks
  34520. var downSampleCallback = function (indice) {
  34521. var i = indice;
  34522. return function (effect) {
  34523. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34524. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34525. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  34526. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  34527. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  34528. effect.setArray2("dsOffsets", downSampleOffsets);
  34529. };
  34530. };
  34531. var downSampleAfterRenderCallback = function (effect) {
  34532. // Unpack result
  34533. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  34534. 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);
  34535. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  34536. };
  34537. // Create luminance post-process
  34538. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  34539. 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);
  34540. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  34541. // Create down sample post-processes
  34542. for (var i = lumSteps - 2; i >= 0; i--) {
  34543. var length = Math.pow(3, i);
  34544. ratio = { width: length, height: length };
  34545. var defines = "#define DOWN_SAMPLE\n";
  34546. if (i === 0) {
  34547. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  34548. }
  34549. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  34550. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  34551. if (i === 0) {
  34552. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  34553. }
  34554. }
  34555. };
  34556. /**
  34557. * Gaussian blur post-processes. Horizontal and Vertical
  34558. */
  34559. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  34560. var _this = this;
  34561. var blurOffsetsW = new Array(9);
  34562. var blurOffsetsH = new Array(9);
  34563. var blurWeights = new Array(9);
  34564. var uniforms = ["blurOffsets", "blurWeights"];
  34565. // Utils for gaussian blur
  34566. var calculateBlurOffsets = function (height) {
  34567. var lastOutputDimensions = {
  34568. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  34569. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  34570. };
  34571. for (var i = 0; i < 9; i++) {
  34572. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  34573. if (height) {
  34574. blurOffsetsH[i] = value;
  34575. }
  34576. else {
  34577. blurOffsetsW[i] = value;
  34578. }
  34579. }
  34580. };
  34581. var calculateWeights = function () {
  34582. var x = 0.0;
  34583. for (var i = 0; i < 9; i++) {
  34584. x = (i - 4.0) / 4.0;
  34585. 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));
  34586. }
  34587. };
  34588. // Callback
  34589. var gaussianBlurCallback = function (height) {
  34590. return function (effect) {
  34591. if (_this._needUpdate) {
  34592. calculateWeights();
  34593. calculateBlurOffsets(height);
  34594. }
  34595. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  34596. effect.setArray("blurWeights", blurWeights);
  34597. };
  34598. };
  34599. // Create horizontal gaussian blur post-processes
  34600. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  34601. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34602. // Create vertical gaussian blur post-process
  34603. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34604. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34605. };
  34606. // Luminance generator
  34607. HDRRenderingPipeline.LUM_STEPS = 6;
  34608. return HDRRenderingPipeline;
  34609. })(BABYLON.PostProcessRenderPipeline);
  34610. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34611. })(BABYLON || (BABYLON = {}));
  34612. var BABYLON;
  34613. (function (BABYLON) {
  34614. var FaceAdjacencies = (function () {
  34615. function FaceAdjacencies() {
  34616. this.edges = new Array();
  34617. this.edgesConnectedCount = 0;
  34618. }
  34619. return FaceAdjacencies;
  34620. })();
  34621. var EdgesRenderer = (function () {
  34622. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34623. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34624. if (epsilon === void 0) { epsilon = 0.95; }
  34625. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34626. this._linesPositions = new Array();
  34627. this._linesNormals = new Array();
  34628. this._linesIndices = new Array();
  34629. this._buffers = new Array();
  34630. this._checkVerticesInsteadOfIndices = false;
  34631. this._source = source;
  34632. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34633. this._epsilon = epsilon;
  34634. this._prepareRessources();
  34635. this._generateEdgesLines();
  34636. }
  34637. EdgesRenderer.prototype._prepareRessources = function () {
  34638. if (this._lineShader) {
  34639. return;
  34640. }
  34641. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34642. attributes: ["position", "normal"],
  34643. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34644. });
  34645. this._lineShader.disableDepthWrite = true;
  34646. this._lineShader.backFaceCulling = false;
  34647. };
  34648. EdgesRenderer.prototype.dispose = function () {
  34649. this._vb0.dispose();
  34650. this._vb1.dispose();
  34651. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34652. this._lineShader.dispose();
  34653. };
  34654. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34655. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34656. return 0;
  34657. }
  34658. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34659. return 1;
  34660. }
  34661. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34662. return 2;
  34663. }
  34664. return -1;
  34665. };
  34666. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34667. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34668. return 0;
  34669. }
  34670. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34671. return 1;
  34672. }
  34673. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34674. return 2;
  34675. }
  34676. return -1;
  34677. };
  34678. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34679. var needToCreateLine;
  34680. if (edge === undefined) {
  34681. needToCreateLine = true;
  34682. }
  34683. else {
  34684. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34685. needToCreateLine = dotProduct < this._epsilon;
  34686. }
  34687. if (needToCreateLine) {
  34688. var offset = this._linesPositions.length / 3;
  34689. var normal = p0.subtract(p1);
  34690. normal.normalize();
  34691. // Positions
  34692. this._linesPositions.push(p0.x);
  34693. this._linesPositions.push(p0.y);
  34694. this._linesPositions.push(p0.z);
  34695. this._linesPositions.push(p0.x);
  34696. this._linesPositions.push(p0.y);
  34697. this._linesPositions.push(p0.z);
  34698. this._linesPositions.push(p1.x);
  34699. this._linesPositions.push(p1.y);
  34700. this._linesPositions.push(p1.z);
  34701. this._linesPositions.push(p1.x);
  34702. this._linesPositions.push(p1.y);
  34703. this._linesPositions.push(p1.z);
  34704. // Normals
  34705. this._linesNormals.push(p1.x);
  34706. this._linesNormals.push(p1.y);
  34707. this._linesNormals.push(p1.z);
  34708. this._linesNormals.push(-1);
  34709. this._linesNormals.push(p1.x);
  34710. this._linesNormals.push(p1.y);
  34711. this._linesNormals.push(p1.z);
  34712. this._linesNormals.push(1);
  34713. this._linesNormals.push(p0.x);
  34714. this._linesNormals.push(p0.y);
  34715. this._linesNormals.push(p0.z);
  34716. this._linesNormals.push(-1);
  34717. this._linesNormals.push(p0.x);
  34718. this._linesNormals.push(p0.y);
  34719. this._linesNormals.push(p0.z);
  34720. this._linesNormals.push(1);
  34721. // Indices
  34722. this._linesIndices.push(offset);
  34723. this._linesIndices.push(offset + 1);
  34724. this._linesIndices.push(offset + 2);
  34725. this._linesIndices.push(offset);
  34726. this._linesIndices.push(offset + 2);
  34727. this._linesIndices.push(offset + 3);
  34728. }
  34729. };
  34730. EdgesRenderer.prototype._generateEdgesLines = function () {
  34731. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34732. var indices = this._source.getIndices();
  34733. // First let's find adjacencies
  34734. var adjacencies = new Array();
  34735. var faceNormals = new Array();
  34736. var index;
  34737. var faceAdjacencies;
  34738. // Prepare faces
  34739. for (index = 0; index < indices.length; index += 3) {
  34740. faceAdjacencies = new FaceAdjacencies();
  34741. var p0Index = indices[index];
  34742. var p1Index = indices[index + 1];
  34743. var p2Index = indices[index + 2];
  34744. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34745. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34746. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34747. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34748. faceNormal.normalize();
  34749. faceNormals.push(faceNormal);
  34750. adjacencies.push(faceAdjacencies);
  34751. }
  34752. // Scan
  34753. for (index = 0; index < adjacencies.length; index++) {
  34754. faceAdjacencies = adjacencies[index];
  34755. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34756. var otherFaceAdjacencies = adjacencies[otherIndex];
  34757. if (faceAdjacencies.edgesConnectedCount === 3) {
  34758. break;
  34759. }
  34760. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34761. continue;
  34762. }
  34763. var otherP0 = indices[otherIndex * 3];
  34764. var otherP1 = indices[otherIndex * 3 + 1];
  34765. var otherP2 = indices[otherIndex * 3 + 2];
  34766. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34767. var otherEdgeIndex;
  34768. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34769. continue;
  34770. }
  34771. switch (edgeIndex) {
  34772. case 0:
  34773. if (this._checkVerticesInsteadOfIndices) {
  34774. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34775. }
  34776. else {
  34777. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34778. }
  34779. break;
  34780. case 1:
  34781. if (this._checkVerticesInsteadOfIndices) {
  34782. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34783. }
  34784. else {
  34785. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34786. }
  34787. break;
  34788. case 2:
  34789. if (this._checkVerticesInsteadOfIndices) {
  34790. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34791. }
  34792. else {
  34793. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34794. }
  34795. break;
  34796. }
  34797. if (otherEdgeIndex === -1) {
  34798. continue;
  34799. }
  34800. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34801. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34802. faceAdjacencies.edgesConnectedCount++;
  34803. otherFaceAdjacencies.edgesConnectedCount++;
  34804. if (faceAdjacencies.edgesConnectedCount === 3) {
  34805. break;
  34806. }
  34807. }
  34808. }
  34809. }
  34810. // Create lines
  34811. for (index = 0; index < adjacencies.length; index++) {
  34812. // 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
  34813. var current = adjacencies[index];
  34814. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34815. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34816. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34817. }
  34818. // Merge into a single mesh
  34819. var engine = this._source.getScene().getEngine();
  34820. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34821. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34822. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34823. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34824. this._ib = engine.createIndexBuffer(this._linesIndices);
  34825. this._indicesCount = this._linesIndices.length;
  34826. };
  34827. EdgesRenderer.prototype.render = function () {
  34828. if (!this._lineShader.isReady()) {
  34829. return;
  34830. }
  34831. var scene = this._source.getScene();
  34832. var engine = scene.getEngine();
  34833. this._lineShader._preBind();
  34834. // VBOs
  34835. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34836. scene.resetCachedMaterial();
  34837. this._lineShader.setColor4("color", this._source.edgesColor);
  34838. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34839. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34840. this._lineShader.bind(this._source.getWorldMatrix());
  34841. // Draw order
  34842. engine.draw(true, 0, this._indicesCount);
  34843. this._lineShader.unbind();
  34844. engine.setDepthWrite(true);
  34845. };
  34846. return EdgesRenderer;
  34847. })();
  34848. BABYLON.EdgesRenderer = EdgesRenderer;
  34849. })(BABYLON || (BABYLON = {}));
  34850. var BABYLON;
  34851. (function (BABYLON) {
  34852. (function (TonemappingOperator) {
  34853. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34854. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34855. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34856. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34857. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34858. var TonemappingOperator = BABYLON.TonemappingOperator;
  34859. ;
  34860. var TonemapPostProcess = (function (_super) {
  34861. __extends(TonemapPostProcess, _super);
  34862. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34863. var _this = this;
  34864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34865. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34866. this._operator = operator;
  34867. this._exposureAdjustment = exposureAdjustment;
  34868. var params = ["_ExposureAdjustment"];
  34869. var defines = "#define ";
  34870. if (operator === TonemappingOperator.Hable)
  34871. defines += "HABLE_TONEMAPPING";
  34872. else if (operator === TonemappingOperator.Reinhard)
  34873. defines += "REINHARD_TONEMAPPING";
  34874. else if (operator === TonemappingOperator.HejiDawson)
  34875. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34876. else if (operator === TonemappingOperator.Photographic)
  34877. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34878. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34879. this.onApply = function (effect) {
  34880. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34881. };
  34882. }
  34883. return TonemapPostProcess;
  34884. })(BABYLON.PostProcess);
  34885. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34886. })(BABYLON || (BABYLON = {}));
  34887. var BABYLON;
  34888. (function (BABYLON) {
  34889. var maxSimultaneousLights = 4;
  34890. var PBRMaterialDefines = (function (_super) {
  34891. __extends(PBRMaterialDefines, _super);
  34892. function PBRMaterialDefines() {
  34893. _super.call(this);
  34894. this.ALBEDO = false;
  34895. this.CLIPPLANE = false;
  34896. this.ALPHATEST = false;
  34897. this.FOG = false;
  34898. this.NORMAL = false;
  34899. this.UV1 = false;
  34900. this.UV2 = false;
  34901. this.VERTEXCOLOR = false;
  34902. this.VERTEXALPHA = false;
  34903. this.BONES = false;
  34904. this.BONES4 = false;
  34905. this.BonesPerMesh = 0;
  34906. this.INSTANCES = false;
  34907. this.POINTSIZE = false;
  34908. this._keys = Object.keys(this);
  34909. }
  34910. return PBRMaterialDefines;
  34911. })(BABYLON.MaterialDefines);
  34912. var PBRMaterial = (function (_super) {
  34913. __extends(PBRMaterial, _super);
  34914. function PBRMaterial(name, scene) {
  34915. _super.call(this, name, scene);
  34916. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34917. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34918. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34919. this._scaledDiffuse = new BABYLON.Color3();
  34920. this._scaledSpecular = new BABYLON.Color3();
  34921. this._defines = new PBRMaterialDefines();
  34922. this._cachedDefines = new PBRMaterialDefines();
  34923. this._cachedDefines.BonesPerMesh = -1;
  34924. }
  34925. PBRMaterial.prototype.needAlphaBlending = function () {
  34926. return this.alpha < 1.0;
  34927. };
  34928. PBRMaterial.prototype.needAlphaTesting = function () {
  34929. return false;
  34930. };
  34931. PBRMaterial.prototype.getAlphaTestTexture = function () {
  34932. return null;
  34933. };
  34934. // Methods
  34935. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  34936. if (this.checkReadyOnlyOnce) {
  34937. if (this._wasPreviouslyReady) {
  34938. return true;
  34939. }
  34940. }
  34941. var scene = this.getScene();
  34942. if (!this.checkReadyOnEveryCall) {
  34943. if (this._renderId === scene.getRenderId()) {
  34944. return true;
  34945. }
  34946. }
  34947. var engine = scene.getEngine();
  34948. var needNormals = false;
  34949. var needUVs = false;
  34950. this._defines.reset();
  34951. // Textures
  34952. if (scene.texturesEnabled) {
  34953. }
  34954. // Effect
  34955. if (scene.clipPlane) {
  34956. this._defines.CLIPPLANE = true;
  34957. }
  34958. if (engine.getAlphaTesting()) {
  34959. this._defines.ALPHATEST = true;
  34960. }
  34961. // Point size
  34962. if (this.pointsCloud || scene.forcePointsCloud) {
  34963. this._defines.POINTSIZE = true;
  34964. }
  34965. // Fog
  34966. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34967. this._defines.FOG = true;
  34968. }
  34969. // Lights
  34970. // Attribs
  34971. if (mesh) {
  34972. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34973. this._defines.NORMAL = true;
  34974. }
  34975. if (needUVs) {
  34976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34977. this._defines.UV1 = true;
  34978. }
  34979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34980. this._defines.UV2 = true;
  34981. }
  34982. }
  34983. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34984. this._defines.VERTEXCOLOR = true;
  34985. if (mesh.hasVertexAlpha) {
  34986. this._defines.VERTEXALPHA = true;
  34987. }
  34988. }
  34989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34990. this._defines.BONES = true;
  34991. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  34992. this._defines.BONES4 = true;
  34993. }
  34994. // Instances
  34995. if (useInstances) {
  34996. this._defines.INSTANCES = true;
  34997. }
  34998. }
  34999. // Get correct effect
  35000. if (!this._defines.isEqual(this._cachedDefines)) {
  35001. this._defines.cloneTo(this._cachedDefines);
  35002. scene.resetCachedMaterial();
  35003. // Fallbacks
  35004. var fallbacks = new BABYLON.EffectFallbacks();
  35005. if (this._defines.FOG) {
  35006. fallbacks.addFallback(1, "FOG");
  35007. }
  35008. if (this._defines.BONES4) {
  35009. fallbacks.addFallback(0, "BONES4");
  35010. }
  35011. //Attributes
  35012. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35013. if (this._defines.NORMAL) {
  35014. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35015. }
  35016. if (this._defines.UV1) {
  35017. attribs.push(BABYLON.VertexBuffer.UVKind);
  35018. }
  35019. if (this._defines.UV2) {
  35020. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35021. }
  35022. if (this._defines.VERTEXCOLOR) {
  35023. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35024. }
  35025. if (this._defines.BONES) {
  35026. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35027. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35028. }
  35029. if (this._defines.INSTANCES) {
  35030. attribs.push("world0");
  35031. attribs.push("world1");
  35032. attribs.push("world2");
  35033. attribs.push("world3");
  35034. }
  35035. // Legacy browser patch
  35036. var join = this._defines.toString();
  35037. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  35038. "vFogInfos", "vFogColor", "pointSize",
  35039. "mBones",
  35040. "vClipPlane",
  35041. ], [], join, fallbacks, this.onCompiled, this.onError);
  35042. }
  35043. if (!this._effect.isReady()) {
  35044. return false;
  35045. }
  35046. this._renderId = scene.getRenderId();
  35047. this._wasPreviouslyReady = true;
  35048. return true;
  35049. };
  35050. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35051. this._effect.setMatrix("world", world);
  35052. };
  35053. PBRMaterial.prototype.bind = function (world, mesh) {
  35054. var scene = this.getScene();
  35055. // Matrices
  35056. this.bindOnlyWorldMatrix(world);
  35057. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35058. // Bones
  35059. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35060. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35061. }
  35062. if (scene.getCachedMaterial() !== this) {
  35063. // Clip plane
  35064. if (scene.clipPlane) {
  35065. var clipPlane = scene.clipPlane;
  35066. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35067. }
  35068. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  35069. }
  35070. // Point size
  35071. if (this.pointsCloud) {
  35072. this._effect.setFloat("pointSize", this.pointSize);
  35073. }
  35074. // Colors
  35075. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  35076. // View
  35077. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35078. this._effect.setMatrix("view", scene.getViewMatrix());
  35079. }
  35080. // Fog
  35081. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35082. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35083. this._effect.setColor3("vFogColor", scene.fogColor);
  35084. }
  35085. _super.prototype.bind.call(this, world, mesh);
  35086. };
  35087. PBRMaterial.prototype.getAnimatables = function () {
  35088. var results = [];
  35089. return results;
  35090. };
  35091. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  35092. _super.prototype.dispose.call(this, forceDisposeEffect);
  35093. };
  35094. PBRMaterial.prototype.clone = function (name) {
  35095. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  35096. // Base material
  35097. this.copyTo(newPBRMaterial);
  35098. // PBRMaterial material
  35099. newPBRMaterial.albedoColor = this.albedoColor.clone();
  35100. return newPBRMaterial;
  35101. };
  35102. return PBRMaterial;
  35103. })(BABYLON.Material);
  35104. BABYLON.PBRMaterial = PBRMaterial;
  35105. })(BABYLON || (BABYLON = {}));
  35106. var BABYLON;
  35107. (function (BABYLON) {
  35108. var ReflectionProbe = (function () {
  35109. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35110. var _this = this;
  35111. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35112. this.name = name;
  35113. this._viewMatrix = BABYLON.Matrix.Identity();
  35114. this._target = BABYLON.Vector3.Zero();
  35115. this._add = BABYLON.Vector3.Zero();
  35116. this.position = BABYLON.Vector3.Zero();
  35117. this._scene = scene;
  35118. this._scene.reflectionProbes.push(this);
  35119. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35120. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35121. switch (faceIndex) {
  35122. case 0:
  35123. _this._add.copyFromFloats(1, 0, 0);
  35124. break;
  35125. case 1:
  35126. _this._add.copyFromFloats(-1, 0, 0);
  35127. break;
  35128. case 2:
  35129. _this._add.copyFromFloats(0, -1, 0);
  35130. break;
  35131. case 3:
  35132. _this._add.copyFromFloats(0, 1, 0);
  35133. break;
  35134. case 4:
  35135. _this._add.copyFromFloats(0, 0, 1);
  35136. break;
  35137. case 5:
  35138. _this._add.copyFromFloats(0, 0, -1);
  35139. break;
  35140. }
  35141. if (_this._attachedMesh) {
  35142. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35143. }
  35144. _this.position.addToRef(_this._add, _this._target);
  35145. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35146. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35147. };
  35148. this._renderTargetTexture.onAfterUnbind = function () {
  35149. scene.updateTransformMatrix(true);
  35150. };
  35151. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35152. }
  35153. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35154. get: function () {
  35155. return this._renderTargetTexture.refreshRate;
  35156. },
  35157. set: function (value) {
  35158. this._renderTargetTexture.refreshRate = value;
  35159. },
  35160. enumerable: true,
  35161. configurable: true
  35162. });
  35163. ReflectionProbe.prototype.getScene = function () {
  35164. return this._scene;
  35165. };
  35166. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35167. get: function () {
  35168. return this._renderTargetTexture;
  35169. },
  35170. enumerable: true,
  35171. configurable: true
  35172. });
  35173. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35174. get: function () {
  35175. return this._renderTargetTexture.renderList;
  35176. },
  35177. enumerable: true,
  35178. configurable: true
  35179. });
  35180. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35181. this._attachedMesh = mesh;
  35182. };
  35183. ReflectionProbe.prototype.dispose = function () {
  35184. var index = this._scene.reflectionProbes.indexOf(this);
  35185. if (index !== -1) {
  35186. // Remove from the scene if found
  35187. this._scene.reflectionProbes.splice(index, 1);
  35188. }
  35189. };
  35190. return ReflectionProbe;
  35191. })();
  35192. BABYLON.ReflectionProbe = ReflectionProbe;
  35193. })(BABYLON || (BABYLON = {}));
  35194. var BABYLON;
  35195. (function (BABYLON) {
  35196. var SolidParticle = (function () {
  35197. function SolidParticle(particleIndex, positionIndex, shape, shapeUV, shapeId, idxInShape) {
  35198. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35199. this.position = BABYLON.Vector3.Zero(); // position
  35200. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35201. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35202. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35203. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35204. this.alive = true; // alive
  35205. this.idx = particleIndex;
  35206. this._pos = positionIndex;
  35207. this._shape = shape;
  35208. this._shapeUV = shapeUV;
  35209. this.shapeId = shapeId;
  35210. this.idxInShape = idxInShape;
  35211. }
  35212. return SolidParticle;
  35213. })();
  35214. BABYLON.SolidParticle = SolidParticle;
  35215. })(BABYLON || (BABYLON = {}));
  35216. var BABYLON;
  35217. (function (BABYLON) {
  35218. var SolidParticleSystem = (function () {
  35219. function SolidParticleSystem(name, scene) {
  35220. // public members
  35221. this.particles = new Array();
  35222. this.nbParticles = 0;
  35223. this.billboard = false;
  35224. this.counter = 0;
  35225. this._positions = new Array();
  35226. this._indices = new Array();
  35227. this._normals = new Array();
  35228. this._colors = new Array();
  35229. this._uvs = new Array();
  35230. this._index = 0; // indices index
  35231. this._shapeCounter = 0;
  35232. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  35233. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35234. this._computeParticleColor = true;
  35235. this._computeParticleTexture = true;
  35236. this._computeParticleRotation = true;
  35237. this._computeParticleVertex = false;
  35238. this._cam_axisZ = BABYLON.Vector3.Zero();
  35239. this._cam_axisY = BABYLON.Vector3.Zero();
  35240. this._cam_axisX = BABYLON.Vector3.Zero();
  35241. this._axisX = BABYLON.Axis.X;
  35242. this._axisY = BABYLON.Axis.Y;
  35243. this._axisZ = BABYLON.Axis.Z;
  35244. this._fakeCamPos = BABYLON.Vector3.Zero();
  35245. this._rotMatrix = new BABYLON.Matrix();
  35246. this._invertedMatrix = new BABYLON.Matrix();
  35247. this._rotated = BABYLON.Vector3.Zero();
  35248. this._quaternion = new BABYLON.Quaternion();
  35249. this._vertex = BABYLON.Vector3.Zero();
  35250. this._yaw = 0.0;
  35251. this._pitch = 0.0;
  35252. this._roll = 0.0;
  35253. this._halfroll = 0.0;
  35254. this._halfpitch = 0.0;
  35255. this._halfyaw = 0.0;
  35256. this._sinRoll = 0.0;
  35257. this._cosRoll = 0.0;
  35258. this._sinPitch = 0.0;
  35259. this._cosPitch = 0.0;
  35260. this._sinYaw = 0.0;
  35261. this._cosYaw = 0.0;
  35262. this.name = name;
  35263. this._scene = scene;
  35264. this._camera = scene.activeCamera;
  35265. }
  35266. // build the SPS mesh : returns the mesh
  35267. SolidParticleSystem.prototype.buildMesh = function (upgradable) {
  35268. if (upgradable === void 0) { upgradable = true; }
  35269. if (this.nbParticles === 0) {
  35270. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35271. this.addShape(triangle, 1);
  35272. triangle.dispose();
  35273. }
  35274. this._positions32 = new Float32Array(this._positions);
  35275. this._uvs32 = new Float32Array(this._uvs);
  35276. this._colors32 = new Float32Array(this._colors);
  35277. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35278. this._normals32 = new Float32Array(this._normals);
  35279. var vertexData = new BABYLON.VertexData();
  35280. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35281. vertexData.indices = this._indices;
  35282. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35283. if (this._uvs32) {
  35284. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35285. ;
  35286. }
  35287. if (this._colors32) {
  35288. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35289. }
  35290. var mesh = new BABYLON.Mesh(name, this._scene);
  35291. vertexData.applyToMesh(mesh, upgradable);
  35292. this.mesh = mesh;
  35293. // free memory
  35294. this._positions = null;
  35295. this._normals = null;
  35296. this._uvs = null;
  35297. this._colors = null;
  35298. return mesh;
  35299. };
  35300. //reset copy
  35301. SolidParticleSystem.prototype._resetCopy = function () {
  35302. this._copy.position.x = 0;
  35303. this._copy.position.y = 0;
  35304. this._copy.position.z = 0;
  35305. this._copy.rotation.x = 0;
  35306. this._copy.rotation.y = 0;
  35307. this._copy.rotation.z = 0;
  35308. this._copy.quaternion = null;
  35309. this._copy.scale.x = 1;
  35310. this._copy.scale.y = 1;
  35311. this._copy.scale.z = 1;
  35312. this._copy.uvs.x = 0;
  35313. this._copy.uvs.y = 0;
  35314. this._copy.uvs.z = 1;
  35315. this._copy.uvs.w = 1;
  35316. this._copy.color = null;
  35317. };
  35318. // _meshBuilder : inserts the shape model in the global SPS mesh
  35319. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idxInShape, options) {
  35320. var i;
  35321. var u = 0;
  35322. var c = 0;
  35323. this._resetCopy();
  35324. if (options && options.positionFunction) {
  35325. options.positionFunction(this._copy, p, idxInShape);
  35326. }
  35327. if (this._copy.quaternion) {
  35328. this._quaternion.x = this._copy.quaternion.x;
  35329. this._quaternion.y = this._copy.quaternion.y;
  35330. this._quaternion.z = this._copy.quaternion.z;
  35331. this._quaternion.w = this._copy.quaternion.w;
  35332. }
  35333. else {
  35334. this._yaw = this._copy.rotation.y;
  35335. this._pitch = this._copy.rotation.x;
  35336. this._roll = this._copy.rotation.z;
  35337. this._quaternionRotationYPR();
  35338. }
  35339. this._quaternionToRotationMatrix();
  35340. for (i = 0; i < shape.length; i++) {
  35341. this._vertex.x = shape[i].x;
  35342. this._vertex.y = shape[i].y;
  35343. this._vertex.z = shape[i].z;
  35344. if (options && options.vertexFunction) {
  35345. options.vertexFunction(this._copy, this._vertex, i);
  35346. }
  35347. this._vertex.x *= this._copy.scale.x;
  35348. this._vertex.y *= this._copy.scale.y;
  35349. this._vertex.z *= this._copy.scale.z;
  35350. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35351. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35352. if (meshUV) {
  35353. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  35354. u += 2;
  35355. }
  35356. if (this._copy.color) {
  35357. this._color = this._copy.color;
  35358. }
  35359. else if (meshCol && meshCol[c]) {
  35360. this._color.r = meshCol[c];
  35361. this._color.g = meshCol[c + 1];
  35362. this._color.b = meshCol[c + 2];
  35363. this._color.a = meshCol[c + 3];
  35364. }
  35365. else {
  35366. this._color.r = 1;
  35367. this._color.g = 1;
  35368. this._color.b = 1;
  35369. this._color.a = 1;
  35370. }
  35371. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35372. c += 4;
  35373. }
  35374. for (i = 0; i < meshInd.length; i++) {
  35375. indices.push(p + meshInd[i]);
  35376. }
  35377. };
  35378. // returns a shape array from positions array
  35379. SolidParticleSystem.prototype._posToShape = function (positions) {
  35380. var shape = [];
  35381. for (var i = 0; i < positions.length; i += 3) {
  35382. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  35383. }
  35384. return shape;
  35385. };
  35386. // returns a shapeUV array from a Vector4 uvs
  35387. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  35388. var shapeUV = [];
  35389. if (uvs) {
  35390. for (var i = 0; i < uvs.length; i++)
  35391. shapeUV.push(uvs[i]);
  35392. }
  35393. return shapeUV;
  35394. };
  35395. // adds a new particle object in the particles array and double links the particle (next/previous)
  35396. SolidParticleSystem.prototype._addParticle = function (p, idxpos, shape, shapeUV, shapeId, idxInShape) {
  35397. this._particle = new BABYLON.SolidParticle(p, idxpos, shape, shapeUV, shapeId, idxInShape);
  35398. this.particles.push(this._particle);
  35399. this._particle.previous = this._previousParticle;
  35400. if (this._previousParticle) {
  35401. this._previousParticle.next = this._particle;
  35402. }
  35403. this._previousParticle = this._particle;
  35404. };
  35405. // add solid particles from a shape model in the particles array
  35406. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  35407. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35408. var meshInd = mesh.getIndices();
  35409. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35410. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35411. var shape = this._posToShape(meshPos);
  35412. var shapeUV = this._uvsToShapeUV(meshUV);
  35413. // particles
  35414. for (var i = 0; i < nb; i++) {
  35415. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, i, options);
  35416. this._addParticle(this.nbParticles + i, this._positions.length, shape, shapeUV, this._shapeCounter, i);
  35417. this._index += shape.length;
  35418. }
  35419. this.nbParticles += nb;
  35420. this._shapeCounter++;
  35421. return this._shapeCounter;
  35422. };
  35423. // resets a particle back to its just built status
  35424. SolidParticleSystem.prototype.resetParticle = function (particle) {
  35425. for (var pt = 0; pt < particle._shape.length; pt++) {
  35426. this._positions[particle._pos + pt * 3] = particle._shape[pt].x;
  35427. this._positions[particle._pos + pt * 3 + 1] = particle._shape[pt].y;
  35428. this._positions[particle._pos + pt * 3 + 2] = particle._shape[pt].z;
  35429. }
  35430. };
  35431. // sets all the particles
  35432. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  35433. if (start === void 0) { start = 0; }
  35434. if (end === void 0) { end = this.nbParticles - 1; }
  35435. if (update === void 0) { update = true; }
  35436. // custom beforeUpdate
  35437. this.beforeUpdateParticles(start, end, update);
  35438. this._cam_axisX.x = 1;
  35439. this._cam_axisX.y = 0;
  35440. this._cam_axisX.z = 0;
  35441. this._cam_axisY.x = 0;
  35442. this._cam_axisY.y = 1;
  35443. this._cam_axisY.z = 0;
  35444. this._cam_axisZ.x = 0;
  35445. this._cam_axisZ.y = 0;
  35446. this._cam_axisZ.z = 1;
  35447. // if the particles will always face the camera
  35448. if (this.billboard) {
  35449. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  35450. this._yaw = this.mesh.rotation.y;
  35451. this._pitch = this.mesh.rotation.x;
  35452. this._roll = this.mesh.rotation.z;
  35453. this._quaternionRotationYPR();
  35454. this._quaternionToRotationMatrix();
  35455. this._rotMatrix.invertToRef(this._invertedMatrix);
  35456. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertedMatrix, this._fakeCamPos);
  35457. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  35458. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  35459. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  35460. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  35461. this._cam_axisY.normalize();
  35462. this._cam_axisX.normalize();
  35463. this._cam_axisZ.normalize();
  35464. }
  35465. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  35466. var idx = 0;
  35467. var index = 0;
  35468. var colidx = 0;
  35469. var colorIndex = 0;
  35470. var uvidx = 0;
  35471. var uvIndex = 0;
  35472. // particle loop
  35473. for (var p = start; p <= end; p++) {
  35474. this._particle = this.particles[p];
  35475. // call to custom user function to update the particle properties
  35476. this.updateParticle(this._particle);
  35477. // particle rotation matrix
  35478. if (this.billboard) {
  35479. this._particle.rotation.x = 0.0;
  35480. this._particle.rotation.y = 0.0;
  35481. }
  35482. if (this._computeParticleRotation) {
  35483. if (this._particle.quaternion) {
  35484. this._quaternion.x = this._particle.quaternion.x;
  35485. this._quaternion.y = this._particle.quaternion.y;
  35486. this._quaternion.z = this._particle.quaternion.z;
  35487. this._quaternion.w = this._particle.quaternion.w;
  35488. }
  35489. else {
  35490. this._yaw = this._particle.rotation.y;
  35491. this._pitch = this._particle.rotation.x;
  35492. this._roll = this._particle.rotation.z;
  35493. this._quaternionRotationYPR();
  35494. }
  35495. this._quaternionToRotationMatrix();
  35496. }
  35497. for (var pt = 0; pt < this._particle._shape.length; pt++) {
  35498. idx = index + pt * 3;
  35499. colidx = colorIndex + pt * 4;
  35500. uvidx = uvIndex + pt * 2;
  35501. this._vertex.x = this._particle._shape[pt].x;
  35502. this._vertex.y = this._particle._shape[pt].y;
  35503. this._vertex.z = this._particle._shape[pt].z;
  35504. if (this._computeParticleVertex) {
  35505. this.updateParticleVertex(this._particle, this._vertex, pt);
  35506. }
  35507. this._vertex.x *= this._particle.scale.x;
  35508. this._vertex.y *= this._particle.scale.y;
  35509. this._vertex.z *= this._particle.scale.z;
  35510. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35511. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  35512. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  35513. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  35514. if (this._computeParticleColor) {
  35515. this._colors32[colidx] = this._particle.color.r;
  35516. this._colors32[colidx + 1] = this._particle.color.g;
  35517. this._colors32[colidx + 2] = this._particle.color.b;
  35518. this._colors32[colidx + 3] = this._particle.color.a;
  35519. }
  35520. if (this._computeParticleTexture) {
  35521. this._uvs32[uvidx] = this._particle._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  35522. this._uvs32[uvidx + 1] = this._particle._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  35523. }
  35524. }
  35525. index = idx + 3;
  35526. colorIndex = colidx + 4;
  35527. uvIndex = uvidx + 2;
  35528. }
  35529. if (update) {
  35530. if (this._computeParticleColor) {
  35531. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  35532. }
  35533. if (this._computeParticleTexture) {
  35534. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  35535. }
  35536. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  35537. if (!this.mesh.areNormalsFrozen) {
  35538. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  35539. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  35540. }
  35541. }
  35542. this.afterUpdateParticles(start, end, update);
  35543. };
  35544. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  35545. this._halfroll = this._roll * 0.5;
  35546. this._halfpitch = this._pitch * 0.5;
  35547. this._halfyaw = this._yaw * 0.5;
  35548. this._sinRoll = Math.sin(this._halfroll);
  35549. this._cosRoll = Math.cos(this._halfroll);
  35550. this._sinPitch = Math.sin(this._halfpitch);
  35551. this._cosPitch = Math.cos(this._halfpitch);
  35552. this._sinYaw = Math.sin(this._halfyaw);
  35553. this._cosYaw = Math.cos(this._halfyaw);
  35554. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  35555. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  35556. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  35557. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  35558. };
  35559. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  35560. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  35561. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  35562. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  35563. this._rotMatrix.m[3] = 0;
  35564. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  35565. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  35566. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  35567. this._rotMatrix.m[7] = 0;
  35568. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  35569. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  35570. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  35571. this._rotMatrix.m[11] = 0;
  35572. this._rotMatrix.m[12] = 0;
  35573. this._rotMatrix.m[13] = 0;
  35574. this._rotMatrix.m[14] = 0;
  35575. this._rotMatrix.m[15] = 1.0;
  35576. };
  35577. // dispose the SPS
  35578. SolidParticleSystem.prototype.dispose = function () {
  35579. this.mesh.dispose();
  35580. };
  35581. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  35582. // getters
  35583. get: function () {
  35584. return this._computeParticleRotation;
  35585. },
  35586. // Optimizer setters
  35587. set: function (val) {
  35588. this._computeParticleRotation = val;
  35589. },
  35590. enumerable: true,
  35591. configurable: true
  35592. });
  35593. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  35594. get: function () {
  35595. return this._computeParticleColor;
  35596. },
  35597. set: function (val) {
  35598. this._computeParticleColor = val;
  35599. },
  35600. enumerable: true,
  35601. configurable: true
  35602. });
  35603. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  35604. get: function () {
  35605. return this._computeParticleTexture;
  35606. },
  35607. set: function (val) {
  35608. this._computeParticleTexture = val;
  35609. },
  35610. enumerable: true,
  35611. configurable: true
  35612. });
  35613. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  35614. get: function () {
  35615. return this._computeParticleVertex;
  35616. },
  35617. set: function (val) {
  35618. this._computeParticleVertex = val;
  35619. },
  35620. enumerable: true,
  35621. configurable: true
  35622. });
  35623. // =======================================================================
  35624. // Particle behavior logic
  35625. // these following methods may be overwritten by the user to fit his needs
  35626. // init : sets all particles first values and calls updateParticle to set them in space
  35627. // can be overwritten by the user
  35628. SolidParticleSystem.prototype.initParticles = function () {
  35629. };
  35630. // recycles a particle : can by overwritten by the user
  35631. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  35632. return particle;
  35633. };
  35634. // updates a particle : can be overwritten by the user
  35635. // will be called on each particle by setParticles() :
  35636. // ex : just set a particle position or velocity and recycle conditions
  35637. SolidParticleSystem.prototype.updateParticle = function (particle) {
  35638. return particle;
  35639. };
  35640. // updates a vertex of a particle : can be overwritten by the user
  35641. // will be called on each vertex particle by setParticles() :
  35642. // particle : the current particle
  35643. // vertex : the current index of the current particle
  35644. // pt : the index of the current vertex in the particle shape
  35645. // ex : just set a vertex particle position
  35646. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  35647. return vertex;
  35648. };
  35649. // will be called before any other treatment by setParticles()
  35650. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  35651. };
  35652. // will be called after all setParticles() treatments
  35653. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  35654. };
  35655. return SolidParticleSystem;
  35656. })();
  35657. BABYLON.SolidParticleSystem = SolidParticleSystem;
  35658. })(BABYLON || (BABYLON = {}));
  35659. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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\nprecision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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 EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvarying vec3 vPositionUVW;\r\n#else\r\n\tuniform mat4 reflectionMatrix;\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\n\tuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\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#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#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#ifdef SHADOWPCF0\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#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#ifdef SHADOWPCF1\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#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#ifdef SHADOWPCF2\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#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#ifdef SHADOWPCF3\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#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\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\tbias = vReflectionInfos.y;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x * shadow;\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x * shadow;\r\n#endif\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\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// 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\tvec3 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\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += lightmapColor;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\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 REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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\nprecision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 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#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\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":"precision highp float;\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 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\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\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\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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":"precision highp float;\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}"};
  35660. 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=g*(2*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=g*(2*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=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}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 n(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,n){return this.r===t&&this.g===i&&this.b===n},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,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,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 n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}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,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=n;var r=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,n){return new i(this.x*t,this.y*n)},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,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},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,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,f=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,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,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}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)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*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,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,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,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},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,n,r){return new i(this.x*t,this.y*n,this.z*r)},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,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=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];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,f=t.y*a+r.y*u+n.y*m+o.y*y,p=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,f,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=c.X,f=c.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,f)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,f)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}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,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,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,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},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,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},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,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}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,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,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 n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=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(n,r,o,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=o.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,f=y+c;return 0!==f&&1!==f?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*f),t.z=Math.atan2(e-h,u+m)):0===f?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+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 n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],f=o+a+c;f>0?(n=.5/Math.sqrt(f+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},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,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=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],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=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]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+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 n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];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],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],f=this.m[12],p=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*p,v=m*l-y*p,g=u*x-c*f,d=u*l-y*f,T=u*p-m*f,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),A=1/(i*R+n*_+r*M+o*F),b=h*x-a*l,P=e*x-a*p,C=e*l-h*p,I=s*x-a*f,E=s*l-h*f,q=s*p-e*f,L=h*c-a*y,D=e*c-a*m,S=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*A,t.m[4]=_*A,t.m[8]=M*A,t.m[12]=F*A,t.m[1]=-(n*z-r*w+o*v)*A,t.m[5]=(i*z-r*g+o*d)*A,t.m[9]=-(i*w-n*g+o*T)*A,t.m[13]=(i*v-n*d+r*T)*A,t.m[2]=(n*b-r*P+o*C)*A,t.m[6]=-(i*b-r*I+o*E)*A,t.m[10]=(i*P-n*I+o*q)*A,t.m[14]=-(i*C-n*E+r*q)*A,t.m[3]=-(n*L-r*D+o*S)*A,t.m[7]=(i*L-r*Z+o*N)*A,t.m[11]=-(i*D-n*Z+o*W)*A,t.m[15]=(i*S-n*N+r*W)*A,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 n=new i;return this.multiplyToRef(t,n),n},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 n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],f=this.m[10],p=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],A=t.m[8],b=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],q=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*A+e*I,i[n+1]=r*g+o*_+s*b+e*E,i[n+2]=r*d+o*M+s*P+e*q,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*A+m*I,i[n+5]=h*g+a*_+u*b+m*E,i[n+6]=h*d+a*M+u*P+m*q,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+f*A+p*I,i[n+9]=y*g+c*_+f*b+p*E,i[n+10]=y*d+c*M+f*P+p*q,i[n+11]=y*T+c*F+f*C+p*L,i[n+12]=l*v+x*R+z*A+w*I,i[n+13]=l*g+x*_+z*b+w*E,i[n+14]=l*d+x*M+z*P+w*q,i[n+15]=l*T+x*F+z*C+w*L,this},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(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,f,p,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=f,x.m[14]=p,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,f,p,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=f,z.m[13]=p,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=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 n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},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 n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,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 n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,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 n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,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,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,\nr.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.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,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},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 n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(t,i,n),this.d=r}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 n=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,y)},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,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,f=Math.sqrt(m*m+y*y+c*c);return r=0!==f?1/f:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,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 n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.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,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(0,0,0,0));return t.GetPlanesToRef(i,n),n},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=m;var y=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=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(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)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(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)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(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)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,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=c;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,f=1/(3*s*m+2*e*a+h);a-=(c-t)*f,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var p=t.Orientation,l=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,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?p.CW:p.CCW,this.angle=l.FromDegrees(this.orientation===p.CW?a-m:m-a)}return t}();t.Arc2=x;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 o(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 w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),y=m.angle.radians()/e;m.orientation===p.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,f=0;e>f;f++){var l=Math.cos(c)*m.radius+m.centerPoint.x,z=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(l,z),c+=y}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],n=this._points[0];t+=n.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.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var y=u.normalize(),c=n-o;return new r(h.x+y.x*c,h.y+y.y*c)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(t,i,n){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 r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!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 n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].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 n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,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(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=g;var d=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var T=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=T}(BABYLON||(BABYLON={}));";
  35661. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  35662. module.exports = BABYLON;
  35663. };