babylon.max.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var rotation = Vector3.Zero();
  845. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  846. return rotation;
  847. };
  848. /**
  849. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  850. */
  851. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  852. var u = Vector3.Normalize(axis1);
  853. var w = Vector3.Normalize(axis3);
  854. // world axis
  855. var X = Axis.X;
  856. var Y = Axis.Y;
  857. // equation unknowns and vars
  858. var yaw = 0.0;
  859. var pitch = 0.0;
  860. var roll = 0.0;
  861. var x = 0.0;
  862. var y = 0.0;
  863. var z = 0.0;
  864. var t = 0.0;
  865. var sign = -1.0;
  866. var nbRevert = 0;
  867. var cross;
  868. var dot = 0.0;
  869. // step 1 : rotation around w
  870. // Rv3(u) = u1, and u1 belongs to plane xOz
  871. // Rv3(w) = w1 = w invariant
  872. var u1;
  873. var v1;
  874. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  875. z = 1.0;
  876. }
  877. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  878. x = 1.0;
  879. }
  880. else {
  881. t = w.z / w.x;
  882. x = -t * Math.sqrt(1 / (1 + t * t));
  883. z = Math.sqrt(1 / (1 + t * t));
  884. }
  885. u1 = new Vector3(x, y, z);
  886. u1.normalize();
  887. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  888. v1.normalize();
  889. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  890. cross.normalize();
  891. if (Vector3.Dot(w, cross) < 0) {
  892. sign = 1.0;
  893. }
  894. dot = Vector3.Dot(u, u1);
  895. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  896. roll = Math.acos(dot) * sign;
  897. if (Vector3.Dot(u1, X) < 0) {
  898. roll = Math.PI + roll;
  899. u1 = u1.scaleInPlace(-1);
  900. v1 = v1.scaleInPlace(-1);
  901. nbRevert++;
  902. }
  903. // step 2 : rotate around u1
  904. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  905. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  906. var w2;
  907. var v2;
  908. x = 0.0;
  909. y = 0.0;
  910. z = 0.0;
  911. sign = -1;
  912. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  913. x = 1.0;
  914. }
  915. else {
  916. t = u1.z / u1.x;
  917. x = -t * Math.sqrt(1 / (1 + t * t));
  918. z = Math.sqrt(1 / (1 + t * t));
  919. }
  920. w2 = new Vector3(x, y, z);
  921. w2.normalize();
  922. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  923. v2.normalize();
  924. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  925. cross.normalize();
  926. if (Vector3.Dot(u1, cross) < 0) {
  927. sign = 1.0;
  928. }
  929. dot = Vector3.Dot(w, w2);
  930. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  931. pitch = Math.acos(dot) * sign;
  932. if (Vector3.Dot(v2, Y) < 0) {
  933. pitch = Math.PI + pitch;
  934. v2 = v2.scaleInPlace(-1);
  935. w2 = w2.scaleInPlace(-1);
  936. nbRevert++;
  937. }
  938. // step 3 : rotate around v2
  939. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  940. sign = -1;
  941. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(cross, Y) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(u1, X);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  949. if (dot < 0 && nbRevert < 2) {
  950. yaw = Math.PI + yaw;
  951. }
  952. ref.x = pitch;
  953. ref.y = yaw;
  954. ref.z = roll;
  955. };
  956. return Vector3;
  957. })();
  958. BABYLON.Vector3 = Vector3;
  959. //Vector4 class created for EulerAngle class conversion to Quaternion
  960. var Vector4 = (function () {
  961. function Vector4(x, y, z, w) {
  962. this.x = x;
  963. this.y = y;
  964. this.z = z;
  965. this.w = w;
  966. }
  967. Vector4.prototype.toString = function () {
  968. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  969. };
  970. // Operators
  971. Vector4.prototype.asArray = function () {
  972. var result = [];
  973. this.toArray(result, 0);
  974. return result;
  975. };
  976. Vector4.prototype.toArray = function (array, index) {
  977. if (index === undefined) {
  978. index = 0;
  979. }
  980. array[index] = this.x;
  981. array[index + 1] = this.y;
  982. array[index + 2] = this.z;
  983. array[index + 3] = this.w;
  984. return this;
  985. };
  986. Vector4.prototype.addInPlace = function (otherVector) {
  987. this.x += otherVector.x;
  988. this.y += otherVector.y;
  989. this.z += otherVector.z;
  990. this.w += otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.add = function (otherVector) {
  994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  995. };
  996. Vector4.prototype.addToRef = function (otherVector, result) {
  997. result.x = this.x + otherVector.x;
  998. result.y = this.y + otherVector.y;
  999. result.z = this.z + otherVector.z;
  1000. result.w = this.w + otherVector.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.subtractInPlace = function (otherVector) {
  1004. this.x -= otherVector.x;
  1005. this.y -= otherVector.y;
  1006. this.z -= otherVector.z;
  1007. this.w -= otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtract = function (otherVector) {
  1011. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1012. };
  1013. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1014. result.x = this.x - otherVector.x;
  1015. result.y = this.y - otherVector.y;
  1016. result.z = this.z - otherVector.z;
  1017. result.w = this.w - otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1021. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1022. };
  1023. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1024. result.x = this.x - x;
  1025. result.y = this.y - y;
  1026. result.z = this.z - z;
  1027. result.w = this.w - w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.negate = function () {
  1031. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1032. };
  1033. Vector4.prototype.scaleInPlace = function (scale) {
  1034. this.x *= scale;
  1035. this.y *= scale;
  1036. this.z *= scale;
  1037. this.w *= scale;
  1038. return this;
  1039. };
  1040. Vector4.prototype.scale = function (scale) {
  1041. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1042. };
  1043. Vector4.prototype.scaleToRef = function (scale, result) {
  1044. result.x = this.x * scale;
  1045. result.y = this.y * scale;
  1046. result.z = this.z * scale;
  1047. result.w = this.w * scale;
  1048. };
  1049. Vector4.prototype.equals = function (otherVector) {
  1050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1051. };
  1052. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1053. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1054. return otherVector
  1055. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1056. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1057. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1059. };
  1060. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1061. return this.x === x && this.y === y && this.z === z && this.w === w;
  1062. };
  1063. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1064. this.x *= otherVector.x;
  1065. this.y *= otherVector.y;
  1066. this.z *= otherVector.z;
  1067. this.w *= otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiply = function (otherVector) {
  1071. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1072. };
  1073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1074. result.x = this.x * otherVector.x;
  1075. result.y = this.y * otherVector.y;
  1076. result.z = this.z * otherVector.z;
  1077. result.w = this.w * otherVector.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1082. };
  1083. Vector4.prototype.divide = function (otherVector) {
  1084. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1085. };
  1086. Vector4.prototype.divideToRef = function (otherVector, result) {
  1087. result.x = this.x / otherVector.x;
  1088. result.y = this.y / otherVector.y;
  1089. result.z = this.z / otherVector.z;
  1090. result.w = this.w / otherVector.w;
  1091. return this;
  1092. };
  1093. Vector4.prototype.MinimizeInPlace = function (other) {
  1094. if (other.x < this.x)
  1095. this.x = other.x;
  1096. if (other.y < this.y)
  1097. this.y = other.y;
  1098. if (other.z < this.z)
  1099. this.z = other.z;
  1100. if (other.w < this.w)
  1101. this.w = other.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MaximizeInPlace = function (other) {
  1105. if (other.x > this.x)
  1106. this.x = other.x;
  1107. if (other.y > this.y)
  1108. this.y = other.y;
  1109. if (other.z > this.z)
  1110. this.z = other.z;
  1111. if (other.w > this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. // Properties
  1116. Vector4.prototype.length = function () {
  1117. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1118. };
  1119. Vector4.prototype.lengthSquared = function () {
  1120. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1121. };
  1122. // Methods
  1123. Vector4.prototype.normalize = function () {
  1124. var len = this.length();
  1125. if (len === 0)
  1126. return this;
  1127. var num = 1.0 / len;
  1128. this.x *= num;
  1129. this.y *= num;
  1130. this.z *= num;
  1131. this.w *= num;
  1132. return this;
  1133. };
  1134. Vector4.prototype.clone = function () {
  1135. return new Vector4(this.x, this.y, this.z, this.w);
  1136. };
  1137. Vector4.prototype.copyFrom = function (source) {
  1138. this.x = source.x;
  1139. this.y = source.y;
  1140. this.z = source.z;
  1141. this.w = source.w;
  1142. return this;
  1143. };
  1144. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. this.w = w;
  1149. return this;
  1150. };
  1151. // Statics
  1152. Vector4.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Vector4.FromArrayToRef = function (array, offset, result) {
  1159. result.x = array[offset];
  1160. result.y = array[offset + 1];
  1161. result.z = array[offset + 2];
  1162. result.w = array[offset + 3];
  1163. };
  1164. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1165. result.x = array[offset];
  1166. result.y = array[offset + 1];
  1167. result.z = array[offset + 2];
  1168. result.w = array[offset + 3];
  1169. };
  1170. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1171. result.x = x;
  1172. result.y = y;
  1173. result.z = z;
  1174. result.w = w;
  1175. };
  1176. Vector4.Zero = function () {
  1177. return new Vector4(0, 0, 0, 0);
  1178. };
  1179. Vector4.Normalize = function (vector) {
  1180. var result = Vector4.Zero();
  1181. Vector4.NormalizeToRef(vector, result);
  1182. return result;
  1183. };
  1184. Vector4.NormalizeToRef = function (vector, result) {
  1185. result.copyFrom(vector);
  1186. result.normalize();
  1187. };
  1188. Vector4.Minimize = function (left, right) {
  1189. var min = left.clone();
  1190. min.MinimizeInPlace(right);
  1191. return min;
  1192. };
  1193. Vector4.Maximize = function (left, right) {
  1194. var max = left.clone();
  1195. max.MaximizeInPlace(right);
  1196. return max;
  1197. };
  1198. Vector4.Distance = function (value1, value2) {
  1199. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1200. };
  1201. Vector4.DistanceSquared = function (value1, value2) {
  1202. var x = value1.x - value2.x;
  1203. var y = value1.y - value2.y;
  1204. var z = value1.z - value2.z;
  1205. var w = value1.w - value2.w;
  1206. return (x * x) + (y * y) + (z * z) + (w * w);
  1207. };
  1208. Vector4.Center = function (value1, value2) {
  1209. var center = value1.add(value2);
  1210. center.scaleInPlace(0.5);
  1211. return center;
  1212. };
  1213. return Vector4;
  1214. })();
  1215. BABYLON.Vector4 = Vector4;
  1216. var Quaternion = (function () {
  1217. function Quaternion(x, y, z, w) {
  1218. if (x === void 0) { x = 0; }
  1219. if (y === void 0) { y = 0; }
  1220. if (z === void 0) { z = 0; }
  1221. if (w === void 0) { w = 1; }
  1222. this.x = x;
  1223. this.y = y;
  1224. this.z = z;
  1225. this.w = w;
  1226. }
  1227. Quaternion.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1229. };
  1230. Quaternion.prototype.asArray = function () {
  1231. return [this.x, this.y, this.z, this.w];
  1232. };
  1233. Quaternion.prototype.equals = function (otherQuaternion) {
  1234. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1235. };
  1236. Quaternion.prototype.clone = function () {
  1237. return new Quaternion(this.x, this.y, this.z, this.w);
  1238. };
  1239. Quaternion.prototype.copyFrom = function (other) {
  1240. this.x = other.x;
  1241. this.y = other.y;
  1242. this.z = other.z;
  1243. this.w = other.w;
  1244. return this;
  1245. };
  1246. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. };
  1253. Quaternion.prototype.add = function (other) {
  1254. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1255. };
  1256. Quaternion.prototype.subtract = function (other) {
  1257. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1258. };
  1259. Quaternion.prototype.scale = function (value) {
  1260. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1261. };
  1262. Quaternion.prototype.multiply = function (q1) {
  1263. var result = new Quaternion(0, 0, 0, 1.0);
  1264. this.multiplyToRef(q1, result);
  1265. return result;
  1266. };
  1267. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1268. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1269. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1270. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1271. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1272. result.copyFromFloats(x, y, z, w);
  1273. return this;
  1274. };
  1275. Quaternion.prototype.length = function () {
  1276. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1277. };
  1278. Quaternion.prototype.normalize = function () {
  1279. var length = 1.0 / this.length();
  1280. this.x *= length;
  1281. this.y *= length;
  1282. this.z *= length;
  1283. this.w *= length;
  1284. return this;
  1285. };
  1286. Quaternion.prototype.toEulerAngles = function () {
  1287. var result = Vector3.Zero();
  1288. this.toEulerAnglesToRef(result);
  1289. return result;
  1290. };
  1291. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1292. //result is an EulerAngles in the in the z-x-z convention
  1293. var qx = this.x;
  1294. var qy = this.y;
  1295. var qz = this.z;
  1296. var qw = this.w;
  1297. var qxy = qx * qy;
  1298. var qxz = qx * qz;
  1299. var qwy = qw * qy;
  1300. var qwz = qw * qz;
  1301. var qwx = qw * qx;
  1302. var qyz = qy * qz;
  1303. var sqx = qx * qx;
  1304. var sqy = qy * qy;
  1305. var determinant = sqx + sqy;
  1306. if (determinant !== 0.000 && determinant !== 1.000) {
  1307. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1308. result.y = Math.acos(1 - 2 * determinant);
  1309. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1310. }
  1311. else {
  1312. if (determinant === 0.0) {
  1313. result.x = 0.0;
  1314. result.y = 0.0;
  1315. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1316. }
  1317. else {
  1318. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1319. result.y = Math.PI;
  1320. result.z = 0.0;
  1321. }
  1322. }
  1323. return this;
  1324. };
  1325. Quaternion.prototype.toRotationMatrix = function (result) {
  1326. var xx = this.x * this.x;
  1327. var yy = this.y * this.y;
  1328. var zz = this.z * this.z;
  1329. var xy = this.x * this.y;
  1330. var zw = this.z * this.w;
  1331. var zx = this.z * this.x;
  1332. var yw = this.y * this.w;
  1333. var yz = this.y * this.z;
  1334. var xw = this.x * this.w;
  1335. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1336. result.m[1] = 2.0 * (xy + zw);
  1337. result.m[2] = 2.0 * (zx - yw);
  1338. result.m[3] = 0;
  1339. result.m[4] = 2.0 * (xy - zw);
  1340. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1341. result.m[6] = 2.0 * (yz + xw);
  1342. result.m[7] = 0;
  1343. result.m[8] = 2.0 * (zx + yw);
  1344. result.m[9] = 2.0 * (yz - xw);
  1345. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1346. result.m[11] = 0;
  1347. result.m[12] = 0;
  1348. result.m[13] = 0;
  1349. result.m[14] = 0;
  1350. result.m[15] = 1.0;
  1351. return this;
  1352. };
  1353. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1354. Quaternion.FromRotationMatrixToRef(matrix, this);
  1355. return this;
  1356. };
  1357. // Statics
  1358. Quaternion.FromRotationMatrix = function (matrix) {
  1359. var result = new Quaternion();
  1360. Quaternion.FromRotationMatrixToRef(matrix, result);
  1361. return result;
  1362. };
  1363. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1364. var data = matrix.m;
  1365. var m11 = data[0], m12 = data[4], m13 = data[8];
  1366. var m21 = data[1], m22 = data[5], m23 = data[9];
  1367. var m31 = data[2], m32 = data[6], m33 = data[10];
  1368. var trace = m11 + m22 + m33;
  1369. var s;
  1370. if (trace > 0) {
  1371. s = 0.5 / Math.sqrt(trace + 1.0);
  1372. result.w = 0.25 / s;
  1373. result.x = (m32 - m23) * s;
  1374. result.y = (m13 - m31) * s;
  1375. result.z = (m21 - m12) * s;
  1376. }
  1377. else if (m11 > m22 && m11 > m33) {
  1378. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1379. result.w = (m32 - m23) / s;
  1380. result.x = 0.25 * s;
  1381. result.y = (m12 + m21) / s;
  1382. result.z = (m13 + m31) / s;
  1383. }
  1384. else if (m22 > m33) {
  1385. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1386. result.w = (m13 - m31) / s;
  1387. result.x = (m12 + m21) / s;
  1388. result.y = 0.25 * s;
  1389. result.z = (m23 + m32) / s;
  1390. }
  1391. else {
  1392. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1393. result.w = (m21 - m12) / s;
  1394. result.x = (m13 + m31) / s;
  1395. result.y = (m23 + m32) / s;
  1396. result.z = 0.25 * s;
  1397. }
  1398. };
  1399. Quaternion.Inverse = function (q) {
  1400. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1401. };
  1402. Quaternion.Identity = function () {
  1403. return new Quaternion(0, 0, 0, 1);
  1404. };
  1405. Quaternion.RotationAxis = function (axis, angle) {
  1406. var result = new Quaternion();
  1407. var sin = Math.sin(angle / 2);
  1408. axis.normalize();
  1409. result.w = Math.cos(angle / 2);
  1410. result.x = axis.x * sin;
  1411. result.y = axis.y * sin;
  1412. result.z = axis.z * sin;
  1413. return result;
  1414. };
  1415. Quaternion.FromArray = function (array, offset) {
  1416. if (!offset) {
  1417. offset = 0;
  1418. }
  1419. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1420. };
  1421. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1422. var result = new Quaternion();
  1423. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1424. return result;
  1425. };
  1426. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1427. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1428. var halfRoll = roll * 0.5;
  1429. var halfPitch = pitch * 0.5;
  1430. var halfYaw = yaw * 0.5;
  1431. var sinRoll = Math.sin(halfRoll);
  1432. var cosRoll = Math.cos(halfRoll);
  1433. var sinPitch = Math.sin(halfPitch);
  1434. var cosPitch = Math.cos(halfPitch);
  1435. var sinYaw = Math.sin(halfYaw);
  1436. var cosYaw = Math.cos(halfYaw);
  1437. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1438. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1439. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1440. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1441. };
  1442. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1448. // Produces a quaternion from Euler angles in the z-x-z orientation
  1449. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1450. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1451. var halfBeta = beta * 0.5;
  1452. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1454. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1456. };
  1457. Quaternion.Slerp = function (left, right, amount) {
  1458. var num2;
  1459. var num3;
  1460. var num = amount;
  1461. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1462. var flag = false;
  1463. if (num4 < 0) {
  1464. flag = true;
  1465. num4 = -num4;
  1466. }
  1467. if (num4 > 0.999999) {
  1468. num3 = 1 - num;
  1469. num2 = flag ? -num : num;
  1470. }
  1471. else {
  1472. var num5 = Math.acos(num4);
  1473. var num6 = (1.0 / Math.sin(num5));
  1474. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1475. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1476. }
  1477. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1478. };
  1479. return Quaternion;
  1480. })();
  1481. BABYLON.Quaternion = Quaternion;
  1482. var Matrix = (function () {
  1483. function Matrix() {
  1484. this.m = new Float32Array(16);
  1485. }
  1486. // Properties
  1487. Matrix.prototype.isIdentity = function () {
  1488. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1489. return false;
  1490. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1491. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1492. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1493. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1494. return false;
  1495. return true;
  1496. };
  1497. Matrix.prototype.determinant = function () {
  1498. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1499. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1500. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1501. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1502. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1503. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1504. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1505. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1506. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1507. };
  1508. // Methods
  1509. Matrix.prototype.toArray = function () {
  1510. return this.m;
  1511. };
  1512. Matrix.prototype.asArray = function () {
  1513. return this.toArray();
  1514. };
  1515. Matrix.prototype.invert = function () {
  1516. this.invertToRef(this);
  1517. return this;
  1518. };
  1519. Matrix.prototype.reset = function () {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = 0;
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.add = function (other) {
  1526. var result = new Matrix();
  1527. this.addToRef(other, result);
  1528. return result;
  1529. };
  1530. Matrix.prototype.addToRef = function (other, result) {
  1531. for (var index = 0; index < 16; index++) {
  1532. result.m[index] = this.m[index] + other.m[index];
  1533. }
  1534. return this;
  1535. };
  1536. Matrix.prototype.addToSelf = function (other) {
  1537. for (var index = 0; index < 16; index++) {
  1538. this.m[index] += other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.invertToRef = function (other) {
  1543. var l1 = this.m[0];
  1544. var l2 = this.m[1];
  1545. var l3 = this.m[2];
  1546. var l4 = this.m[3];
  1547. var l5 = this.m[4];
  1548. var l6 = this.m[5];
  1549. var l7 = this.m[6];
  1550. var l8 = this.m[7];
  1551. var l9 = this.m[8];
  1552. var l10 = this.m[9];
  1553. var l11 = this.m[10];
  1554. var l12 = this.m[11];
  1555. var l13 = this.m[12];
  1556. var l14 = this.m[13];
  1557. var l15 = this.m[14];
  1558. var l16 = this.m[15];
  1559. var l17 = (l11 * l16) - (l12 * l15);
  1560. var l18 = (l10 * l16) - (l12 * l14);
  1561. var l19 = (l10 * l15) - (l11 * l14);
  1562. var l20 = (l9 * l16) - (l12 * l13);
  1563. var l21 = (l9 * l15) - (l11 * l13);
  1564. var l22 = (l9 * l14) - (l10 * l13);
  1565. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1566. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1567. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1568. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1569. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1570. var l28 = (l7 * l16) - (l8 * l15);
  1571. var l29 = (l6 * l16) - (l8 * l14);
  1572. var l30 = (l6 * l15) - (l7 * l14);
  1573. var l31 = (l5 * l16) - (l8 * l13);
  1574. var l32 = (l5 * l15) - (l7 * l13);
  1575. var l33 = (l5 * l14) - (l6 * l13);
  1576. var l34 = (l7 * l12) - (l8 * l11);
  1577. var l35 = (l6 * l12) - (l8 * l10);
  1578. var l36 = (l6 * l11) - (l7 * l10);
  1579. var l37 = (l5 * l12) - (l8 * l9);
  1580. var l38 = (l5 * l11) - (l7 * l9);
  1581. var l39 = (l5 * l10) - (l6 * l9);
  1582. other.m[0] = l23 * l27;
  1583. other.m[4] = l24 * l27;
  1584. other.m[8] = l25 * l27;
  1585. other.m[12] = l26 * l27;
  1586. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1587. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1588. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1589. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1590. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1591. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1592. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1593. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1594. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1595. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1596. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1597. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1598. return this;
  1599. };
  1600. Matrix.prototype.invertToRefSIMD = function (other) {
  1601. var src = this.m;
  1602. var dest = other.m;
  1603. var row0, row1, row2, row3;
  1604. var tmp1;
  1605. var minor0, minor1, minor2, minor3;
  1606. var det;
  1607. // Load the 4 rows
  1608. var src0 = SIMD.float32x4.load(src, 0);
  1609. var src1 = SIMD.float32x4.load(src, 4);
  1610. var src2 = SIMD.float32x4.load(src, 8);
  1611. var src3 = SIMD.float32x4.load(src, 12);
  1612. // Transpose the source matrix. Sort of. Not a true transpose operation
  1613. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1614. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1615. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1616. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1617. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1618. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1619. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1620. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1621. // This is a true transposition, but it will lead to an incorrect result
  1622. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1623. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1624. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1625. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1626. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1627. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1628. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1629. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1630. // ----
  1631. tmp1 = SIMD.float32x4.mul(row2, row3);
  1632. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1633. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1634. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1635. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1636. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1637. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1638. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1639. // ----
  1640. tmp1 = SIMD.float32x4.mul(row1, row2);
  1641. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1643. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1646. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1647. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1652. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1653. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1656. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1657. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1658. // ----
  1659. tmp1 = SIMD.float32x4.mul(row0, row1);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1661. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1662. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1663. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1665. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1666. // ----
  1667. tmp1 = SIMD.float32x4.mul(row0, row3);
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1670. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1672. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1673. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1674. // ----
  1675. tmp1 = SIMD.float32x4.mul(row0, row2);
  1676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1677. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1678. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1680. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1681. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1682. // Compute determinant
  1683. det = SIMD.float32x4.mul(row0, minor0);
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1685. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1686. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1687. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1688. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1689. // These shuffles aren't necessary if the faulty transposition is done
  1690. // up at the top of this function.
  1691. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1692. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1693. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1694. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1695. // Compute final values by multiplying with 1/det
  1696. minor0 = SIMD.float32x4.mul(det, minor0);
  1697. minor1 = SIMD.float32x4.mul(det, minor1);
  1698. minor2 = SIMD.float32x4.mul(det, minor2);
  1699. minor3 = SIMD.float32x4.mul(det, minor3);
  1700. SIMD.float32x4.store(dest, 0, minor0);
  1701. SIMD.float32x4.store(dest, 4, minor1);
  1702. SIMD.float32x4.store(dest, 8, minor2);
  1703. SIMD.float32x4.store(dest, 12, minor3);
  1704. return this;
  1705. };
  1706. Matrix.prototype.setTranslation = function (vector3) {
  1707. this.m[12] = vector3.x;
  1708. this.m[13] = vector3.y;
  1709. this.m[14] = vector3.z;
  1710. return this;
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1786. if (offset === void 0) { offset = 0; }
  1787. var tm = this.m;
  1788. var om = other.m;
  1789. var om0 = SIMD.float32x4.load(om, 0);
  1790. var om1 = SIMD.float32x4.load(om, 4);
  1791. var om2 = SIMD.float32x4.load(om, 8);
  1792. var om3 = SIMD.float32x4.load(om, 12);
  1793. var tm0 = SIMD.float32x4.load(tm, 0);
  1794. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1795. var tm1 = SIMD.float32x4.load(tm, 4);
  1796. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1797. var tm2 = SIMD.float32x4.load(tm, 8);
  1798. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1799. var tm3 = SIMD.float32x4.load(tm, 12);
  1800. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1801. };
  1802. Matrix.prototype.equals = function (value) {
  1803. return value &&
  1804. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1805. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1806. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1807. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1808. };
  1809. Matrix.prototype.clone = function () {
  1810. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1811. };
  1812. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1813. translation.x = this.m[12];
  1814. translation.y = this.m[13];
  1815. translation.z = this.m[14];
  1816. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1817. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1818. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1819. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1820. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1821. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1822. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1823. rotation.x = 0;
  1824. rotation.y = 0;
  1825. rotation.z = 0;
  1826. rotation.w = 1;
  1827. return false;
  1828. }
  1829. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1830. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1831. return true;
  1832. };
  1833. // Statics
  1834. Matrix.FromArray = function (array, offset) {
  1835. var result = new Matrix();
  1836. if (!offset) {
  1837. offset = 0;
  1838. }
  1839. Matrix.FromArrayToRef(array, offset, result);
  1840. return result;
  1841. };
  1842. Matrix.FromArrayToRef = function (array, offset, result) {
  1843. for (var index = 0; index < 16; index++) {
  1844. result.m[index] = array[index + offset];
  1845. }
  1846. };
  1847. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1848. for (var index = 0; index < 16; index++) {
  1849. result.m[index] = array[index + offset] * scale;
  1850. }
  1851. };
  1852. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1853. result.m[0] = initialM11;
  1854. result.m[1] = initialM12;
  1855. result.m[2] = initialM13;
  1856. result.m[3] = initialM14;
  1857. result.m[4] = initialM21;
  1858. result.m[5] = initialM22;
  1859. result.m[6] = initialM23;
  1860. result.m[7] = initialM24;
  1861. result.m[8] = initialM31;
  1862. result.m[9] = initialM32;
  1863. result.m[10] = initialM33;
  1864. result.m[11] = initialM34;
  1865. result.m[12] = initialM41;
  1866. result.m[13] = initialM42;
  1867. result.m[14] = initialM43;
  1868. result.m[15] = initialM44;
  1869. };
  1870. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1871. var result = new Matrix();
  1872. result.m[0] = initialM11;
  1873. result.m[1] = initialM12;
  1874. result.m[2] = initialM13;
  1875. result.m[3] = initialM14;
  1876. result.m[4] = initialM21;
  1877. result.m[5] = initialM22;
  1878. result.m[6] = initialM23;
  1879. result.m[7] = initialM24;
  1880. result.m[8] = initialM31;
  1881. result.m[9] = initialM32;
  1882. result.m[10] = initialM33;
  1883. result.m[11] = initialM34;
  1884. result.m[12] = initialM41;
  1885. result.m[13] = initialM42;
  1886. result.m[14] = initialM43;
  1887. result.m[15] = initialM44;
  1888. return result;
  1889. };
  1890. Matrix.Compose = function (scale, rotation, translation) {
  1891. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1892. var rotationMatrix = Matrix.Identity();
  1893. rotation.toRotationMatrix(rotationMatrix);
  1894. result = result.multiply(rotationMatrix);
  1895. result.setTranslation(translation);
  1896. return result;
  1897. };
  1898. Matrix.Identity = function () {
  1899. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1900. };
  1901. Matrix.IdentityToRef = function (result) {
  1902. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1903. };
  1904. Matrix.Zero = function () {
  1905. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1906. };
  1907. Matrix.RotationX = function (angle) {
  1908. var result = new Matrix();
  1909. Matrix.RotationXToRef(angle, result);
  1910. return result;
  1911. };
  1912. Matrix.Invert = function (source) {
  1913. var result = new Matrix();
  1914. source.invertToRef(result);
  1915. return result;
  1916. };
  1917. Matrix.RotationXToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[0] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[5] = c;
  1923. result.m[10] = c;
  1924. result.m[9] = -s;
  1925. result.m[6] = s;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[7] = 0;
  1931. result.m[8] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationY = function (angle) {
  1938. var result = new Matrix();
  1939. Matrix.RotationYToRef(angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationYToRef = function (angle, result) {
  1943. var s = Math.sin(angle);
  1944. var c = Math.cos(angle);
  1945. result.m[5] = 1.0;
  1946. result.m[15] = 1.0;
  1947. result.m[0] = c;
  1948. result.m[2] = -s;
  1949. result.m[8] = s;
  1950. result.m[10] = c;
  1951. result.m[1] = 0;
  1952. result.m[3] = 0;
  1953. result.m[4] = 0;
  1954. result.m[6] = 0;
  1955. result.m[7] = 0;
  1956. result.m[9] = 0;
  1957. result.m[11] = 0;
  1958. result.m[12] = 0;
  1959. result.m[13] = 0;
  1960. result.m[14] = 0;
  1961. };
  1962. Matrix.RotationZ = function (angle) {
  1963. var result = new Matrix();
  1964. Matrix.RotationZToRef(angle, result);
  1965. return result;
  1966. };
  1967. Matrix.RotationZToRef = function (angle, result) {
  1968. var s = Math.sin(angle);
  1969. var c = Math.cos(angle);
  1970. result.m[10] = 1.0;
  1971. result.m[15] = 1.0;
  1972. result.m[0] = c;
  1973. result.m[1] = s;
  1974. result.m[4] = -s;
  1975. result.m[5] = c;
  1976. result.m[2] = 0;
  1977. result.m[3] = 0;
  1978. result.m[6] = 0;
  1979. result.m[7] = 0;
  1980. result.m[8] = 0;
  1981. result.m[9] = 0;
  1982. result.m[11] = 0;
  1983. result.m[12] = 0;
  1984. result.m[13] = 0;
  1985. result.m[14] = 0;
  1986. };
  1987. Matrix.RotationAxis = function (axis, angle) {
  1988. var s = Math.sin(-angle);
  1989. var c = Math.cos(-angle);
  1990. var c1 = 1 - c;
  1991. axis.normalize();
  1992. var result = Matrix.Zero();
  1993. result.m[0] = (axis.x * axis.x) * c1 + c;
  1994. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1995. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1996. result.m[3] = 0.0;
  1997. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1998. result.m[5] = (axis.y * axis.y) * c1 + c;
  1999. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2000. result.m[7] = 0.0;
  2001. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2002. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2003. result.m[10] = (axis.z * axis.z) * c1 + c;
  2004. result.m[11] = 0.0;
  2005. result.m[15] = 1.0;
  2006. return result;
  2007. };
  2008. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2009. var result = new Matrix();
  2010. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2011. return result;
  2012. };
  2013. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2014. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2015. this._tempQuaternion.toRotationMatrix(result);
  2016. };
  2017. Matrix.Scaling = function (x, y, z) {
  2018. var result = Matrix.Zero();
  2019. Matrix.ScalingToRef(x, y, z, result);
  2020. return result;
  2021. };
  2022. Matrix.ScalingToRef = function (x, y, z, result) {
  2023. result.m[0] = x;
  2024. result.m[1] = 0;
  2025. result.m[2] = 0;
  2026. result.m[3] = 0;
  2027. result.m[4] = 0;
  2028. result.m[5] = y;
  2029. result.m[6] = 0;
  2030. result.m[7] = 0;
  2031. result.m[8] = 0;
  2032. result.m[9] = 0;
  2033. result.m[10] = z;
  2034. result.m[11] = 0;
  2035. result.m[12] = 0;
  2036. result.m[13] = 0;
  2037. result.m[14] = 0;
  2038. result.m[15] = 1.0;
  2039. };
  2040. Matrix.Translation = function (x, y, z) {
  2041. var result = Matrix.Identity();
  2042. Matrix.TranslationToRef(x, y, z, result);
  2043. return result;
  2044. };
  2045. Matrix.TranslationToRef = function (x, y, z, result) {
  2046. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2047. };
  2048. Matrix.LookAtLH = function (eye, target, up) {
  2049. var result = Matrix.Zero();
  2050. Matrix.LookAtLHToRef(eye, target, up, result);
  2051. return result;
  2052. };
  2053. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2054. // Z axis
  2055. target.subtractToRef(eye, this._zAxis);
  2056. this._zAxis.normalize();
  2057. // X axis
  2058. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2059. if (this._xAxis.lengthSquared() === 0) {
  2060. this._xAxis.x = 1.0;
  2061. }
  2062. else {
  2063. this._xAxis.normalize();
  2064. }
  2065. // Y axis
  2066. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2067. this._yAxis.normalize();
  2068. // Eye angles
  2069. var ex = -Vector3.Dot(this._xAxis, eye);
  2070. var ey = -Vector3.Dot(this._yAxis, eye);
  2071. var ez = -Vector3.Dot(this._zAxis, eye);
  2072. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2073. };
  2074. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2075. var out = result.m;
  2076. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2077. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2078. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2079. // cc.kmVec3Subtract(f, pCenter, pEye);
  2080. var f = SIMD.float32x4.sub(center, eye);
  2081. // cc.kmVec3Normalize(f, f);
  2082. var tmp = SIMD.float32x4.mul(f, f);
  2083. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2084. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2085. // cc.kmVec3Assign(up, pUp);
  2086. // cc.kmVec3Normalize(up, up);
  2087. tmp = SIMD.float32x4.mul(up, up);
  2088. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2089. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2090. // cc.kmVec3Cross(s, f, up);
  2091. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2092. // cc.kmVec3Normalize(s, s);
  2093. tmp = SIMD.float32x4.mul(s, s);
  2094. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2095. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2096. // cc.kmVec3Cross(u, s, f);
  2097. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2098. // cc.kmVec3Normalize(s, s);
  2099. tmp = SIMD.float32x4.mul(s, s);
  2100. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2101. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2102. var zero = SIMD.float32x4.splat(0.0);
  2103. s = SIMD.float32x4.neg(s);
  2104. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2105. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2106. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2107. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2108. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2109. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2110. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2111. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2112. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2113. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2114. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2115. var b3 = SIMD.float32x4.neg(eye);
  2116. b3 = SIMD.float32x4.withW(b3, 1.0);
  2117. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2118. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2119. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2120. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2121. };
  2122. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2123. var matrix = Matrix.Zero();
  2124. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2125. return matrix;
  2126. };
  2127. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2128. var hw = 2.0 / width;
  2129. var hh = 2.0 / height;
  2130. var id = 1.0 / (zfar - znear);
  2131. var nid = znear / (znear - zfar);
  2132. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2133. };
  2134. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2135. var matrix = Matrix.Zero();
  2136. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2137. return matrix;
  2138. };
  2139. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2140. result.m[0] = 2.0 / (right - left);
  2141. result.m[1] = result.m[2] = result.m[3] = 0;
  2142. result.m[5] = 2.0 / (top - bottom);
  2143. result.m[4] = result.m[6] = result.m[7] = 0;
  2144. result.m[10] = -1.0 / (znear - zfar);
  2145. result.m[8] = result.m[9] = result.m[11] = 0;
  2146. result.m[12] = (left + right) / (left - right);
  2147. result.m[13] = (top + bottom) / (bottom - top);
  2148. result.m[14] = znear / (znear - zfar);
  2149. result.m[15] = 1.0;
  2150. };
  2151. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2152. var matrix = Matrix.Zero();
  2153. matrix.m[0] = (2.0 * znear) / width;
  2154. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2155. matrix.m[5] = (2.0 * znear) / height;
  2156. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2157. matrix.m[10] = -zfar / (znear - zfar);
  2158. matrix.m[8] = matrix.m[9] = 0.0;
  2159. matrix.m[11] = 1.0;
  2160. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2161. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2162. return matrix;
  2163. };
  2164. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2165. var matrix = Matrix.Zero();
  2166. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2167. return matrix;
  2168. };
  2169. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2170. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2171. var tan = 1.0 / (Math.tan(fov * 0.5));
  2172. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2173. if (v_fixed) {
  2174. result.m[0] = tan / aspect;
  2175. }
  2176. else {
  2177. result.m[0] = tan;
  2178. }
  2179. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2180. if (v_fixed) {
  2181. result.m[5] = tan;
  2182. }
  2183. else {
  2184. result.m[5] = tan * aspect;
  2185. }
  2186. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2187. result.m[8] = result.m[9] = 0.0;
  2188. result.m[10] = -zfar / (znear - zfar);
  2189. result.m[11] = 1.0;
  2190. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2191. result.m[14] = (znear * zfar) / (znear - zfar);
  2192. };
  2193. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2194. var cw = viewport.width;
  2195. var ch = viewport.height;
  2196. var cx = viewport.x;
  2197. var cy = viewport.y;
  2198. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2199. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2200. };
  2201. Matrix.GetAsMatrix2x2 = function (matrix) {
  2202. return new Float32Array([
  2203. matrix.m[0], matrix.m[1],
  2204. matrix.m[4], matrix.m[5]
  2205. ]);
  2206. };
  2207. Matrix.GetAsMatrix3x3 = function (matrix) {
  2208. return new Float32Array([
  2209. matrix.m[0], matrix.m[1], matrix.m[2],
  2210. matrix.m[4], matrix.m[5], matrix.m[6],
  2211. matrix.m[8], matrix.m[9], matrix.m[10]
  2212. ]);
  2213. };
  2214. Matrix.Transpose = function (matrix) {
  2215. var result = new Matrix();
  2216. result.m[0] = matrix.m[0];
  2217. result.m[1] = matrix.m[4];
  2218. result.m[2] = matrix.m[8];
  2219. result.m[3] = matrix.m[12];
  2220. result.m[4] = matrix.m[1];
  2221. result.m[5] = matrix.m[5];
  2222. result.m[6] = matrix.m[9];
  2223. result.m[7] = matrix.m[13];
  2224. result.m[8] = matrix.m[2];
  2225. result.m[9] = matrix.m[6];
  2226. result.m[10] = matrix.m[10];
  2227. result.m[11] = matrix.m[14];
  2228. result.m[12] = matrix.m[3];
  2229. result.m[13] = matrix.m[7];
  2230. result.m[14] = matrix.m[11];
  2231. result.m[15] = matrix.m[15];
  2232. return result;
  2233. };
  2234. Matrix.Reflection = function (plane) {
  2235. var matrix = new Matrix();
  2236. Matrix.ReflectionToRef(plane, matrix);
  2237. return matrix;
  2238. };
  2239. Matrix.ReflectionToRef = function (plane, result) {
  2240. plane.normalize();
  2241. var x = plane.normal.x;
  2242. var y = plane.normal.y;
  2243. var z = plane.normal.z;
  2244. var temp = -2 * x;
  2245. var temp2 = -2 * y;
  2246. var temp3 = -2 * z;
  2247. result.m[0] = (temp * x) + 1;
  2248. result.m[1] = temp2 * x;
  2249. result.m[2] = temp3 * x;
  2250. result.m[3] = 0.0;
  2251. result.m[4] = temp * y;
  2252. result.m[5] = (temp2 * y) + 1;
  2253. result.m[6] = temp3 * y;
  2254. result.m[7] = 0.0;
  2255. result.m[8] = temp * z;
  2256. result.m[9] = temp2 * z;
  2257. result.m[10] = (temp3 * z) + 1;
  2258. result.m[11] = 0.0;
  2259. result.m[12] = temp * plane.d;
  2260. result.m[13] = temp2 * plane.d;
  2261. result.m[14] = temp3 * plane.d;
  2262. result.m[15] = 1.0;
  2263. };
  2264. Matrix._tempQuaternion = new Quaternion();
  2265. Matrix._xAxis = Vector3.Zero();
  2266. Matrix._yAxis = Vector3.Zero();
  2267. Matrix._zAxis = Vector3.Zero();
  2268. return Matrix;
  2269. })();
  2270. BABYLON.Matrix = Matrix;
  2271. var Plane = (function () {
  2272. function Plane(a, b, c, d) {
  2273. this.normal = new Vector3(a, b, c);
  2274. this.d = d;
  2275. }
  2276. Plane.prototype.asArray = function () {
  2277. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2278. };
  2279. // Methods
  2280. Plane.prototype.clone = function () {
  2281. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2282. };
  2283. Plane.prototype.normalize = function () {
  2284. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2285. var magnitude = 0;
  2286. if (norm !== 0) {
  2287. magnitude = 1.0 / norm;
  2288. }
  2289. this.normal.x *= magnitude;
  2290. this.normal.y *= magnitude;
  2291. this.normal.z *= magnitude;
  2292. this.d *= magnitude;
  2293. return this;
  2294. };
  2295. Plane.prototype.transform = function (transformation) {
  2296. var transposedMatrix = Matrix.Transpose(transformation);
  2297. var x = this.normal.x;
  2298. var y = this.normal.y;
  2299. var z = this.normal.z;
  2300. var d = this.d;
  2301. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2302. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2303. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2304. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2305. return new Plane(normalX, normalY, normalZ, finalD);
  2306. };
  2307. Plane.prototype.dotCoordinate = function (point) {
  2308. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2309. };
  2310. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2311. var x1 = point2.x - point1.x;
  2312. var y1 = point2.y - point1.y;
  2313. var z1 = point2.z - point1.z;
  2314. var x2 = point3.x - point1.x;
  2315. var y2 = point3.y - point1.y;
  2316. var z2 = point3.z - point1.z;
  2317. var yz = (y1 * z2) - (z1 * y2);
  2318. var xz = (z1 * x2) - (x1 * z2);
  2319. var xy = (x1 * y2) - (y1 * x2);
  2320. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2321. var invPyth;
  2322. if (pyth !== 0) {
  2323. invPyth = 1.0 / pyth;
  2324. }
  2325. else {
  2326. invPyth = 0;
  2327. }
  2328. this.normal.x = yz * invPyth;
  2329. this.normal.y = xz * invPyth;
  2330. this.normal.z = xy * invPyth;
  2331. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2332. return this;
  2333. };
  2334. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2335. var dot = Vector3.Dot(this.normal, direction);
  2336. return (dot <= epsilon);
  2337. };
  2338. Plane.prototype.signedDistanceTo = function (point) {
  2339. return Vector3.Dot(point, this.normal) + this.d;
  2340. };
  2341. // Statics
  2342. Plane.FromArray = function (array) {
  2343. return new Plane(array[0], array[1], array[2], array[3]);
  2344. };
  2345. Plane.FromPoints = function (point1, point2, point3) {
  2346. var result = new Plane(0, 0, 0, 0);
  2347. result.copyFromPoints(point1, point2, point3);
  2348. return result;
  2349. };
  2350. Plane.FromPositionAndNormal = function (origin, normal) {
  2351. var result = new Plane(0, 0, 0, 0);
  2352. normal.normalize();
  2353. result.normal = normal;
  2354. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2355. return result;
  2356. };
  2357. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2358. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2359. return Vector3.Dot(point, normal) + d;
  2360. };
  2361. return Plane;
  2362. })();
  2363. BABYLON.Plane = Plane;
  2364. var Viewport = (function () {
  2365. function Viewport(x, y, width, height) {
  2366. this.x = x;
  2367. this.y = y;
  2368. this.width = width;
  2369. this.height = height;
  2370. }
  2371. Viewport.prototype.toGlobal = function (engine) {
  2372. var width = engine.getRenderWidth();
  2373. var height = engine.getRenderHeight();
  2374. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2375. };
  2376. return Viewport;
  2377. })();
  2378. BABYLON.Viewport = Viewport;
  2379. var Frustum = (function () {
  2380. function Frustum() {
  2381. }
  2382. Frustum.GetPlanes = function (transform) {
  2383. var frustumPlanes = [];
  2384. for (var index = 0; index < 6; index++) {
  2385. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2386. }
  2387. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2388. return frustumPlanes;
  2389. };
  2390. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2391. // Near
  2392. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2393. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2394. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2395. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2396. frustumPlanes[0].normalize();
  2397. // Far
  2398. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2399. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2400. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2401. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2402. frustumPlanes[1].normalize();
  2403. // Left
  2404. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2405. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2406. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2407. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2408. frustumPlanes[2].normalize();
  2409. // Right
  2410. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2411. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2412. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2413. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2414. frustumPlanes[3].normalize();
  2415. // Top
  2416. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2417. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2418. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2419. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2420. frustumPlanes[4].normalize();
  2421. // Bottom
  2422. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2423. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2424. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2425. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2426. frustumPlanes[5].normalize();
  2427. };
  2428. return Frustum;
  2429. })();
  2430. BABYLON.Frustum = Frustum;
  2431. var Ray = (function () {
  2432. function Ray(origin, direction, length) {
  2433. if (length === void 0) { length = Number.MAX_VALUE; }
  2434. this.origin = origin;
  2435. this.direction = direction;
  2436. this.length = length;
  2437. }
  2438. // Methods
  2439. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2440. var d = 0.0;
  2441. var maxValue = Number.MAX_VALUE;
  2442. var inv;
  2443. var min;
  2444. var max;
  2445. var temp;
  2446. if (Math.abs(this.direction.x) < 0.0000001) {
  2447. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2448. return false;
  2449. }
  2450. }
  2451. else {
  2452. inv = 1.0 / this.direction.x;
  2453. min = (minimum.x - this.origin.x) * inv;
  2454. max = (maximum.x - this.origin.x) * inv;
  2455. if (max === -Infinity) {
  2456. max = Infinity;
  2457. }
  2458. if (min > max) {
  2459. temp = min;
  2460. min = max;
  2461. max = temp;
  2462. }
  2463. d = Math.max(min, d);
  2464. maxValue = Math.min(max, maxValue);
  2465. if (d > maxValue) {
  2466. return false;
  2467. }
  2468. }
  2469. if (Math.abs(this.direction.y) < 0.0000001) {
  2470. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2471. return false;
  2472. }
  2473. }
  2474. else {
  2475. inv = 1.0 / this.direction.y;
  2476. min = (minimum.y - this.origin.y) * inv;
  2477. max = (maximum.y - this.origin.y) * inv;
  2478. if (max === -Infinity) {
  2479. max = Infinity;
  2480. }
  2481. if (min > max) {
  2482. temp = min;
  2483. min = max;
  2484. max = temp;
  2485. }
  2486. d = Math.max(min, d);
  2487. maxValue = Math.min(max, maxValue);
  2488. if (d > maxValue) {
  2489. return false;
  2490. }
  2491. }
  2492. if (Math.abs(this.direction.z) < 0.0000001) {
  2493. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2494. return false;
  2495. }
  2496. }
  2497. else {
  2498. inv = 1.0 / this.direction.z;
  2499. min = (minimum.z - this.origin.z) * inv;
  2500. max = (maximum.z - this.origin.z) * inv;
  2501. if (max === -Infinity) {
  2502. max = Infinity;
  2503. }
  2504. if (min > max) {
  2505. temp = min;
  2506. min = max;
  2507. max = temp;
  2508. }
  2509. d = Math.max(min, d);
  2510. maxValue = Math.min(max, maxValue);
  2511. if (d > maxValue) {
  2512. return false;
  2513. }
  2514. }
  2515. return true;
  2516. };
  2517. Ray.prototype.intersectsBox = function (box) {
  2518. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2519. };
  2520. Ray.prototype.intersectsSphere = function (sphere) {
  2521. var x = sphere.center.x - this.origin.x;
  2522. var y = sphere.center.y - this.origin.y;
  2523. var z = sphere.center.z - this.origin.z;
  2524. var pyth = (x * x) + (y * y) + (z * z);
  2525. var rr = sphere.radius * sphere.radius;
  2526. if (pyth <= rr) {
  2527. return true;
  2528. }
  2529. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2530. if (dot < 0.0) {
  2531. return false;
  2532. }
  2533. var temp = pyth - (dot * dot);
  2534. return temp <= rr;
  2535. };
  2536. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2537. if (!this._edge1) {
  2538. this._edge1 = Vector3.Zero();
  2539. this._edge2 = Vector3.Zero();
  2540. this._pvec = Vector3.Zero();
  2541. this._tvec = Vector3.Zero();
  2542. this._qvec = Vector3.Zero();
  2543. }
  2544. vertex1.subtractToRef(vertex0, this._edge1);
  2545. vertex2.subtractToRef(vertex0, this._edge2);
  2546. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2547. var det = Vector3.Dot(this._edge1, this._pvec);
  2548. if (det === 0) {
  2549. return null;
  2550. }
  2551. var invdet = 1 / det;
  2552. this.origin.subtractToRef(vertex0, this._tvec);
  2553. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2554. if (bu < 0 || bu > 1.0) {
  2555. return null;
  2556. }
  2557. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2558. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2559. if (bv < 0 || bu + bv > 1.0) {
  2560. return null;
  2561. }
  2562. //check if the distance is longer than the predefined length.
  2563. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2564. if (distance > this.length) {
  2565. return null;
  2566. }
  2567. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2568. };
  2569. // Statics
  2570. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2571. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2572. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2573. var direction = end.subtract(start);
  2574. direction.normalize();
  2575. return new Ray(start, direction);
  2576. };
  2577. /**
  2578. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2579. * transformed to the given world matrix.
  2580. * @param origin The origin point
  2581. * @param end The end point
  2582. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2583. */
  2584. Ray.CreateNewFromTo = function (origin, end, world) {
  2585. if (world === void 0) { world = Matrix.Identity(); }
  2586. var direction = end.subtract(origin);
  2587. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2588. direction.normalize();
  2589. return Ray.Transform(new Ray(origin, direction, length), world);
  2590. };
  2591. Ray.Transform = function (ray, matrix) {
  2592. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2593. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2594. return new Ray(newOrigin, newDirection, ray.length);
  2595. };
  2596. return Ray;
  2597. })();
  2598. BABYLON.Ray = Ray;
  2599. (function (Space) {
  2600. Space[Space["LOCAL"] = 0] = "LOCAL";
  2601. Space[Space["WORLD"] = 1] = "WORLD";
  2602. })(BABYLON.Space || (BABYLON.Space = {}));
  2603. var Space = BABYLON.Space;
  2604. var Axis = (function () {
  2605. function Axis() {
  2606. }
  2607. Axis.X = new Vector3(1, 0, 0);
  2608. Axis.Y = new Vector3(0, 1, 0);
  2609. Axis.Z = new Vector3(0, 0, 1);
  2610. return Axis;
  2611. })();
  2612. BABYLON.Axis = Axis;
  2613. ;
  2614. var BezierCurve = (function () {
  2615. function BezierCurve() {
  2616. }
  2617. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2618. // Extract X (which is equal to time here)
  2619. var f0 = 1 - 3 * x2 + 3 * x1;
  2620. var f1 = 3 * x2 - 6 * x1;
  2621. var f2 = 3 * x1;
  2622. var refinedT = t;
  2623. for (var i = 0; i < 5; i++) {
  2624. var refinedT2 = refinedT * refinedT;
  2625. var refinedT3 = refinedT2 * refinedT;
  2626. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2627. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2628. refinedT -= (x - t) * slope;
  2629. refinedT = Math.min(1, Math.max(0, refinedT));
  2630. }
  2631. // Resolve cubic bezier for the given x
  2632. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2633. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2634. Math.pow(refinedT, 3);
  2635. };
  2636. return BezierCurve;
  2637. })();
  2638. BABYLON.BezierCurve = BezierCurve;
  2639. (function (Orientation) {
  2640. Orientation[Orientation["CW"] = 0] = "CW";
  2641. Orientation[Orientation["CCW"] = 1] = "CCW";
  2642. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2643. var Orientation = BABYLON.Orientation;
  2644. var Angle = (function () {
  2645. function Angle(radians) {
  2646. var _this = this;
  2647. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2648. this.radians = function () { return _this._radians; };
  2649. this._radians = radians;
  2650. if (this._radians < 0)
  2651. this._radians += (2 * Math.PI);
  2652. }
  2653. Angle.BetweenTwoPoints = function (a, b) {
  2654. var delta = b.subtract(a);
  2655. var theta = Math.atan2(delta.y, delta.x);
  2656. return new Angle(theta);
  2657. };
  2658. Angle.FromRadians = function (radians) {
  2659. return new Angle(radians);
  2660. };
  2661. Angle.FromDegrees = function (degrees) {
  2662. return new Angle(degrees * Math.PI / 180);
  2663. };
  2664. return Angle;
  2665. })();
  2666. BABYLON.Angle = Angle;
  2667. var Arc2 = (function () {
  2668. function Arc2(startPoint, midPoint, endPoint) {
  2669. this.startPoint = startPoint;
  2670. this.midPoint = midPoint;
  2671. this.endPoint = endPoint;
  2672. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2673. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2674. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2675. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2676. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2677. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2678. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2679. var a1 = this.startAngle.degrees();
  2680. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2681. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2682. // angles correction
  2683. if (a2 - a1 > +180.0)
  2684. a2 -= 360.0;
  2685. if (a2 - a1 < -180.0)
  2686. a2 += 360.0;
  2687. if (a3 - a2 > +180.0)
  2688. a3 -= 360.0;
  2689. if (a3 - a2 < -180.0)
  2690. a3 += 360.0;
  2691. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2692. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2693. }
  2694. return Arc2;
  2695. })();
  2696. BABYLON.Arc2 = Arc2;
  2697. var PathCursor = (function () {
  2698. function PathCursor(path) {
  2699. this.path = path;
  2700. this._onchange = new Array();
  2701. this.value = 0;
  2702. this.animations = new Array();
  2703. }
  2704. PathCursor.prototype.getPoint = function () {
  2705. var point = this.path.getPointAtLengthPosition(this.value);
  2706. return new Vector3(point.x, 0, point.y);
  2707. };
  2708. PathCursor.prototype.moveAhead = function (step) {
  2709. if (step === void 0) { step = 0.002; }
  2710. this.move(step);
  2711. return this;
  2712. };
  2713. PathCursor.prototype.moveBack = function (step) {
  2714. if (step === void 0) { step = 0.002; }
  2715. this.move(-step);
  2716. return this;
  2717. };
  2718. PathCursor.prototype.move = function (step) {
  2719. if (Math.abs(step) > 1) {
  2720. throw "step size should be less than 1.";
  2721. }
  2722. this.value += step;
  2723. this.ensureLimits();
  2724. this.raiseOnChange();
  2725. return this;
  2726. };
  2727. PathCursor.prototype.ensureLimits = function () {
  2728. while (this.value > 1) {
  2729. this.value -= 1;
  2730. }
  2731. while (this.value < 0) {
  2732. this.value += 1;
  2733. }
  2734. return this;
  2735. };
  2736. // used by animation engine
  2737. PathCursor.prototype.markAsDirty = function (propertyName) {
  2738. this.ensureLimits();
  2739. this.raiseOnChange();
  2740. return this;
  2741. };
  2742. PathCursor.prototype.raiseOnChange = function () {
  2743. var _this = this;
  2744. this._onchange.forEach(function (f) { return f(_this); });
  2745. return this;
  2746. };
  2747. PathCursor.prototype.onchange = function (f) {
  2748. this._onchange.push(f);
  2749. return this;
  2750. };
  2751. return PathCursor;
  2752. })();
  2753. BABYLON.PathCursor = PathCursor;
  2754. var Path2 = (function () {
  2755. function Path2(x, y) {
  2756. this._points = new Array();
  2757. this._length = 0;
  2758. this.closed = false;
  2759. this._points.push(new Vector2(x, y));
  2760. }
  2761. Path2.prototype.addLineTo = function (x, y) {
  2762. if (closed) {
  2763. BABYLON.Tools.Error("cannot add lines to closed paths");
  2764. return this;
  2765. }
  2766. var newPoint = new Vector2(x, y);
  2767. var previousPoint = this._points[this._points.length - 1];
  2768. this._points.push(newPoint);
  2769. this._length += newPoint.subtract(previousPoint).length();
  2770. return this;
  2771. };
  2772. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2773. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2774. if (closed) {
  2775. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2776. return this;
  2777. }
  2778. var startPoint = this._points[this._points.length - 1];
  2779. var midPoint = new Vector2(midX, midY);
  2780. var endPoint = new Vector2(endX, endY);
  2781. var arc = new Arc2(startPoint, midPoint, endPoint);
  2782. var increment = arc.angle.radians() / numberOfSegments;
  2783. if (arc.orientation === Orientation.CW)
  2784. increment *= -1;
  2785. var currentAngle = arc.startAngle.radians() + increment;
  2786. for (var i = 0; i < numberOfSegments; i++) {
  2787. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2788. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2789. this.addLineTo(x, y);
  2790. currentAngle += increment;
  2791. }
  2792. return this;
  2793. };
  2794. Path2.prototype.close = function () {
  2795. this.closed = true;
  2796. return this;
  2797. };
  2798. Path2.prototype.length = function () {
  2799. var result = this._length;
  2800. if (!this.closed) {
  2801. var lastPoint = this._points[this._points.length - 1];
  2802. var firstPoint = this._points[0];
  2803. result += (firstPoint.subtract(lastPoint).length());
  2804. }
  2805. return result;
  2806. };
  2807. Path2.prototype.getPoints = function () {
  2808. return this._points;
  2809. };
  2810. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2811. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2812. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2813. return Vector2.Zero();
  2814. }
  2815. var lengthPosition = normalizedLengthPosition * this.length();
  2816. var previousOffset = 0;
  2817. for (var i = 0; i < this._points.length; i++) {
  2818. var j = (i + 1) % this._points.length;
  2819. var a = this._points[i];
  2820. var b = this._points[j];
  2821. var bToA = b.subtract(a);
  2822. var nextOffset = (bToA.length() + previousOffset);
  2823. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2824. var dir = bToA.normalize();
  2825. var localOffset = lengthPosition - previousOffset;
  2826. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2827. }
  2828. previousOffset = nextOffset;
  2829. }
  2830. BABYLON.Tools.Error("internal error");
  2831. return Vector2.Zero();
  2832. };
  2833. Path2.StartingAt = function (x, y) {
  2834. return new Path2(x, y);
  2835. };
  2836. return Path2;
  2837. })();
  2838. BABYLON.Path2 = Path2;
  2839. var Path3D = (function () {
  2840. /**
  2841. * new Path3D(path, normal, raw)
  2842. * path : an array of Vector3, the curve axis of the Path3D
  2843. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2844. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2845. */
  2846. function Path3D(path, firstNormal, raw) {
  2847. this.path = path;
  2848. this._curve = new Array();
  2849. this._distances = new Array();
  2850. this._tangents = new Array();
  2851. this._normals = new Array();
  2852. this._binormals = new Array();
  2853. for (var p = 0; p < path.length; p++) {
  2854. this._curve[p] = path[p].clone(); // hard copy
  2855. }
  2856. this._raw = raw || false;
  2857. this._compute(firstNormal);
  2858. }
  2859. Path3D.prototype.getCurve = function () {
  2860. return this._curve;
  2861. };
  2862. Path3D.prototype.getTangents = function () {
  2863. return this._tangents;
  2864. };
  2865. Path3D.prototype.getNormals = function () {
  2866. return this._normals;
  2867. };
  2868. Path3D.prototype.getBinormals = function () {
  2869. return this._binormals;
  2870. };
  2871. Path3D.prototype.getDistances = function () {
  2872. return this._distances;
  2873. };
  2874. Path3D.prototype.update = function (path, firstNormal) {
  2875. for (var p = 0; p < path.length; p++) {
  2876. this._curve[p].x = path[p].x;
  2877. this._curve[p].y = path[p].y;
  2878. this._curve[p].z = path[p].z;
  2879. }
  2880. this._compute(firstNormal);
  2881. return this;
  2882. };
  2883. // private function compute() : computes tangents, normals and binormals
  2884. Path3D.prototype._compute = function (firstNormal) {
  2885. var l = this._curve.length;
  2886. // first and last tangents
  2887. this._tangents[0] = this._getFirstNonNullVector(0);
  2888. if (!this._raw) {
  2889. this._tangents[0].normalize();
  2890. }
  2891. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2892. if (!this._raw) {
  2893. this._tangents[l - 1].normalize();
  2894. }
  2895. // normals and binormals at first point : arbitrary vector with _normalVector()
  2896. var tg0 = this._tangents[0];
  2897. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2898. this._normals[0] = pp0;
  2899. if (!this._raw) {
  2900. this._normals[0].normalize();
  2901. }
  2902. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2903. if (!this._raw) {
  2904. this._binormals[0].normalize();
  2905. }
  2906. this._distances[0] = 0;
  2907. // normals and binormals : next points
  2908. var prev; // previous vector (segment)
  2909. var cur; // current vector (segment)
  2910. var curTang; // current tangent
  2911. // previous normal
  2912. var prevBinor; // previous binormal
  2913. for (var i = 1; i < l; i++) {
  2914. // tangents
  2915. prev = this._getLastNonNullVector(i);
  2916. if (i < l - 1) {
  2917. cur = this._getFirstNonNullVector(i);
  2918. this._tangents[i] = prev.add(cur);
  2919. this._tangents[i].normalize();
  2920. }
  2921. this._distances[i] = this._distances[i - 1] + prev.length();
  2922. // normals and binormals
  2923. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2924. curTang = this._tangents[i];
  2925. prevBinor = this._binormals[i - 1];
  2926. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2927. if (!this._raw) {
  2928. this._normals[i].normalize();
  2929. }
  2930. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2931. if (!this._raw) {
  2932. this._binormals[i].normalize();
  2933. }
  2934. }
  2935. };
  2936. // private function getFirstNonNullVector(index)
  2937. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2938. Path3D.prototype._getFirstNonNullVector = function (index) {
  2939. var i = 1;
  2940. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2941. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2942. i++;
  2943. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. }
  2945. return nNVector;
  2946. };
  2947. // private function getLastNonNullVector(index)
  2948. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2949. Path3D.prototype._getLastNonNullVector = function (index) {
  2950. var i = 1;
  2951. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2952. while (nLVector.length() === 0 && index > i + 1) {
  2953. i++;
  2954. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. }
  2956. return nLVector;
  2957. };
  2958. // private function normalVector(v0, vt, va) :
  2959. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2960. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2961. Path3D.prototype._normalVector = function (v0, vt, va) {
  2962. var normal0;
  2963. if (va === undefined || va === null) {
  2964. var point;
  2965. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2966. point = new Vector3(0, -1, 0);
  2967. }
  2968. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(1, 0, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(0, 0, 1);
  2973. }
  2974. normal0 = Vector3.Cross(vt, point);
  2975. }
  2976. else {
  2977. normal0 = Vector3.Cross(vt, va);
  2978. Vector3.CrossToRef(normal0, vt, normal0);
  2979. }
  2980. normal0.normalize();
  2981. return normal0;
  2982. };
  2983. return Path3D;
  2984. })();
  2985. BABYLON.Path3D = Path3D;
  2986. var Curve3 = (function () {
  2987. function Curve3(points) {
  2988. this._length = 0;
  2989. this._points = points;
  2990. this._length = this._computeLength(points);
  2991. }
  2992. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2993. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2994. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2995. var bez = new Array();
  2996. var equation = function (t, val0, val1, val2) {
  2997. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2998. return res;
  2999. };
  3000. for (var i = 0; i <= nbPoints; i++) {
  3001. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3002. }
  3003. return new Curve3(bez);
  3004. };
  3005. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3006. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3007. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3008. var bez = new Array();
  3009. var equation = function (t, val0, val1, val2, val3) {
  3010. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  3011. return res;
  3012. };
  3013. for (var i = 0; i <= nbPoints; i++) {
  3014. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3015. }
  3016. return new Curve3(bez);
  3017. };
  3018. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3019. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3020. var hermite = new Array();
  3021. var step = 1 / nbPoints;
  3022. for (var i = 0; i <= nbPoints; i++) {
  3023. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3024. }
  3025. return new Curve3(hermite);
  3026. };
  3027. Curve3.prototype.getPoints = function () {
  3028. return this._points;
  3029. };
  3030. Curve3.prototype.length = function () {
  3031. return this._length;
  3032. };
  3033. Curve3.prototype.continue = function (curve) {
  3034. var lastPoint = this._points[this._points.length - 1];
  3035. var continuedPoints = this._points.slice();
  3036. var curvePoints = curve.getPoints();
  3037. for (var i = 1; i < curvePoints.length; i++) {
  3038. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3039. }
  3040. var continuedCurve = new Curve3(continuedPoints);
  3041. return continuedCurve;
  3042. };
  3043. Curve3.prototype._computeLength = function (path) {
  3044. var l = 0;
  3045. for (var i = 1; i < path.length; i++) {
  3046. l += (path[i].subtract(path[i - 1])).length();
  3047. }
  3048. return l;
  3049. };
  3050. return Curve3;
  3051. })();
  3052. BABYLON.Curve3 = Curve3;
  3053. // Vertex formats
  3054. var PositionNormalVertex = (function () {
  3055. function PositionNormalVertex(position, normal) {
  3056. if (position === void 0) { position = Vector3.Zero(); }
  3057. if (normal === void 0) { normal = Vector3.Up(); }
  3058. this.position = position;
  3059. this.normal = normal;
  3060. }
  3061. PositionNormalVertex.prototype.clone = function () {
  3062. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3063. };
  3064. return PositionNormalVertex;
  3065. })();
  3066. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3067. var PositionNormalTextureVertex = (function () {
  3068. function PositionNormalTextureVertex(position, normal, uv) {
  3069. if (position === void 0) { position = Vector3.Zero(); }
  3070. if (normal === void 0) { normal = Vector3.Up(); }
  3071. if (uv === void 0) { uv = Vector2.Zero(); }
  3072. this.position = position;
  3073. this.normal = normal;
  3074. this.uv = uv;
  3075. }
  3076. PositionNormalTextureVertex.prototype.clone = function () {
  3077. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3078. };
  3079. return PositionNormalTextureVertex;
  3080. })();
  3081. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3082. // SIMD
  3083. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3084. var previousInvertToRef = Matrix.prototype.invertToRef;
  3085. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3086. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3087. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3088. var SIMDHelper = (function () {
  3089. function SIMDHelper() {
  3090. }
  3091. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3092. get: function () {
  3093. return SIMDHelper._isEnabled;
  3094. },
  3095. enumerable: true,
  3096. configurable: true
  3097. });
  3098. SIMDHelper.DisableSIMD = function () {
  3099. // Replace functions
  3100. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3101. Matrix.prototype.invertToRef = previousInvertToRef;
  3102. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3103. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3104. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3105. SIMDHelper._isEnabled = false;
  3106. };
  3107. SIMDHelper.EnableSIMD = function () {
  3108. if (window.SIMD === undefined) {
  3109. return;
  3110. }
  3111. // Replace functions
  3112. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3113. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3114. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3115. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3116. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3117. Object.defineProperty(Vector3.prototype, "x", {
  3118. get: function () { return this._data[0]; },
  3119. set: function (value) {
  3120. if (!this._data) {
  3121. this._data = new Float32Array(3);
  3122. }
  3123. this._data[0] = value;
  3124. }
  3125. });
  3126. Object.defineProperty(Vector3.prototype, "y", {
  3127. get: function () { return this._data[1]; },
  3128. set: function (value) {
  3129. this._data[1] = value;
  3130. }
  3131. });
  3132. Object.defineProperty(Vector3.prototype, "z", {
  3133. get: function () { return this._data[2]; },
  3134. set: function (value) {
  3135. this._data[2] = value;
  3136. }
  3137. });
  3138. SIMDHelper._isEnabled = true;
  3139. };
  3140. SIMDHelper._isEnabled = false;
  3141. return SIMDHelper;
  3142. })();
  3143. BABYLON.SIMDHelper = SIMDHelper;
  3144. })(BABYLON || (BABYLON = {}));
  3145. var BABYLON;
  3146. (function (BABYLON) {
  3147. var Database = (function () {
  3148. function Database(urlToScene, callbackManifestChecked) {
  3149. // Handling various flavors of prefixed version of IndexedDB
  3150. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3151. this.callbackManifestChecked = callbackManifestChecked;
  3152. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3153. this.db = null;
  3154. this.enableSceneOffline = false;
  3155. this.enableTexturesOffline = false;
  3156. this.manifestVersionFound = 0;
  3157. this.mustUpdateRessources = false;
  3158. this.hasReachedQuota = false;
  3159. if (!Database.IDBStorageEnabled) {
  3160. this.callbackManifestChecked(true);
  3161. }
  3162. else {
  3163. this.checkManifestFile();
  3164. }
  3165. }
  3166. Database.prototype.checkManifestFile = function () {
  3167. var _this = this;
  3168. function noManifestFile() {
  3169. that.enableSceneOffline = false;
  3170. that.enableTexturesOffline = false;
  3171. that.callbackManifestChecked(false);
  3172. }
  3173. var that = this;
  3174. var manifestURL = this.currentSceneUrl + ".manifest";
  3175. var xhr = new XMLHttpRequest();
  3176. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3177. xhr.open("GET", manifestURLTimeStamped, true);
  3178. xhr.addEventListener("load", function () {
  3179. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3180. try {
  3181. var manifestFile = JSON.parse(xhr.response);
  3182. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3183. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3184. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3185. _this.manifestVersionFound = manifestFile.version;
  3186. }
  3187. if (_this.callbackManifestChecked) {
  3188. _this.callbackManifestChecked(true);
  3189. }
  3190. }
  3191. catch (ex) {
  3192. noManifestFile();
  3193. }
  3194. }
  3195. else {
  3196. noManifestFile();
  3197. }
  3198. }, false);
  3199. xhr.addEventListener("error", function (event) {
  3200. noManifestFile();
  3201. }, false);
  3202. try {
  3203. xhr.send();
  3204. }
  3205. catch (ex) {
  3206. BABYLON.Tools.Error("Error on XHR send request.");
  3207. that.callbackManifestChecked(false);
  3208. }
  3209. };
  3210. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3211. var _this = this;
  3212. function handleError() {
  3213. that.isSupported = false;
  3214. if (errorCallback)
  3215. errorCallback();
  3216. }
  3217. var that = this;
  3218. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3219. // Your browser doesn't support IndexedDB
  3220. this.isSupported = false;
  3221. if (errorCallback)
  3222. errorCallback();
  3223. }
  3224. else {
  3225. // If the DB hasn't been opened or created yet
  3226. if (!this.db) {
  3227. this.hasReachedQuota = false;
  3228. this.isSupported = true;
  3229. var request = this.idbFactory.open("babylonjs", 1);
  3230. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3231. request.onerror = function (event) {
  3232. handleError();
  3233. };
  3234. // executes when a version change transaction cannot complete due to other active transactions
  3235. request.onblocked = function (event) {
  3236. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3237. handleError();
  3238. };
  3239. // DB has been opened successfully
  3240. request.onsuccess = function (event) {
  3241. _this.db = request.result;
  3242. successCallback();
  3243. };
  3244. // Initialization of the DB. Creating Scenes & Textures stores
  3245. request.onupgradeneeded = function (event) {
  3246. _this.db = (event.target).result;
  3247. try {
  3248. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3249. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3250. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3251. }
  3252. catch (ex) {
  3253. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3254. handleError();
  3255. }
  3256. };
  3257. }
  3258. else {
  3259. if (successCallback)
  3260. successCallback();
  3261. }
  3262. }
  3263. };
  3264. Database.prototype.loadImageFromDB = function (url, image) {
  3265. var _this = this;
  3266. var completeURL = Database.ReturnFullUrlLocation(url);
  3267. var saveAndLoadImage = function () {
  3268. if (!_this.hasReachedQuota && _this.db !== null) {
  3269. // the texture is not yet in the DB, let's try to save it
  3270. _this._saveImageIntoDBAsync(completeURL, image);
  3271. }
  3272. else {
  3273. image.src = url;
  3274. }
  3275. };
  3276. if (!this.mustUpdateRessources) {
  3277. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3278. }
  3279. else {
  3280. saveAndLoadImage();
  3281. }
  3282. };
  3283. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3284. if (this.isSupported && this.db !== null) {
  3285. var texture;
  3286. var transaction = this.db.transaction(["textures"]);
  3287. transaction.onabort = function (event) {
  3288. image.src = url;
  3289. };
  3290. transaction.oncomplete = function (event) {
  3291. var blobTextureURL;
  3292. if (texture) {
  3293. var URL = window.URL || window.webkitURL;
  3294. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3295. image.onerror = function () {
  3296. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3297. image.src = url;
  3298. };
  3299. image.src = blobTextureURL;
  3300. }
  3301. else {
  3302. notInDBCallback();
  3303. }
  3304. };
  3305. var getRequest = transaction.objectStore("textures").get(url);
  3306. getRequest.onsuccess = function (event) {
  3307. texture = (event.target).result;
  3308. };
  3309. getRequest.onerror = function (event) {
  3310. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3311. image.src = url;
  3312. };
  3313. }
  3314. else {
  3315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3316. image.src = url;
  3317. }
  3318. };
  3319. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3320. var _this = this;
  3321. if (this.isSupported) {
  3322. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3323. var generateBlobUrl = function () {
  3324. var blobTextureURL;
  3325. if (blob) {
  3326. var URL = window.URL || window.webkitURL;
  3327. try {
  3328. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3329. }
  3330. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3331. catch (ex) {
  3332. blobTextureURL = URL.createObjectURL(blob);
  3333. }
  3334. }
  3335. image.src = blobTextureURL;
  3336. };
  3337. if (Database.IsUASupportingBlobStorage) {
  3338. var xhr = new XMLHttpRequest(), blob;
  3339. xhr.open("GET", url, true);
  3340. xhr.responseType = "blob";
  3341. xhr.addEventListener("load", function () {
  3342. if (xhr.status === 200) {
  3343. // Blob as response (XHR2)
  3344. blob = xhr.response;
  3345. var transaction = _this.db.transaction(["textures"], "readwrite");
  3346. // the transaction could abort because of a QuotaExceededError error
  3347. transaction.onabort = function (event) {
  3348. try {
  3349. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3350. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3351. this.hasReachedQuota = true;
  3352. }
  3353. }
  3354. catch (ex) { }
  3355. generateBlobUrl();
  3356. };
  3357. transaction.oncomplete = function (event) {
  3358. generateBlobUrl();
  3359. };
  3360. var newTexture = { textureUrl: url, data: blob };
  3361. try {
  3362. // Put the blob into the dabase
  3363. var addRequest = transaction.objectStore("textures").put(newTexture);
  3364. addRequest.onsuccess = function (event) {
  3365. };
  3366. addRequest.onerror = function (event) {
  3367. generateBlobUrl();
  3368. };
  3369. }
  3370. catch (ex) {
  3371. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3372. if (ex.code === 25) {
  3373. Database.IsUASupportingBlobStorage = false;
  3374. }
  3375. image.src = url;
  3376. }
  3377. }
  3378. else {
  3379. image.src = url;
  3380. }
  3381. }, false);
  3382. xhr.addEventListener("error", function (event) {
  3383. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3384. image.src = url;
  3385. }, false);
  3386. xhr.send();
  3387. }
  3388. else {
  3389. image.src = url;
  3390. }
  3391. }
  3392. else {
  3393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3394. image.src = url;
  3395. }
  3396. };
  3397. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3398. var _this = this;
  3399. var updateVersion = function (event) {
  3400. // the version is not yet in the DB or we need to update it
  3401. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3402. };
  3403. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3404. };
  3405. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3406. var _this = this;
  3407. if (this.isSupported) {
  3408. var version;
  3409. try {
  3410. var transaction = this.db.transaction(["versions"]);
  3411. transaction.oncomplete = function (event) {
  3412. if (version) {
  3413. // If the version in the JSON file is > than the version in DB
  3414. if (_this.manifestVersionFound > version.data) {
  3415. _this.mustUpdateRessources = true;
  3416. updateInDBCallback();
  3417. }
  3418. else {
  3419. callback(version.data);
  3420. }
  3421. }
  3422. else {
  3423. _this.mustUpdateRessources = true;
  3424. updateInDBCallback();
  3425. }
  3426. };
  3427. transaction.onabort = function (event) {
  3428. callback(-1);
  3429. };
  3430. var getRequest = transaction.objectStore("versions").get(url);
  3431. getRequest.onsuccess = function (event) {
  3432. version = (event.target).result;
  3433. };
  3434. getRequest.onerror = function (event) {
  3435. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3436. callback(-1);
  3437. };
  3438. }
  3439. catch (ex) {
  3440. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3441. callback(-1);
  3442. }
  3443. }
  3444. else {
  3445. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3446. callback(-1);
  3447. }
  3448. };
  3449. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3450. var _this = this;
  3451. if (this.isSupported && !this.hasReachedQuota) {
  3452. try {
  3453. // Open a transaction to the database
  3454. var transaction = this.db.transaction(["versions"], "readwrite");
  3455. // the transaction could abort because of a QuotaExceededError error
  3456. transaction.onabort = function (event) {
  3457. try {
  3458. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3459. _this.hasReachedQuota = true;
  3460. }
  3461. }
  3462. catch (ex) { }
  3463. callback(-1);
  3464. };
  3465. transaction.oncomplete = function (event) {
  3466. callback(_this.manifestVersionFound);
  3467. };
  3468. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3469. // Put the scene into the database
  3470. var addRequest = transaction.objectStore("versions").put(newVersion);
  3471. addRequest.onsuccess = function (event) {
  3472. };
  3473. addRequest.onerror = function (event) {
  3474. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3475. };
  3476. }
  3477. catch (ex) {
  3478. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3479. callback(-1);
  3480. }
  3481. }
  3482. else {
  3483. callback(-1);
  3484. }
  3485. };
  3486. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3487. var _this = this;
  3488. var completeUrl = Database.ReturnFullUrlLocation(url);
  3489. var saveAndLoadFile = function (event) {
  3490. // the scene is not yet in the DB, let's try to save it
  3491. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3492. };
  3493. this._checkVersionFromDB(completeUrl, function (version) {
  3494. if (version !== -1) {
  3495. if (!_this.mustUpdateRessources) {
  3496. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3497. }
  3498. else {
  3499. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3500. }
  3501. }
  3502. else {
  3503. errorCallback();
  3504. }
  3505. });
  3506. };
  3507. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3508. if (this.isSupported) {
  3509. var targetStore;
  3510. if (url.indexOf(".babylon") !== -1) {
  3511. targetStore = "scenes";
  3512. }
  3513. else {
  3514. targetStore = "textures";
  3515. }
  3516. var file;
  3517. var transaction = this.db.transaction([targetStore]);
  3518. transaction.oncomplete = function (event) {
  3519. if (file) {
  3520. callback(file.data);
  3521. }
  3522. else {
  3523. notInDBCallback();
  3524. }
  3525. };
  3526. transaction.onabort = function (event) {
  3527. notInDBCallback();
  3528. };
  3529. var getRequest = transaction.objectStore(targetStore).get(url);
  3530. getRequest.onsuccess = function (event) {
  3531. file = (event.target).result;
  3532. };
  3533. getRequest.onerror = function (event) {
  3534. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3535. notInDBCallback();
  3536. };
  3537. }
  3538. else {
  3539. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3540. callback();
  3541. }
  3542. };
  3543. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3544. var _this = this;
  3545. if (this.isSupported) {
  3546. var targetStore;
  3547. if (url.indexOf(".babylon") !== -1) {
  3548. targetStore = "scenes";
  3549. }
  3550. else {
  3551. targetStore = "textures";
  3552. }
  3553. // Create XHR
  3554. var xhr = new XMLHttpRequest(), fileData;
  3555. xhr.open("GET", url, true);
  3556. if (useArrayBuffer) {
  3557. xhr.responseType = "arraybuffer";
  3558. }
  3559. xhr.onprogress = progressCallback;
  3560. xhr.addEventListener("load", function () {
  3561. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3562. // Blob as response (XHR2)
  3563. //fileData = xhr.responseText;
  3564. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3565. if (!_this.hasReachedQuota) {
  3566. // Open a transaction to the database
  3567. var transaction = _this.db.transaction([targetStore], "readwrite");
  3568. // the transaction could abort because of a QuotaExceededError error
  3569. transaction.onabort = function (event) {
  3570. try {
  3571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3572. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3573. this.hasReachedQuota = true;
  3574. }
  3575. }
  3576. catch (ex) { }
  3577. callback(fileData);
  3578. };
  3579. transaction.oncomplete = function (event) {
  3580. callback(fileData);
  3581. };
  3582. var newFile;
  3583. if (targetStore === "scenes") {
  3584. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3585. }
  3586. else {
  3587. newFile = { textureUrl: url, data: fileData };
  3588. }
  3589. try {
  3590. // Put the scene into the database
  3591. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3592. addRequest.onsuccess = function (event) {
  3593. };
  3594. addRequest.onerror = function (event) {
  3595. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3596. };
  3597. }
  3598. catch (ex) {
  3599. callback(fileData);
  3600. }
  3601. }
  3602. else {
  3603. callback(fileData);
  3604. }
  3605. }
  3606. else {
  3607. callback();
  3608. }
  3609. }, false);
  3610. xhr.addEventListener("error", function (event) {
  3611. BABYLON.Tools.Error("error on XHR request.");
  3612. callback();
  3613. }, false);
  3614. xhr.send();
  3615. }
  3616. else {
  3617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3618. callback();
  3619. }
  3620. };
  3621. Database.IsUASupportingBlobStorage = true;
  3622. Database.IDBStorageEnabled = true;
  3623. Database.parseURL = function (url) {
  3624. var a = document.createElement('a');
  3625. a.href = url;
  3626. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3627. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3628. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3629. return absLocation;
  3630. };
  3631. Database.ReturnFullUrlLocation = function (url) {
  3632. if (url.indexOf("http:/") === -1) {
  3633. return (Database.parseURL(window.location.href) + url);
  3634. }
  3635. else {
  3636. return url;
  3637. }
  3638. };
  3639. return Database;
  3640. })();
  3641. BABYLON.Database = Database;
  3642. })(BABYLON || (BABYLON = {}));
  3643. var BABYLON;
  3644. (function (BABYLON) {
  3645. var Internals;
  3646. (function (Internals) {
  3647. /*
  3648. * Based on jsTGALoader - Javascript loader for TGA file
  3649. * By Vincent Thibault
  3650. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3651. */
  3652. var TGATools = (function () {
  3653. function TGATools() {
  3654. }
  3655. TGATools.GetTGAHeader = function (data) {
  3656. var offset = 0;
  3657. var header = {
  3658. id_length: data[offset++],
  3659. colormap_type: data[offset++],
  3660. image_type: data[offset++],
  3661. colormap_index: data[offset++] | data[offset++] << 8,
  3662. colormap_length: data[offset++] | data[offset++] << 8,
  3663. colormap_size: data[offset++],
  3664. origin: [
  3665. data[offset++] | data[offset++] << 8,
  3666. data[offset++] | data[offset++] << 8
  3667. ],
  3668. width: data[offset++] | data[offset++] << 8,
  3669. height: data[offset++] | data[offset++] << 8,
  3670. pixel_size: data[offset++],
  3671. flags: data[offset++]
  3672. };
  3673. return header;
  3674. };
  3675. TGATools.UploadContent = function (gl, data) {
  3676. // Not enough data to contain header ?
  3677. if (data.length < 19) {
  3678. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3679. return;
  3680. }
  3681. // Read Header
  3682. var offset = 18;
  3683. var header = TGATools.GetTGAHeader(data);
  3684. // Assume it's a valid Targa file.
  3685. if (header.id_length + offset > data.length) {
  3686. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3687. return;
  3688. }
  3689. // Skip not needed data
  3690. offset += header.id_length;
  3691. var use_rle = false;
  3692. var use_pal = false;
  3693. var use_rgb = false;
  3694. var use_grey = false;
  3695. // Get some informations.
  3696. switch (header.image_type) {
  3697. case TGATools._TYPE_RLE_INDEXED:
  3698. use_rle = true;
  3699. case TGATools._TYPE_INDEXED:
  3700. use_pal = true;
  3701. break;
  3702. case TGATools._TYPE_RLE_RGB:
  3703. use_rle = true;
  3704. case TGATools._TYPE_RGB:
  3705. use_rgb = true;
  3706. break;
  3707. case TGATools._TYPE_RLE_GREY:
  3708. use_rle = true;
  3709. case TGATools._TYPE_GREY:
  3710. use_grey = true;
  3711. break;
  3712. }
  3713. var pixel_data;
  3714. var numAlphaBits = header.flags & 0xf;
  3715. var pixel_size = header.pixel_size >> 3;
  3716. var pixel_total = header.width * header.height * pixel_size;
  3717. // Read palettes
  3718. var palettes;
  3719. if (use_pal) {
  3720. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3721. }
  3722. // Read LRE
  3723. if (use_rle) {
  3724. pixel_data = new Uint8Array(pixel_total);
  3725. var c, count, i;
  3726. var localOffset = 0;
  3727. var pixels = new Uint8Array(pixel_size);
  3728. while (offset < pixel_total && localOffset < pixel_total) {
  3729. c = data[offset++];
  3730. count = (c & 0x7f) + 1;
  3731. // RLE pixels
  3732. if (c & 0x80) {
  3733. // Bind pixel tmp array
  3734. for (i = 0; i < pixel_size; ++i) {
  3735. pixels[i] = data[offset++];
  3736. }
  3737. // Copy pixel array
  3738. for (i = 0; i < count; ++i) {
  3739. pixel_data.set(pixels, localOffset + i * pixel_size);
  3740. }
  3741. localOffset += pixel_size * count;
  3742. }
  3743. else {
  3744. count *= pixel_size;
  3745. for (i = 0; i < count; ++i) {
  3746. pixel_data[localOffset + i] = data[offset++];
  3747. }
  3748. localOffset += count;
  3749. }
  3750. }
  3751. }
  3752. else {
  3753. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3754. }
  3755. // Load to texture
  3756. var x_start, y_start, x_step, y_step, y_end, x_end;
  3757. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3758. default:
  3759. case TGATools._ORIGIN_UL:
  3760. x_start = 0;
  3761. x_step = 1;
  3762. x_end = header.width;
  3763. y_start = 0;
  3764. y_step = 1;
  3765. y_end = header.height;
  3766. break;
  3767. case TGATools._ORIGIN_BL:
  3768. x_start = 0;
  3769. x_step = 1;
  3770. x_end = header.width;
  3771. y_start = header.height - 1;
  3772. y_step = -1;
  3773. y_end = -1;
  3774. break;
  3775. case TGATools._ORIGIN_UR:
  3776. x_start = header.width - 1;
  3777. x_step = -1;
  3778. x_end = -1;
  3779. y_start = 0;
  3780. y_step = 1;
  3781. y_end = header.height;
  3782. break;
  3783. case TGATools._ORIGIN_BR:
  3784. x_start = header.width - 1;
  3785. x_step = -1;
  3786. x_end = -1;
  3787. y_start = header.height - 1;
  3788. y_step = -1;
  3789. y_end = -1;
  3790. break;
  3791. }
  3792. // Load the specify method
  3793. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3794. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3795. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3796. };
  3797. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3798. var image = pixel_data, colormap = palettes;
  3799. var width = header.width, height = header.height;
  3800. var color, i = 0, x, y;
  3801. var imageData = new Uint8Array(width * height * 4);
  3802. for (y = y_start; y !== y_end; y += y_step) {
  3803. for (x = x_start; x !== x_end; x += x_step, i++) {
  3804. color = image[i];
  3805. imageData[(x + width * y) * 4 + 3] = 255;
  3806. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3807. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3808. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3809. }
  3810. }
  3811. return imageData;
  3812. };
  3813. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3814. var image = pixel_data;
  3815. var width = header.width, height = header.height;
  3816. var color, i = 0, x, y;
  3817. var imageData = new Uint8Array(width * height * 4);
  3818. for (y = y_start; y !== y_end; y += y_step) {
  3819. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3820. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3821. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3822. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3823. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3824. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3825. }
  3826. }
  3827. return imageData;
  3828. };
  3829. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3830. var image = pixel_data;
  3831. var width = header.width, height = header.height;
  3832. var i = 0, x, y;
  3833. var imageData = new Uint8Array(width * height * 4);
  3834. for (y = y_start; y !== y_end; y += y_step) {
  3835. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3836. imageData[(x + width * y) * 4 + 3] = 255;
  3837. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3838. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3839. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3840. }
  3841. }
  3842. return imageData;
  3843. };
  3844. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3845. var image = pixel_data;
  3846. var width = header.width, height = header.height;
  3847. var i = 0, x, y;
  3848. var imageData = new Uint8Array(width * height * 4);
  3849. for (y = y_start; y !== y_end; y += y_step) {
  3850. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3851. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3852. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3853. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3854. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3855. }
  3856. }
  3857. return imageData;
  3858. };
  3859. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3860. var image = pixel_data;
  3861. var width = header.width, height = header.height;
  3862. var color, i = 0, x, y;
  3863. var imageData = new Uint8Array(width * height * 4);
  3864. for (y = y_start; y !== y_end; y += y_step) {
  3865. for (x = x_start; x !== x_end; x += x_step, i++) {
  3866. color = image[i];
  3867. imageData[(x + width * y) * 4 + 0] = color;
  3868. imageData[(x + width * y) * 4 + 1] = color;
  3869. imageData[(x + width * y) * 4 + 2] = color;
  3870. imageData[(x + width * y) * 4 + 3] = 255;
  3871. }
  3872. }
  3873. return imageData;
  3874. };
  3875. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3876. var image = pixel_data;
  3877. var width = header.width, height = header.height;
  3878. var i = 0, x, y;
  3879. var imageData = new Uint8Array(width * height * 4);
  3880. for (y = y_start; y !== y_end; y += y_step) {
  3881. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3882. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3883. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3884. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3885. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3886. }
  3887. }
  3888. return imageData;
  3889. };
  3890. TGATools._TYPE_NO_DATA = 0;
  3891. TGATools._TYPE_INDEXED = 1;
  3892. TGATools._TYPE_RGB = 2;
  3893. TGATools._TYPE_GREY = 3;
  3894. TGATools._TYPE_RLE_INDEXED = 9;
  3895. TGATools._TYPE_RLE_RGB = 10;
  3896. TGATools._TYPE_RLE_GREY = 11;
  3897. TGATools._ORIGIN_MASK = 0x30;
  3898. TGATools._ORIGIN_SHIFT = 0x04;
  3899. TGATools._ORIGIN_BL = 0x00;
  3900. TGATools._ORIGIN_BR = 0x01;
  3901. TGATools._ORIGIN_UL = 0x02;
  3902. TGATools._ORIGIN_UR = 0x03;
  3903. return TGATools;
  3904. })();
  3905. Internals.TGATools = TGATools;
  3906. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3907. })(BABYLON || (BABYLON = {}));
  3908. var BABYLON;
  3909. (function (BABYLON) {
  3910. var Internals;
  3911. (function (Internals) {
  3912. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3913. // All values and structures referenced from:
  3914. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3915. var DDS_MAGIC = 0x20534444;
  3916. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  3917. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3918. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  3919. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3920. function FourCCToInt32(value) {
  3921. return value.charCodeAt(0) +
  3922. (value.charCodeAt(1) << 8) +
  3923. (value.charCodeAt(2) << 16) +
  3924. (value.charCodeAt(3) << 24);
  3925. }
  3926. function Int32ToFourCC(value) {
  3927. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3928. }
  3929. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3930. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3931. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3932. var headerLengthInt = 31; // The header length in 32 bit ints
  3933. // Offsets into the header array
  3934. var off_magic = 0;
  3935. var off_size = 1;
  3936. var off_flags = 2;
  3937. var off_height = 3;
  3938. var off_width = 4;
  3939. var off_mipmapCount = 7;
  3940. var off_pfFlags = 20;
  3941. var off_pfFourCC = 21;
  3942. var off_RGBbpp = 22;
  3943. var off_RMask = 23;
  3944. var off_GMask = 24;
  3945. var off_BMask = 25;
  3946. var off_AMask = 26;
  3947. var off_caps1 = 27;
  3948. var off_caps2 = 28;
  3949. ;
  3950. var DDSTools = (function () {
  3951. function DDSTools() {
  3952. }
  3953. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3954. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3955. var mipmapCount = 1;
  3956. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3957. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3958. }
  3959. return {
  3960. width: header[off_width],
  3961. height: header[off_height],
  3962. mipmapCount: mipmapCount,
  3963. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3964. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3965. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3966. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3967. };
  3968. };
  3969. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3970. var byteArray = new Uint8Array(dataLength);
  3971. var srcData = new Uint8Array(arrayBuffer);
  3972. var index = 0;
  3973. for (var y = height - 1; y >= 0; y--) {
  3974. for (var x = 0; x < width; x++) {
  3975. var srcPos = dataOffset + (x + y * width) * 4;
  3976. byteArray[index + 2] = srcData[srcPos];
  3977. byteArray[index + 1] = srcData[srcPos + 1];
  3978. byteArray[index] = srcData[srcPos + 2];
  3979. byteArray[index + 3] = srcData[srcPos + 3];
  3980. index += 4;
  3981. }
  3982. }
  3983. return byteArray;
  3984. };
  3985. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3986. var byteArray = new Uint8Array(dataLength);
  3987. var srcData = new Uint8Array(arrayBuffer);
  3988. var index = 0;
  3989. for (var y = height - 1; y >= 0; y--) {
  3990. for (var x = 0; x < width; x++) {
  3991. var srcPos = dataOffset + (x + y * width) * 3;
  3992. byteArray[index + 2] = srcData[srcPos];
  3993. byteArray[index + 1] = srcData[srcPos + 1];
  3994. byteArray[index] = srcData[srcPos + 2];
  3995. index += 3;
  3996. }
  3997. }
  3998. return byteArray;
  3999. };
  4000. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  4001. var byteArray = new Uint8Array(dataLength);
  4002. var srcData = new Uint8Array(arrayBuffer);
  4003. var index = 0;
  4004. for (var y = height - 1; y >= 0; y--) {
  4005. for (var x = 0; x < width; x++) {
  4006. var srcPos = dataOffset + (x + y * width);
  4007. byteArray[index] = srcData[srcPos];
  4008. index++;
  4009. }
  4010. }
  4011. return byteArray;
  4012. };
  4013. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4014. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4015. if (header[off_magic] != DDS_MAGIC) {
  4016. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4017. return;
  4018. }
  4019. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4020. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4021. return;
  4022. }
  4023. if (info.isFourCC) {
  4024. fourCC = header[off_pfFourCC];
  4025. switch (fourCC) {
  4026. case FOURCC_DXT1:
  4027. blockBytes = 8;
  4028. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4029. break;
  4030. case FOURCC_DXT3:
  4031. blockBytes = 16;
  4032. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4033. break;
  4034. case FOURCC_DXT5:
  4035. blockBytes = 16;
  4036. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4037. break;
  4038. default:
  4039. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4040. return;
  4041. }
  4042. }
  4043. mipmapCount = 1;
  4044. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4045. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4046. }
  4047. var bpp = header[off_RGBbpp];
  4048. for (var face = 0; face < faces; face++) {
  4049. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4050. width = header[off_width];
  4051. height = header[off_height];
  4052. dataOffset = header[off_size] + 4;
  4053. for (i = 0; i < mipmapCount; ++i) {
  4054. if (info.isRGB) {
  4055. if (bpp == 24) {
  4056. dataLength = width * height * 3;
  4057. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4058. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4059. }
  4060. else {
  4061. dataLength = width * height * 4;
  4062. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4063. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4064. }
  4065. }
  4066. else if (info.isLuminance) {
  4067. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4068. var unpaddedRowSize = width;
  4069. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4070. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4071. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4072. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4073. }
  4074. else {
  4075. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4076. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4077. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4078. }
  4079. dataOffset += dataLength;
  4080. width *= 0.5;
  4081. height *= 0.5;
  4082. width = Math.max(1.0, width);
  4083. height = Math.max(1.0, height);
  4084. }
  4085. }
  4086. };
  4087. return DDSTools;
  4088. })();
  4089. Internals.DDSTools = DDSTools;
  4090. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4091. })(BABYLON || (BABYLON = {}));
  4092. var BABYLON;
  4093. (function (BABYLON) {
  4094. var SmartArray = (function () {
  4095. function SmartArray(capacity) {
  4096. this.length = 0;
  4097. this._duplicateId = 0;
  4098. this.data = new Array(capacity);
  4099. this._id = SmartArray._GlobalId++;
  4100. }
  4101. SmartArray.prototype.push = function (value) {
  4102. this.data[this.length++] = value;
  4103. if (this.length > this.data.length) {
  4104. this.data.length *= 2;
  4105. }
  4106. if (!value.__smartArrayFlags) {
  4107. value.__smartArrayFlags = {};
  4108. }
  4109. value.__smartArrayFlags[this._id] = this._duplicateId;
  4110. };
  4111. SmartArray.prototype.pushNoDuplicate = function (value) {
  4112. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4113. return;
  4114. }
  4115. this.push(value);
  4116. };
  4117. SmartArray.prototype.sort = function (compareFn) {
  4118. this.data.sort(compareFn);
  4119. };
  4120. SmartArray.prototype.reset = function () {
  4121. this.length = 0;
  4122. this._duplicateId++;
  4123. };
  4124. SmartArray.prototype.concat = function (array) {
  4125. if (array.length === 0) {
  4126. return;
  4127. }
  4128. if (this.length + array.length > this.data.length) {
  4129. this.data.length = (this.length + array.length) * 2;
  4130. }
  4131. for (var index = 0; index < array.length; index++) {
  4132. this.data[this.length++] = (array.data || array)[index];
  4133. }
  4134. };
  4135. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4136. if (array.length === 0) {
  4137. return;
  4138. }
  4139. if (this.length + array.length > this.data.length) {
  4140. this.data.length = (this.length + array.length) * 2;
  4141. }
  4142. for (var index = 0; index < array.length; index++) {
  4143. var item = (array.data || array)[index];
  4144. this.pushNoDuplicate(item);
  4145. }
  4146. };
  4147. SmartArray.prototype.indexOf = function (value) {
  4148. var position = this.data.indexOf(value);
  4149. if (position >= this.length) {
  4150. return -1;
  4151. }
  4152. return position;
  4153. };
  4154. // Statics
  4155. SmartArray._GlobalId = 0;
  4156. return SmartArray;
  4157. })();
  4158. BABYLON.SmartArray = SmartArray;
  4159. })(BABYLON || (BABYLON = {}));
  4160. var BABYLON;
  4161. (function (BABYLON) {
  4162. var SmartCollection = (function () {
  4163. function SmartCollection(capacity) {
  4164. if (capacity === void 0) { capacity = 10; }
  4165. this.count = 0;
  4166. this._initialCapacity = capacity;
  4167. this.items = {};
  4168. this._keys = new Array(this._initialCapacity);
  4169. }
  4170. SmartCollection.prototype.add = function (key, item) {
  4171. if (this.items[key] != undefined) {
  4172. return -1;
  4173. }
  4174. this.items[key] = item;
  4175. //literal keys are always strings, but we keep source type of key in _keys array
  4176. this._keys[this.count++] = key;
  4177. if (this.count > this._keys.length) {
  4178. this._keys.length *= 2;
  4179. }
  4180. return this.count;
  4181. };
  4182. SmartCollection.prototype.remove = function (key) {
  4183. if (this.items[key] == undefined) {
  4184. return -1;
  4185. }
  4186. return this.removeItemOfIndex(this.indexOf(key));
  4187. };
  4188. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4189. if (index < this.count && index > -1) {
  4190. delete this.items[this._keys[index]];
  4191. //here, shifting by hand is better optimised than .splice
  4192. while (index < this.count) {
  4193. this._keys[index] = this._keys[index + 1];
  4194. index++;
  4195. }
  4196. }
  4197. else {
  4198. return -1;
  4199. }
  4200. return --this.count;
  4201. };
  4202. SmartCollection.prototype.indexOf = function (key) {
  4203. for (var i = 0; i !== this.count; i++) {
  4204. if (this._keys[i] === key) {
  4205. return i;
  4206. }
  4207. }
  4208. return -1;
  4209. };
  4210. SmartCollection.prototype.item = function (key) {
  4211. return this.items[key];
  4212. };
  4213. SmartCollection.prototype.getAllKeys = function () {
  4214. if (this.count > 0) {
  4215. var keys = new Array(this.count);
  4216. for (var i = 0; i < this.count; i++) {
  4217. keys[i] = this._keys[i];
  4218. }
  4219. return keys;
  4220. }
  4221. else {
  4222. return undefined;
  4223. }
  4224. };
  4225. SmartCollection.prototype.getKeyByIndex = function (index) {
  4226. if (index < this.count && index > -1) {
  4227. return this._keys[index];
  4228. }
  4229. else {
  4230. return undefined;
  4231. }
  4232. };
  4233. SmartCollection.prototype.getItemByIndex = function (index) {
  4234. if (index < this.count && index > -1) {
  4235. return this.items[this._keys[index]];
  4236. }
  4237. else {
  4238. return undefined;
  4239. }
  4240. };
  4241. SmartCollection.prototype.empty = function () {
  4242. if (this.count > 0) {
  4243. this.count = 0;
  4244. this.items = {};
  4245. this._keys = new Array(this._initialCapacity);
  4246. }
  4247. };
  4248. SmartCollection.prototype.forEach = function (block) {
  4249. var key;
  4250. for (key in this.items) {
  4251. if (this.items.hasOwnProperty(key)) {
  4252. block(this.items[key]);
  4253. }
  4254. }
  4255. };
  4256. return SmartCollection;
  4257. })();
  4258. BABYLON.SmartCollection = SmartCollection;
  4259. })(BABYLON || (BABYLON = {}));
  4260. var BABYLON;
  4261. (function (BABYLON) {
  4262. // Screenshots
  4263. var screenshotCanvas;
  4264. var cloneValue = function (source, destinationObject) {
  4265. if (!source)
  4266. return null;
  4267. if (source instanceof BABYLON.Mesh) {
  4268. return null;
  4269. }
  4270. if (source instanceof BABYLON.SubMesh) {
  4271. return source.clone(destinationObject);
  4272. }
  4273. else if (source.clone) {
  4274. return source.clone();
  4275. }
  4276. return null;
  4277. };
  4278. var Tools = (function () {
  4279. function Tools() {
  4280. }
  4281. Tools.ToHex = function (i) {
  4282. var str = i.toString(16);
  4283. if (i <= 15) {
  4284. return ("0" + str).toUpperCase();
  4285. }
  4286. return str.toUpperCase();
  4287. };
  4288. Tools.SetImmediate = function (action) {
  4289. if (window.setImmediate) {
  4290. window.setImmediate(action);
  4291. }
  4292. else {
  4293. setTimeout(action, 1);
  4294. }
  4295. };
  4296. Tools.IsExponantOfTwo = function (value) {
  4297. var count = 1;
  4298. do {
  4299. count *= 2;
  4300. } while (count < value);
  4301. return count === value;
  4302. };
  4303. Tools.GetExponantOfTwo = function (value, max) {
  4304. var count = 1;
  4305. do {
  4306. count *= 2;
  4307. } while (count < value);
  4308. if (count > max)
  4309. count = max;
  4310. return count;
  4311. };
  4312. Tools.GetFilename = function (path) {
  4313. var index = path.lastIndexOf("/");
  4314. if (index < 0)
  4315. return path;
  4316. return path.substring(index + 1);
  4317. };
  4318. Tools.GetDOMTextContent = function (element) {
  4319. var result = "";
  4320. var child = element.firstChild;
  4321. while (child) {
  4322. if (child.nodeType === 3) {
  4323. result += child.textContent;
  4324. }
  4325. child = child.nextSibling;
  4326. }
  4327. return result;
  4328. };
  4329. Tools.ToDegrees = function (angle) {
  4330. return angle * 180 / Math.PI;
  4331. };
  4332. Tools.ToRadians = function (angle) {
  4333. return angle * Math.PI / 180;
  4334. };
  4335. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4336. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4337. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4338. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4339. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4340. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4341. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4342. }
  4343. return {
  4344. minimum: minimum,
  4345. maximum: maximum
  4346. };
  4347. };
  4348. Tools.ExtractMinAndMax = function (positions, start, count) {
  4349. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4350. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4351. for (var index = start; index < start + count; index++) {
  4352. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4353. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4354. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4355. }
  4356. return {
  4357. minimum: minimum,
  4358. maximum: maximum
  4359. };
  4360. };
  4361. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4362. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4363. return undefined;
  4364. return Array.isArray(obj) ? obj : [obj];
  4365. };
  4366. // Misc.
  4367. Tools.GetPointerPrefix = function () {
  4368. var eventPrefix = "pointer";
  4369. // Check if hand.js is referenced or if the browser natively supports pointer events
  4370. if (!navigator.pointerEnabled) {
  4371. eventPrefix = "mouse";
  4372. }
  4373. return eventPrefix;
  4374. };
  4375. Tools.QueueNewFrame = function (func) {
  4376. if (window.requestAnimationFrame)
  4377. window.requestAnimationFrame(func);
  4378. else if (window.msRequestAnimationFrame)
  4379. window.msRequestAnimationFrame(func);
  4380. else if (window.webkitRequestAnimationFrame)
  4381. window.webkitRequestAnimationFrame(func);
  4382. else if (window.mozRequestAnimationFrame)
  4383. window.mozRequestAnimationFrame(func);
  4384. else if (window.oRequestAnimationFrame)
  4385. window.oRequestAnimationFrame(func);
  4386. else {
  4387. window.setTimeout(func, 16);
  4388. }
  4389. };
  4390. Tools.RequestFullscreen = function (element) {
  4391. if (element.requestFullscreen)
  4392. element.requestFullscreen();
  4393. else if (element.msRequestFullscreen)
  4394. element.msRequestFullscreen();
  4395. else if (element.webkitRequestFullscreen)
  4396. element.webkitRequestFullscreen();
  4397. else if (element.mozRequestFullScreen)
  4398. element.mozRequestFullScreen();
  4399. };
  4400. Tools.ExitFullscreen = function () {
  4401. if (document.exitFullscreen) {
  4402. document.exitFullscreen();
  4403. }
  4404. else if (document.mozCancelFullScreen) {
  4405. document.mozCancelFullScreen();
  4406. }
  4407. else if (document.webkitCancelFullScreen) {
  4408. document.webkitCancelFullScreen();
  4409. }
  4410. else if (document.msCancelFullScreen) {
  4411. document.msCancelFullScreen();
  4412. }
  4413. };
  4414. // External files
  4415. Tools.CleanUrl = function (url) {
  4416. url = url.replace(/#/mg, "%23");
  4417. return url;
  4418. };
  4419. Tools.LoadImage = function (url, onload, onerror, database) {
  4420. url = Tools.CleanUrl(url);
  4421. var img = new Image();
  4422. if (url.substr(0, 5) !== "data:")
  4423. img.crossOrigin = 'anonymous';
  4424. img.onload = function () {
  4425. onload(img);
  4426. };
  4427. img.onerror = function (err) {
  4428. Tools.Error("Error while trying to load texture: " + url);
  4429. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4430. onload(img);
  4431. };
  4432. var noIndexedDB = function () {
  4433. img.src = url;
  4434. };
  4435. var loadFromIndexedDB = function () {
  4436. database.loadImageFromDB(url, img);
  4437. };
  4438. //ANY database to do!
  4439. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4440. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4441. }
  4442. else {
  4443. if (url.indexOf("file:") === -1) {
  4444. noIndexedDB();
  4445. }
  4446. else {
  4447. try {
  4448. var textureName = url.substring(5);
  4449. var blobURL;
  4450. try {
  4451. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4452. }
  4453. catch (ex) {
  4454. // Chrome doesn't support oneTimeOnly parameter
  4455. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4456. }
  4457. img.src = blobURL;
  4458. }
  4459. catch (e) {
  4460. img.src = null;
  4461. }
  4462. }
  4463. }
  4464. return img;
  4465. };
  4466. //ANY
  4467. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4468. url = Tools.CleanUrl(url);
  4469. var noIndexedDB = function () {
  4470. var request = new XMLHttpRequest();
  4471. var loadUrl = Tools.BaseUrl + url;
  4472. request.open('GET', loadUrl, true);
  4473. if (useArrayBuffer) {
  4474. request.responseType = "arraybuffer";
  4475. }
  4476. request.onprogress = progressCallBack;
  4477. request.onreadystatechange = function () {
  4478. if (request.readyState === 4) {
  4479. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4480. callback(!useArrayBuffer ? request.responseText : request.response);
  4481. }
  4482. else {
  4483. if (onError) {
  4484. onError();
  4485. }
  4486. else {
  4487. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4488. }
  4489. }
  4490. }
  4491. };
  4492. request.send(null);
  4493. };
  4494. var loadFromIndexedDB = function () {
  4495. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4496. };
  4497. if (url.indexOf("file:") !== -1) {
  4498. var fileName = url.substring(5);
  4499. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4500. }
  4501. else {
  4502. // Caching all files
  4503. if (database && database.enableSceneOffline) {
  4504. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4505. }
  4506. else {
  4507. noIndexedDB();
  4508. }
  4509. }
  4510. };
  4511. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4512. var reader = new FileReader();
  4513. reader.onload = function (e) {
  4514. //target doesn't have result from ts 1.3
  4515. callback(e.target['result']);
  4516. };
  4517. reader.onprogress = progressCallback;
  4518. reader.readAsDataURL(fileToLoad);
  4519. };
  4520. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4521. var reader = new FileReader();
  4522. reader.onerror = function (e) {
  4523. Tools.Log("Error while reading file: " + fileToLoad.name);
  4524. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4525. };
  4526. reader.onload = function (e) {
  4527. //target doesn't have result from ts 1.3
  4528. callback(e.target['result']);
  4529. };
  4530. reader.onprogress = progressCallBack;
  4531. if (!useArrayBuffer) {
  4532. // Asynchronous read
  4533. reader.readAsText(fileToLoad);
  4534. }
  4535. else {
  4536. reader.readAsArrayBuffer(fileToLoad);
  4537. }
  4538. };
  4539. // Misc.
  4540. Tools.Clamp = function (value, min, max) {
  4541. if (min === void 0) { min = 0; }
  4542. if (max === void 0) { max = 1; }
  4543. return Math.min(max, Math.max(min, value));
  4544. };
  4545. // Returns -1 when value is a negative number and
  4546. // +1 when value is a positive number.
  4547. Tools.Sign = function (value) {
  4548. value = +value; // convert to a number
  4549. if (value === 0 || isNaN(value))
  4550. return value;
  4551. return value > 0 ? 1 : -1;
  4552. };
  4553. Tools.Format = function (value, decimals) {
  4554. if (decimals === void 0) { decimals = 2; }
  4555. return value.toFixed(decimals);
  4556. };
  4557. Tools.CheckExtends = function (v, min, max) {
  4558. if (v.x < min.x)
  4559. min.x = v.x;
  4560. if (v.y < min.y)
  4561. min.y = v.y;
  4562. if (v.z < min.z)
  4563. min.z = v.z;
  4564. if (v.x > max.x)
  4565. max.x = v.x;
  4566. if (v.y > max.y)
  4567. max.y = v.y;
  4568. if (v.z > max.z)
  4569. max.z = v.z;
  4570. };
  4571. Tools.WithinEpsilon = function (a, b, epsilon) {
  4572. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4573. var num = a - b;
  4574. return -epsilon <= num && num <= epsilon;
  4575. };
  4576. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4577. for (var prop in source) {
  4578. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4579. continue;
  4580. }
  4581. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4582. continue;
  4583. }
  4584. var sourceValue = source[prop];
  4585. var typeOfSourceValue = typeof sourceValue;
  4586. if (typeOfSourceValue === "function") {
  4587. continue;
  4588. }
  4589. if (typeOfSourceValue === "object") {
  4590. if (sourceValue instanceof Array) {
  4591. destination[prop] = [];
  4592. if (sourceValue.length > 0) {
  4593. if (typeof sourceValue[0] == "object") {
  4594. for (var index = 0; index < sourceValue.length; index++) {
  4595. var clonedValue = cloneValue(sourceValue[index], destination);
  4596. if (destination[prop].indexOf(clonedValue) === -1) {
  4597. destination[prop].push(clonedValue);
  4598. }
  4599. }
  4600. }
  4601. else {
  4602. destination[prop] = sourceValue.slice(0);
  4603. }
  4604. }
  4605. }
  4606. else {
  4607. destination[prop] = cloneValue(sourceValue, destination);
  4608. }
  4609. }
  4610. else {
  4611. destination[prop] = sourceValue;
  4612. }
  4613. }
  4614. };
  4615. Tools.IsEmpty = function (obj) {
  4616. for (var i in obj) {
  4617. return false;
  4618. }
  4619. return true;
  4620. };
  4621. Tools.RegisterTopRootEvents = function (events) {
  4622. for (var index = 0; index < events.length; index++) {
  4623. var event = events[index];
  4624. window.addEventListener(event.name, event.handler, false);
  4625. try {
  4626. if (window.parent) {
  4627. window.parent.addEventListener(event.name, event.handler, false);
  4628. }
  4629. }
  4630. catch (e) {
  4631. }
  4632. }
  4633. };
  4634. Tools.UnregisterTopRootEvents = function (events) {
  4635. for (var index = 0; index < events.length; index++) {
  4636. var event = events[index];
  4637. window.removeEventListener(event.name, event.handler);
  4638. try {
  4639. if (window.parent) {
  4640. window.parent.removeEventListener(event.name, event.handler);
  4641. }
  4642. }
  4643. catch (e) {
  4644. }
  4645. }
  4646. };
  4647. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4648. // Read the contents of the framebuffer
  4649. var numberOfChannelsByLine = width * 4;
  4650. var halfHeight = height / 2;
  4651. //Reading datas from WebGL
  4652. var data = engine.readPixels(0, 0, width, height);
  4653. //To flip image on Y axis.
  4654. for (var i = 0; i < halfHeight; i++) {
  4655. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4656. var currentCell = j + i * numberOfChannelsByLine;
  4657. var targetLine = height - i - 1;
  4658. var targetCell = j + targetLine * numberOfChannelsByLine;
  4659. var temp = data[currentCell];
  4660. data[currentCell] = data[targetCell];
  4661. data[targetCell] = temp;
  4662. }
  4663. }
  4664. // Create a 2D canvas to store the result
  4665. if (!screenshotCanvas) {
  4666. screenshotCanvas = document.createElement('canvas');
  4667. }
  4668. screenshotCanvas.width = width;
  4669. screenshotCanvas.height = height;
  4670. var context = screenshotCanvas.getContext('2d');
  4671. // Copy the pixels to a 2D canvas
  4672. var imageData = context.createImageData(width, height);
  4673. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4674. var castData = imageData.data;
  4675. castData.set(data);
  4676. context.putImageData(imageData, 0, 0);
  4677. var base64Image = screenshotCanvas.toDataURL();
  4678. if (successCallback) {
  4679. successCallback(base64Image);
  4680. }
  4681. else {
  4682. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4683. if (("download" in document.createElement("a"))) {
  4684. var a = window.document.createElement("a");
  4685. a.href = base64Image;
  4686. var date = new Date();
  4687. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4688. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4689. window.document.body.appendChild(a);
  4690. a.addEventListener("click", function () {
  4691. a.parentElement.removeChild(a);
  4692. });
  4693. a.click();
  4694. }
  4695. else {
  4696. var newWindow = window.open("");
  4697. var img = newWindow.document.createElement("img");
  4698. img.src = base64Image;
  4699. newWindow.document.body.appendChild(img);
  4700. }
  4701. }
  4702. };
  4703. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4704. var width;
  4705. var height;
  4706. //If a precision value is specified
  4707. if (size.precision) {
  4708. width = Math.round(engine.getRenderWidth() * size.precision);
  4709. height = Math.round(width / engine.getAspectRatio(camera));
  4710. size = { width: width, height: height };
  4711. }
  4712. else if (size.width && size.height) {
  4713. width = size.width;
  4714. height = size.height;
  4715. }
  4716. else if (size.width && !size.height) {
  4717. width = size.width;
  4718. height = Math.round(width / engine.getAspectRatio(camera));
  4719. size = { width: width, height: height };
  4720. }
  4721. else if (size.height && !size.width) {
  4722. height = size.height;
  4723. width = Math.round(height * engine.getAspectRatio(camera));
  4724. size = { width: width, height: height };
  4725. }
  4726. else if (!isNaN(size)) {
  4727. height = size;
  4728. width = size;
  4729. }
  4730. else {
  4731. Tools.Error("Invalid 'size' parameter !");
  4732. return;
  4733. }
  4734. var scene = camera.getScene();
  4735. var previousCamera = null;
  4736. if (scene.activeCamera !== camera) {
  4737. previousCamera = scene.activeCamera;
  4738. scene.activeCamera = camera;
  4739. }
  4740. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4741. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4742. texture.renderList = scene.meshes;
  4743. texture.onAfterRender = function () {
  4744. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4745. };
  4746. scene.incrementRenderId();
  4747. texture.render(true);
  4748. texture.dispose();
  4749. if (previousCamera) {
  4750. scene.activeCamera = previousCamera;
  4751. }
  4752. };
  4753. // XHR response validator for local file scenario
  4754. Tools.ValidateXHRData = function (xhr, dataType) {
  4755. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4756. if (dataType === void 0) { dataType = 7; }
  4757. try {
  4758. if (dataType & 1) {
  4759. if (xhr.responseText && xhr.responseText.length > 0) {
  4760. return true;
  4761. }
  4762. else if (dataType === 1) {
  4763. return false;
  4764. }
  4765. }
  4766. if (dataType & 2) {
  4767. // Check header width and height since there is no "TGA" magic number
  4768. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4769. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4770. return true;
  4771. }
  4772. else if (dataType === 2) {
  4773. return false;
  4774. }
  4775. }
  4776. if (dataType & 4) {
  4777. // Check for the "DDS" magic number
  4778. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4779. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4780. return true;
  4781. }
  4782. else {
  4783. return false;
  4784. }
  4785. }
  4786. }
  4787. catch (e) {
  4788. }
  4789. return false;
  4790. };
  4791. Object.defineProperty(Tools, "NoneLogLevel", {
  4792. get: function () {
  4793. return Tools._NoneLogLevel;
  4794. },
  4795. enumerable: true,
  4796. configurable: true
  4797. });
  4798. Object.defineProperty(Tools, "MessageLogLevel", {
  4799. get: function () {
  4800. return Tools._MessageLogLevel;
  4801. },
  4802. enumerable: true,
  4803. configurable: true
  4804. });
  4805. Object.defineProperty(Tools, "WarningLogLevel", {
  4806. get: function () {
  4807. return Tools._WarningLogLevel;
  4808. },
  4809. enumerable: true,
  4810. configurable: true
  4811. });
  4812. Object.defineProperty(Tools, "ErrorLogLevel", {
  4813. get: function () {
  4814. return Tools._ErrorLogLevel;
  4815. },
  4816. enumerable: true,
  4817. configurable: true
  4818. });
  4819. Object.defineProperty(Tools, "AllLogLevel", {
  4820. get: function () {
  4821. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4822. },
  4823. enumerable: true,
  4824. configurable: true
  4825. });
  4826. Tools._AddLogEntry = function (entry) {
  4827. Tools._LogCache = entry + Tools._LogCache;
  4828. if (Tools.OnNewCacheEntry) {
  4829. Tools.OnNewCacheEntry(entry);
  4830. }
  4831. };
  4832. Tools._FormatMessage = function (message) {
  4833. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4834. var date = new Date();
  4835. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4836. };
  4837. Tools._LogDisabled = function (message) {
  4838. // nothing to do
  4839. };
  4840. Tools._LogEnabled = function (message) {
  4841. var formattedMessage = Tools._FormatMessage(message);
  4842. console.log("BJS - " + formattedMessage);
  4843. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4844. Tools._AddLogEntry(entry);
  4845. };
  4846. Tools._WarnDisabled = function (message) {
  4847. // nothing to do
  4848. };
  4849. Tools._WarnEnabled = function (message) {
  4850. var formattedMessage = Tools._FormatMessage(message);
  4851. console.warn("BJS - " + formattedMessage);
  4852. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4853. Tools._AddLogEntry(entry);
  4854. };
  4855. Tools._ErrorDisabled = function (message) {
  4856. // nothing to do
  4857. };
  4858. Tools._ErrorEnabled = function (message) {
  4859. Tools.errorsCount++;
  4860. var formattedMessage = Tools._FormatMessage(message);
  4861. console.error("BJS - " + formattedMessage);
  4862. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4863. Tools._AddLogEntry(entry);
  4864. };
  4865. Object.defineProperty(Tools, "LogCache", {
  4866. get: function () {
  4867. return Tools._LogCache;
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. Tools.ClearLogCache = function () {
  4873. Tools._LogCache = "";
  4874. Tools.errorsCount = 0;
  4875. };
  4876. Object.defineProperty(Tools, "LogLevels", {
  4877. set: function (level) {
  4878. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4879. Tools.Log = Tools._LogEnabled;
  4880. }
  4881. else {
  4882. Tools.Log = Tools._LogDisabled;
  4883. }
  4884. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4885. Tools.Warn = Tools._WarnEnabled;
  4886. }
  4887. else {
  4888. Tools.Warn = Tools._WarnDisabled;
  4889. }
  4890. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4891. Tools.Error = Tools._ErrorEnabled;
  4892. }
  4893. else {
  4894. Tools.Error = Tools._ErrorDisabled;
  4895. }
  4896. },
  4897. enumerable: true,
  4898. configurable: true
  4899. });
  4900. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4901. get: function () {
  4902. return Tools._PerformanceNoneLogLevel;
  4903. },
  4904. enumerable: true,
  4905. configurable: true
  4906. });
  4907. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4908. get: function () {
  4909. return Tools._PerformanceUserMarkLogLevel;
  4910. },
  4911. enumerable: true,
  4912. configurable: true
  4913. });
  4914. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4915. get: function () {
  4916. return Tools._PerformanceConsoleLogLevel;
  4917. },
  4918. enumerable: true,
  4919. configurable: true
  4920. });
  4921. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4922. set: function (level) {
  4923. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4924. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4925. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4926. return;
  4927. }
  4928. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4929. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4930. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4931. return;
  4932. }
  4933. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4934. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4935. },
  4936. enumerable: true,
  4937. configurable: true
  4938. });
  4939. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4940. };
  4941. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4942. };
  4943. Tools._StartUserMark = function (counterName, condition) {
  4944. if (condition === void 0) { condition = true; }
  4945. if (!condition || !Tools._performance.mark) {
  4946. return;
  4947. }
  4948. Tools._performance.mark(counterName + "-Begin");
  4949. };
  4950. Tools._EndUserMark = function (counterName, condition) {
  4951. if (condition === void 0) { condition = true; }
  4952. if (!condition || !Tools._performance.mark) {
  4953. return;
  4954. }
  4955. Tools._performance.mark(counterName + "-End");
  4956. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4957. };
  4958. Tools._StartPerformanceConsole = function (counterName, condition) {
  4959. if (condition === void 0) { condition = true; }
  4960. if (!condition) {
  4961. return;
  4962. }
  4963. Tools._StartUserMark(counterName, condition);
  4964. if (console.time) {
  4965. console.time(counterName);
  4966. }
  4967. };
  4968. Tools._EndPerformanceConsole = function (counterName, condition) {
  4969. if (condition === void 0) { condition = true; }
  4970. if (!condition) {
  4971. return;
  4972. }
  4973. Tools._EndUserMark(counterName, condition);
  4974. if (console.time) {
  4975. console.timeEnd(counterName);
  4976. }
  4977. };
  4978. Object.defineProperty(Tools, "Now", {
  4979. get: function () {
  4980. if (window.performance && window.performance.now) {
  4981. return window.performance.now();
  4982. }
  4983. return new Date().getTime();
  4984. },
  4985. enumerable: true,
  4986. configurable: true
  4987. });
  4988. // Deprecated
  4989. Tools.GetFps = function () {
  4990. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4991. return 0;
  4992. };
  4993. Tools.BaseUrl = "";
  4994. // Logs
  4995. Tools._NoneLogLevel = 0;
  4996. Tools._MessageLogLevel = 1;
  4997. Tools._WarningLogLevel = 2;
  4998. Tools._ErrorLogLevel = 4;
  4999. Tools._LogCache = "";
  5000. Tools.errorsCount = 0;
  5001. Tools.Log = Tools._LogEnabled;
  5002. Tools.Warn = Tools._WarnEnabled;
  5003. Tools.Error = Tools._ErrorEnabled;
  5004. // Performances
  5005. Tools._PerformanceNoneLogLevel = 0;
  5006. Tools._PerformanceUserMarkLogLevel = 1;
  5007. Tools._PerformanceConsoleLogLevel = 2;
  5008. Tools._performance = window.performance;
  5009. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5010. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5011. return Tools;
  5012. })();
  5013. BABYLON.Tools = Tools;
  5014. /**
  5015. * An implementation of a loop for asynchronous functions.
  5016. */
  5017. var AsyncLoop = (function () {
  5018. /**
  5019. * Constroctor.
  5020. * @param iterations the number of iterations.
  5021. * @param _fn the function to run each iteration
  5022. * @param _successCallback the callback that will be called upon succesful execution
  5023. * @param offset starting offset.
  5024. */
  5025. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5026. if (offset === void 0) { offset = 0; }
  5027. this.iterations = iterations;
  5028. this._fn = _fn;
  5029. this._successCallback = _successCallback;
  5030. this.index = offset - 1;
  5031. this._done = false;
  5032. }
  5033. /**
  5034. * Execute the next iteration. Must be called after the last iteration was finished.
  5035. */
  5036. AsyncLoop.prototype.executeNext = function () {
  5037. if (!this._done) {
  5038. if (this.index + 1 < this.iterations) {
  5039. ++this.index;
  5040. this._fn(this);
  5041. }
  5042. else {
  5043. this.breakLoop();
  5044. }
  5045. }
  5046. };
  5047. /**
  5048. * Break the loop and run the success callback.
  5049. */
  5050. AsyncLoop.prototype.breakLoop = function () {
  5051. this._done = true;
  5052. this._successCallback();
  5053. };
  5054. /**
  5055. * Helper function
  5056. */
  5057. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5058. if (offset === void 0) { offset = 0; }
  5059. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5060. loop.executeNext();
  5061. return loop;
  5062. };
  5063. /**
  5064. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5065. * @param iterations total number of iterations
  5066. * @param syncedIterations number of synchronous iterations in each async iteration.
  5067. * @param fn the function to call each iteration.
  5068. * @param callback a success call back that will be called when iterating stops.
  5069. * @param breakFunction a break condition (optional)
  5070. * @param timeout timeout settings for the setTimeout function. default - 0.
  5071. * @constructor
  5072. */
  5073. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5074. if (timeout === void 0) { timeout = 0; }
  5075. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5076. if (breakFunction && breakFunction())
  5077. loop.breakLoop();
  5078. else {
  5079. setTimeout(function () {
  5080. for (var i = 0; i < syncedIterations; ++i) {
  5081. var iteration = (loop.index * syncedIterations) + i;
  5082. if (iteration >= iterations)
  5083. break;
  5084. fn(iteration);
  5085. if (breakFunction && breakFunction()) {
  5086. loop.breakLoop();
  5087. break;
  5088. }
  5089. }
  5090. loop.executeNext();
  5091. }, timeout);
  5092. }
  5093. }, callback);
  5094. };
  5095. return AsyncLoop;
  5096. })();
  5097. BABYLON.AsyncLoop = AsyncLoop;
  5098. })(BABYLON || (BABYLON = {}));
  5099. var BABYLON;
  5100. (function (BABYLON) {
  5101. var _DepthCullingState = (function () {
  5102. function _DepthCullingState() {
  5103. this._isDepthTestDirty = false;
  5104. this._isDepthMaskDirty = false;
  5105. this._isDepthFuncDirty = false;
  5106. this._isCullFaceDirty = false;
  5107. this._isCullDirty = false;
  5108. this._isZOffsetDirty = false;
  5109. }
  5110. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5111. get: function () {
  5112. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5118. get: function () {
  5119. return this._zOffset;
  5120. },
  5121. set: function (value) {
  5122. if (this._zOffset === value) {
  5123. return;
  5124. }
  5125. this._zOffset = value;
  5126. this._isZOffsetDirty = true;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5132. get: function () {
  5133. return this._cullFace;
  5134. },
  5135. set: function (value) {
  5136. if (this._cullFace === value) {
  5137. return;
  5138. }
  5139. this._cullFace = value;
  5140. this._isCullFaceDirty = true;
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5146. get: function () {
  5147. return this._cull;
  5148. },
  5149. set: function (value) {
  5150. if (this._cull === value) {
  5151. return;
  5152. }
  5153. this._cull = value;
  5154. this._isCullDirty = true;
  5155. },
  5156. enumerable: true,
  5157. configurable: true
  5158. });
  5159. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5160. get: function () {
  5161. return this._depthFunc;
  5162. },
  5163. set: function (value) {
  5164. if (this._depthFunc === value) {
  5165. return;
  5166. }
  5167. this._depthFunc = value;
  5168. this._isDepthFuncDirty = true;
  5169. },
  5170. enumerable: true,
  5171. configurable: true
  5172. });
  5173. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5174. get: function () {
  5175. return this._depthMask;
  5176. },
  5177. set: function (value) {
  5178. if (this._depthMask === value) {
  5179. return;
  5180. }
  5181. this._depthMask = value;
  5182. this._isDepthMaskDirty = true;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5188. get: function () {
  5189. return this._depthTest;
  5190. },
  5191. set: function (value) {
  5192. if (this._depthTest === value) {
  5193. return;
  5194. }
  5195. this._depthTest = value;
  5196. this._isDepthTestDirty = true;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. _DepthCullingState.prototype.reset = function () {
  5202. this._depthMask = true;
  5203. this._depthTest = true;
  5204. this._depthFunc = null;
  5205. this._cull = null;
  5206. this._cullFace = null;
  5207. this._zOffset = 0;
  5208. this._isDepthTestDirty = true;
  5209. this._isDepthMaskDirty = true;
  5210. this._isDepthFuncDirty = false;
  5211. this._isCullFaceDirty = false;
  5212. this._isCullDirty = false;
  5213. this._isZOffsetDirty = false;
  5214. };
  5215. _DepthCullingState.prototype.apply = function (gl) {
  5216. if (!this.isDirty) {
  5217. return;
  5218. }
  5219. // Cull
  5220. if (this._isCullDirty) {
  5221. if (this.cull) {
  5222. gl.enable(gl.CULL_FACE);
  5223. }
  5224. else {
  5225. gl.disable(gl.CULL_FACE);
  5226. }
  5227. this._isCullDirty = false;
  5228. }
  5229. // Cull face
  5230. if (this._isCullFaceDirty) {
  5231. gl.cullFace(this.cullFace);
  5232. this._isCullFaceDirty = false;
  5233. }
  5234. // Depth mask
  5235. if (this._isDepthMaskDirty) {
  5236. gl.depthMask(this.depthMask);
  5237. this._isDepthMaskDirty = false;
  5238. }
  5239. // Depth test
  5240. if (this._isDepthTestDirty) {
  5241. if (this.depthTest) {
  5242. gl.enable(gl.DEPTH_TEST);
  5243. }
  5244. else {
  5245. gl.disable(gl.DEPTH_TEST);
  5246. }
  5247. this._isDepthTestDirty = false;
  5248. }
  5249. // Depth func
  5250. if (this._isDepthFuncDirty) {
  5251. gl.depthFunc(this.depthFunc);
  5252. this._isDepthFuncDirty = false;
  5253. }
  5254. // zOffset
  5255. if (this._isZOffsetDirty) {
  5256. if (this.zOffset) {
  5257. gl.enable(gl.POLYGON_OFFSET_FILL);
  5258. gl.polygonOffset(this.zOffset, 0);
  5259. }
  5260. else {
  5261. gl.disable(gl.POLYGON_OFFSET_FILL);
  5262. }
  5263. this._isZOffsetDirty = false;
  5264. }
  5265. };
  5266. return _DepthCullingState;
  5267. })();
  5268. BABYLON._DepthCullingState = _DepthCullingState;
  5269. var _AlphaState = (function () {
  5270. function _AlphaState() {
  5271. this._isAlphaBlendDirty = false;
  5272. this._isBlendFunctionParametersDirty = false;
  5273. this._alphaBlend = false;
  5274. this._blendFunctionParameters = new Array(4);
  5275. }
  5276. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5277. get: function () {
  5278. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5279. },
  5280. enumerable: true,
  5281. configurable: true
  5282. });
  5283. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5284. get: function () {
  5285. return this._alphaBlend;
  5286. },
  5287. set: function (value) {
  5288. if (this._alphaBlend === value) {
  5289. return;
  5290. }
  5291. this._alphaBlend = value;
  5292. this._isAlphaBlendDirty = true;
  5293. },
  5294. enumerable: true,
  5295. configurable: true
  5296. });
  5297. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5298. if (this._blendFunctionParameters[0] === value0 &&
  5299. this._blendFunctionParameters[1] === value1 &&
  5300. this._blendFunctionParameters[2] === value2 &&
  5301. this._blendFunctionParameters[3] === value3) {
  5302. return;
  5303. }
  5304. this._blendFunctionParameters[0] = value0;
  5305. this._blendFunctionParameters[1] = value1;
  5306. this._blendFunctionParameters[2] = value2;
  5307. this._blendFunctionParameters[3] = value3;
  5308. this._isBlendFunctionParametersDirty = true;
  5309. };
  5310. _AlphaState.prototype.reset = function () {
  5311. this._alphaBlend = false;
  5312. this._blendFunctionParameters[0] = null;
  5313. this._blendFunctionParameters[1] = null;
  5314. this._blendFunctionParameters[2] = null;
  5315. this._blendFunctionParameters[3] = null;
  5316. this._isAlphaBlendDirty = true;
  5317. this._isBlendFunctionParametersDirty = false;
  5318. };
  5319. _AlphaState.prototype.apply = function (gl) {
  5320. if (!this.isDirty) {
  5321. return;
  5322. }
  5323. // Alpha blend
  5324. if (this._isAlphaBlendDirty) {
  5325. if (this._alphaBlend) {
  5326. gl.enable(gl.BLEND);
  5327. }
  5328. else {
  5329. gl.disable(gl.BLEND);
  5330. }
  5331. this._isAlphaBlendDirty = false;
  5332. }
  5333. // Alpha function
  5334. if (this._isBlendFunctionParametersDirty) {
  5335. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5336. this._isBlendFunctionParametersDirty = false;
  5337. }
  5338. };
  5339. return _AlphaState;
  5340. })();
  5341. BABYLON._AlphaState = _AlphaState;
  5342. var compileShader = function (gl, source, type, defines) {
  5343. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5344. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5345. gl.compileShader(shader);
  5346. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5347. throw new Error(gl.getShaderInfoLog(shader));
  5348. }
  5349. return shader;
  5350. };
  5351. var getWebGLTextureType = function (gl, type) {
  5352. var textureType = gl.UNSIGNED_BYTE;
  5353. if (type === Engine.TEXTURETYPE_FLOAT)
  5354. textureType = gl.FLOAT;
  5355. return textureType;
  5356. };
  5357. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5358. var magFilter = gl.NEAREST;
  5359. var minFilter = gl.NEAREST;
  5360. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5361. magFilter = gl.LINEAR;
  5362. if (generateMipMaps) {
  5363. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5364. }
  5365. else {
  5366. minFilter = gl.LINEAR;
  5367. }
  5368. }
  5369. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5370. magFilter = gl.LINEAR;
  5371. if (generateMipMaps) {
  5372. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5373. }
  5374. else {
  5375. minFilter = gl.LINEAR;
  5376. }
  5377. }
  5378. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5379. magFilter = gl.NEAREST;
  5380. if (generateMipMaps) {
  5381. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5382. }
  5383. else {
  5384. minFilter = gl.NEAREST;
  5385. }
  5386. }
  5387. return {
  5388. min: minFilter,
  5389. mag: magFilter
  5390. };
  5391. };
  5392. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5394. var engine = scene.getEngine();
  5395. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5396. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5397. gl.bindTexture(gl.TEXTURE_2D, texture);
  5398. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5399. texture._baseWidth = width;
  5400. texture._baseHeight = height;
  5401. texture._width = potWidth;
  5402. texture._height = potHeight;
  5403. texture.isReady = true;
  5404. processFunction(potWidth, potHeight);
  5405. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5408. if (!noMipmap && !isCompressed) {
  5409. gl.generateMipmap(gl.TEXTURE_2D);
  5410. }
  5411. gl.bindTexture(gl.TEXTURE_2D, null);
  5412. engine._activeTexturesCache = [];
  5413. scene._removePendingData(texture);
  5414. };
  5415. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5416. var onload = function () {
  5417. loadedImages[index] = img;
  5418. loadedImages._internalCount++;
  5419. scene._removePendingData(img);
  5420. if (loadedImages._internalCount === 6) {
  5421. onfinish(loadedImages);
  5422. }
  5423. };
  5424. var onerror = function () {
  5425. scene._removePendingData(img);
  5426. };
  5427. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5428. scene._addPendingData(img);
  5429. };
  5430. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5431. var loadedImages = [];
  5432. loadedImages._internalCount = 0;
  5433. for (var index = 0; index < 6; index++) {
  5434. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5435. }
  5436. };
  5437. var EngineCapabilities = (function () {
  5438. function EngineCapabilities() {
  5439. }
  5440. return EngineCapabilities;
  5441. })();
  5442. BABYLON.EngineCapabilities = EngineCapabilities;
  5443. /**
  5444. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5445. */
  5446. var Engine = (function () {
  5447. /**
  5448. * @constructor
  5449. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5450. * @param {boolean} [antialias] - enable antialias
  5451. * @param options - further options to be sent to the getContext function
  5452. */
  5453. function Engine(canvas, antialias, options) {
  5454. var _this = this;
  5455. // Public members
  5456. this.isFullscreen = false;
  5457. this.isPointerLock = false;
  5458. this.cullBackFaces = true;
  5459. this.renderEvenInBackground = true;
  5460. // To enable/disable IDB support and avoid XHR on .manifest
  5461. this.enableOfflineSupport = true;
  5462. this.scenes = new Array();
  5463. this._windowIsBackground = false;
  5464. this._loadingDivBackgroundColor = "black";
  5465. this._drawCalls = 0;
  5466. this._renderingQueueLaunched = false;
  5467. this._activeRenderLoops = [];
  5468. // FPS
  5469. this.fpsRange = 60;
  5470. this.previousFramesDuration = [];
  5471. this.fps = 60;
  5472. this.deltaTime = 0;
  5473. // States
  5474. this._depthCullingState = new _DepthCullingState();
  5475. this._alphaState = new _AlphaState();
  5476. this._alphaMode = Engine.ALPHA_DISABLE;
  5477. // Cache
  5478. this._loadedTexturesCache = new Array();
  5479. this._activeTexturesCache = new Array();
  5480. this._compiledEffects = {};
  5481. this._uintIndicesCurrentlySet = false;
  5482. this._renderingCanvas = canvas;
  5483. options = options || {};
  5484. options.antialias = antialias;
  5485. if (options.preserveDrawingBuffer === undefined) {
  5486. options.preserveDrawingBuffer = false;
  5487. }
  5488. // GL
  5489. try {
  5490. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5491. }
  5492. catch (e) {
  5493. throw new Error("WebGL not supported");
  5494. }
  5495. if (!this._gl) {
  5496. throw new Error("WebGL not supported");
  5497. }
  5498. this._onBlur = function () {
  5499. _this._windowIsBackground = true;
  5500. };
  5501. this._onFocus = function () {
  5502. _this._windowIsBackground = false;
  5503. };
  5504. window.addEventListener("blur", this._onBlur);
  5505. window.addEventListener("focus", this._onFocus);
  5506. // Viewport
  5507. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5508. this.resize();
  5509. // Caps
  5510. this._caps = new EngineCapabilities();
  5511. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5512. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5513. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5514. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5515. // Infos
  5516. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5517. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5518. if (rendererInfo != null) {
  5519. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5520. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5521. }
  5522. if (!this._glVendor) {
  5523. this._glVendor = "Unknown vendor";
  5524. }
  5525. if (!this._glRenderer) {
  5526. this._glRenderer = "Unknown renderer";
  5527. }
  5528. // Extensions
  5529. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5530. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5531. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5532. 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');
  5533. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5534. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5535. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5536. this._caps.highPrecisionShaderSupported = true;
  5537. if (this._gl.getShaderPrecisionFormat) {
  5538. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5539. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5540. }
  5541. // Depth buffer
  5542. this.setDepthBuffer(true);
  5543. this.setDepthFunctionToLessOrEqual();
  5544. this.setDepthWrite(true);
  5545. // Fullscreen
  5546. this._onFullscreenChange = function () {
  5547. if (document.fullscreen !== undefined) {
  5548. _this.isFullscreen = document.fullscreen;
  5549. }
  5550. else if (document.mozFullScreen !== undefined) {
  5551. _this.isFullscreen = document.mozFullScreen;
  5552. }
  5553. else if (document.webkitIsFullScreen !== undefined) {
  5554. _this.isFullscreen = document.webkitIsFullScreen;
  5555. }
  5556. else if (document.msIsFullScreen !== undefined) {
  5557. _this.isFullscreen = document.msIsFullScreen;
  5558. }
  5559. // Pointer lock
  5560. if (_this.isFullscreen && _this._pointerLockRequested) {
  5561. canvas.requestPointerLock = canvas.requestPointerLock ||
  5562. canvas.msRequestPointerLock ||
  5563. canvas.mozRequestPointerLock ||
  5564. canvas.webkitRequestPointerLock;
  5565. if (canvas.requestPointerLock) {
  5566. canvas.requestPointerLock();
  5567. }
  5568. }
  5569. };
  5570. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5571. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5572. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5573. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5574. // Pointer lock
  5575. this._onPointerLockChange = function () {
  5576. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5577. document.webkitPointerLockElement === canvas ||
  5578. document.msPointerLockElement === canvas ||
  5579. document.pointerLockElement === canvas);
  5580. };
  5581. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5582. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5583. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5584. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5585. if (!Engine.audioEngine) {
  5586. Engine.audioEngine = new BABYLON.AudioEngine();
  5587. }
  5588. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5589. }
  5590. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5591. get: function () {
  5592. return Engine._ALPHA_DISABLE;
  5593. },
  5594. enumerable: true,
  5595. configurable: true
  5596. });
  5597. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5598. get: function () {
  5599. return Engine._ALPHA_ONEONE;
  5600. },
  5601. enumerable: true,
  5602. configurable: true
  5603. });
  5604. Object.defineProperty(Engine, "ALPHA_ADD", {
  5605. get: function () {
  5606. return Engine._ALPHA_ADD;
  5607. },
  5608. enumerable: true,
  5609. configurable: true
  5610. });
  5611. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5612. get: function () {
  5613. return Engine._ALPHA_COMBINE;
  5614. },
  5615. enumerable: true,
  5616. configurable: true
  5617. });
  5618. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5619. get: function () {
  5620. return Engine._ALPHA_SUBTRACT;
  5621. },
  5622. enumerable: true,
  5623. configurable: true
  5624. });
  5625. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5626. get: function () {
  5627. return Engine._ALPHA_MULTIPLY;
  5628. },
  5629. enumerable: true,
  5630. configurable: true
  5631. });
  5632. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5633. get: function () {
  5634. return Engine._ALPHA_MAXIMIZED;
  5635. },
  5636. enumerable: true,
  5637. configurable: true
  5638. });
  5639. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5640. get: function () {
  5641. return Engine._DELAYLOADSTATE_NONE;
  5642. },
  5643. enumerable: true,
  5644. configurable: true
  5645. });
  5646. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5647. get: function () {
  5648. return Engine._DELAYLOADSTATE_LOADED;
  5649. },
  5650. enumerable: true,
  5651. configurable: true
  5652. });
  5653. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5654. get: function () {
  5655. return Engine._DELAYLOADSTATE_LOADING;
  5656. },
  5657. enumerable: true,
  5658. configurable: true
  5659. });
  5660. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5661. get: function () {
  5662. return Engine._DELAYLOADSTATE_NOTLOADED;
  5663. },
  5664. enumerable: true,
  5665. configurable: true
  5666. });
  5667. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5668. get: function () {
  5669. return Engine._TEXTUREFORMAT_ALPHA;
  5670. },
  5671. enumerable: true,
  5672. configurable: true
  5673. });
  5674. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5675. get: function () {
  5676. return Engine._TEXTUREFORMAT_LUMINANCE;
  5677. },
  5678. enumerable: true,
  5679. configurable: true
  5680. });
  5681. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5682. get: function () {
  5683. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5684. },
  5685. enumerable: true,
  5686. configurable: true
  5687. });
  5688. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5689. get: function () {
  5690. return Engine._TEXTUREFORMAT_RGB;
  5691. },
  5692. enumerable: true,
  5693. configurable: true
  5694. });
  5695. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5696. get: function () {
  5697. return Engine._TEXTUREFORMAT_RGBA;
  5698. },
  5699. enumerable: true,
  5700. configurable: true
  5701. });
  5702. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5703. get: function () {
  5704. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5705. },
  5706. enumerable: true,
  5707. configurable: true
  5708. });
  5709. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5710. get: function () {
  5711. return Engine._TEXTURETYPE_FLOAT;
  5712. },
  5713. enumerable: true,
  5714. configurable: true
  5715. });
  5716. Object.defineProperty(Engine, "Version", {
  5717. get: function () {
  5718. return "2.3.0-alpha";
  5719. },
  5720. enumerable: true,
  5721. configurable: true
  5722. });
  5723. Engine.prototype._prepareWorkingCanvas = function () {
  5724. if (this._workingCanvas) {
  5725. return;
  5726. }
  5727. this._workingCanvas = document.createElement("canvas");
  5728. this._workingContext = this._workingCanvas.getContext("2d");
  5729. };
  5730. Engine.prototype.getGlInfo = function () {
  5731. return {
  5732. vendor: this._glVendor,
  5733. renderer: this._glRenderer,
  5734. version: this._glVersion
  5735. };
  5736. };
  5737. Engine.prototype.getAspectRatio = function (camera) {
  5738. var viewport = camera.viewport;
  5739. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5740. };
  5741. Engine.prototype.getRenderWidth = function () {
  5742. if (this._currentRenderTarget) {
  5743. return this._currentRenderTarget._width;
  5744. }
  5745. return this._renderingCanvas.width;
  5746. };
  5747. Engine.prototype.getRenderHeight = function () {
  5748. if (this._currentRenderTarget) {
  5749. return this._currentRenderTarget._height;
  5750. }
  5751. return this._renderingCanvas.height;
  5752. };
  5753. Engine.prototype.getRenderingCanvas = function () {
  5754. return this._renderingCanvas;
  5755. };
  5756. Engine.prototype.getRenderingCanvasClientRect = function () {
  5757. return this._renderingCanvas.getBoundingClientRect();
  5758. };
  5759. Engine.prototype.setHardwareScalingLevel = function (level) {
  5760. this._hardwareScalingLevel = level;
  5761. this.resize();
  5762. };
  5763. Engine.prototype.getHardwareScalingLevel = function () {
  5764. return this._hardwareScalingLevel;
  5765. };
  5766. Engine.prototype.getLoadedTexturesCache = function () {
  5767. return this._loadedTexturesCache;
  5768. };
  5769. Engine.prototype.getCaps = function () {
  5770. return this._caps;
  5771. };
  5772. Object.defineProperty(Engine.prototype, "drawCalls", {
  5773. get: function () {
  5774. return this._drawCalls;
  5775. },
  5776. enumerable: true,
  5777. configurable: true
  5778. });
  5779. // Methods
  5780. Engine.prototype.resetDrawCalls = function () {
  5781. this._drawCalls = 0;
  5782. };
  5783. Engine.prototype.setDepthFunctionToGreater = function () {
  5784. this._depthCullingState.depthFunc = this._gl.GREATER;
  5785. };
  5786. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5787. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5788. };
  5789. Engine.prototype.setDepthFunctionToLess = function () {
  5790. this._depthCullingState.depthFunc = this._gl.LESS;
  5791. };
  5792. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5793. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5794. };
  5795. /**
  5796. * stop executing a render loop function and remove it from the execution array
  5797. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5798. */
  5799. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5800. if (!renderFunction) {
  5801. this._activeRenderLoops = [];
  5802. return;
  5803. }
  5804. var index = this._activeRenderLoops.indexOf(renderFunction);
  5805. if (index >= 0) {
  5806. this._activeRenderLoops.splice(index, 1);
  5807. }
  5808. };
  5809. Engine.prototype._renderLoop = function () {
  5810. var _this = this;
  5811. var shouldRender = true;
  5812. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5813. shouldRender = false;
  5814. }
  5815. if (shouldRender) {
  5816. // Start new frame
  5817. this.beginFrame();
  5818. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5819. var renderFunction = this._activeRenderLoops[index];
  5820. renderFunction();
  5821. }
  5822. // Present
  5823. this.endFrame();
  5824. }
  5825. if (this._activeRenderLoops.length > 0) {
  5826. // Register new frame
  5827. BABYLON.Tools.QueueNewFrame(function () {
  5828. _this._renderLoop();
  5829. });
  5830. }
  5831. else {
  5832. this._renderingQueueLaunched = false;
  5833. }
  5834. };
  5835. /**
  5836. * Register and execute a render loop. The engine can have more than one render function.
  5837. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5838. * @example
  5839. * engine.runRenderLoop(function () {
  5840. * scene.render()
  5841. * })
  5842. */
  5843. Engine.prototype.runRenderLoop = function (renderFunction) {
  5844. var _this = this;
  5845. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5846. return;
  5847. }
  5848. this._activeRenderLoops.push(renderFunction);
  5849. if (!this._renderingQueueLaunched) {
  5850. this._renderingQueueLaunched = true;
  5851. BABYLON.Tools.QueueNewFrame(function () {
  5852. _this._renderLoop();
  5853. });
  5854. }
  5855. };
  5856. /**
  5857. * Toggle full screen mode.
  5858. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5859. */
  5860. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5861. if (this.isFullscreen) {
  5862. BABYLON.Tools.ExitFullscreen();
  5863. }
  5864. else {
  5865. this._pointerLockRequested = requestPointerLock;
  5866. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5867. }
  5868. };
  5869. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5870. this.applyStates();
  5871. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5872. if (this._depthCullingState.depthMask) {
  5873. this._gl.clearDepth(1.0);
  5874. }
  5875. var mode = 0;
  5876. if (backBuffer)
  5877. mode |= this._gl.COLOR_BUFFER_BIT;
  5878. if (depthStencil && this._depthCullingState.depthMask)
  5879. mode |= this._gl.DEPTH_BUFFER_BIT;
  5880. this._gl.clear(mode);
  5881. };
  5882. /**
  5883. * Set the WebGL's viewport
  5884. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5885. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5886. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5887. */
  5888. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5889. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5890. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5891. var x = viewport.x || 0;
  5892. var y = viewport.y || 0;
  5893. this._cachedViewport = viewport;
  5894. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5895. };
  5896. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5897. this._cachedViewport = null;
  5898. this._gl.viewport(x, y, width, height);
  5899. };
  5900. Engine.prototype.beginFrame = function () {
  5901. this._measureFps();
  5902. };
  5903. Engine.prototype.endFrame = function () {
  5904. //this.flushFramebuffer();
  5905. };
  5906. /**
  5907. * resize the view according to the canvas' size.
  5908. * @example
  5909. * window.addEventListener("resize", function () {
  5910. * engine.resize();
  5911. * });
  5912. */
  5913. Engine.prototype.resize = function () {
  5914. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5915. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5916. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5917. };
  5918. /**
  5919. * force a specific size of the canvas
  5920. * @param {number} width - the new canvas' width
  5921. * @param {number} height - the new canvas' height
  5922. */
  5923. Engine.prototype.setSize = function (width, height) {
  5924. this._renderingCanvas.width = width;
  5925. this._renderingCanvas.height = height;
  5926. for (var index = 0; index < this.scenes.length; index++) {
  5927. var scene = this.scenes[index];
  5928. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5929. var cam = scene.cameras[camIndex];
  5930. cam._currentRenderId = 0;
  5931. }
  5932. }
  5933. };
  5934. Engine.prototype.bindFramebuffer = function (texture) {
  5935. this._currentRenderTarget = texture;
  5936. var gl = this._gl;
  5937. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5938. this._gl.viewport(0, 0, texture._width, texture._height);
  5939. this.wipeCaches();
  5940. };
  5941. Engine.prototype.unBindFramebuffer = function (texture) {
  5942. this._currentRenderTarget = null;
  5943. if (texture.generateMipMaps) {
  5944. var gl = this._gl;
  5945. gl.bindTexture(gl.TEXTURE_2D, texture);
  5946. gl.generateMipmap(gl.TEXTURE_2D);
  5947. gl.bindTexture(gl.TEXTURE_2D, null);
  5948. }
  5949. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5950. };
  5951. Engine.prototype.flushFramebuffer = function () {
  5952. this._gl.flush();
  5953. };
  5954. Engine.prototype.restoreDefaultFramebuffer = function () {
  5955. this._currentRenderTarget = null;
  5956. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5957. this.setViewport(this._cachedViewport);
  5958. this.wipeCaches();
  5959. };
  5960. // VBOs
  5961. Engine.prototype._resetVertexBufferBinding = function () {
  5962. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5963. this._cachedVertexBuffers = null;
  5964. };
  5965. Engine.prototype.createVertexBuffer = function (vertices) {
  5966. var vbo = this._gl.createBuffer();
  5967. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5968. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5969. this._resetVertexBufferBinding();
  5970. vbo.references = 1;
  5971. return vbo;
  5972. };
  5973. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5974. var vbo = this._gl.createBuffer();
  5975. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5976. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5977. this._resetVertexBufferBinding();
  5978. vbo.references = 1;
  5979. return vbo;
  5980. };
  5981. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5982. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5983. if (offset === undefined) {
  5984. offset = 0;
  5985. }
  5986. if (vertices instanceof Float32Array) {
  5987. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5988. }
  5989. else {
  5990. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5991. }
  5992. this._resetVertexBufferBinding();
  5993. };
  5994. Engine.prototype._resetIndexBufferBinding = function () {
  5995. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5996. this._cachedIndexBuffer = null;
  5997. };
  5998. Engine.prototype.createIndexBuffer = function (indices) {
  5999. var vbo = this._gl.createBuffer();
  6000. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6001. // Check for 32 bits indices
  6002. var arrayBuffer;
  6003. var need32Bits = false;
  6004. if (this._caps.uintIndices) {
  6005. for (var index = 0; index < indices.length; index++) {
  6006. if (indices[index] > 65535) {
  6007. need32Bits = true;
  6008. break;
  6009. }
  6010. }
  6011. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6012. }
  6013. else {
  6014. arrayBuffer = new Uint16Array(indices);
  6015. }
  6016. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6017. this._resetIndexBufferBinding();
  6018. vbo.references = 1;
  6019. vbo.is32Bits = need32Bits;
  6020. return vbo;
  6021. };
  6022. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6023. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6024. this._cachedVertexBuffers = vertexBuffer;
  6025. this._cachedEffectForVertexBuffers = effect;
  6026. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6027. var offset = 0;
  6028. for (var index = 0; index < vertexDeclaration.length; index++) {
  6029. var order = effect.getAttributeLocation(index);
  6030. if (order >= 0) {
  6031. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6032. }
  6033. offset += vertexDeclaration[index] * 4;
  6034. }
  6035. }
  6036. if (this._cachedIndexBuffer !== indexBuffer) {
  6037. this._cachedIndexBuffer = indexBuffer;
  6038. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6039. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6040. }
  6041. };
  6042. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6043. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6044. this._cachedVertexBuffers = vertexBuffers;
  6045. this._cachedEffectForVertexBuffers = effect;
  6046. var attributes = effect.getAttributesNames();
  6047. for (var index = 0; index < attributes.length; index++) {
  6048. var order = effect.getAttributeLocation(index);
  6049. if (order >= 0) {
  6050. var vertexBuffer = vertexBuffers[attributes[index]];
  6051. if (!vertexBuffer) {
  6052. continue;
  6053. }
  6054. var stride = vertexBuffer.getStrideSize();
  6055. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6056. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6057. }
  6058. }
  6059. }
  6060. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6061. this._cachedIndexBuffer = indexBuffer;
  6062. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6063. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6064. }
  6065. };
  6066. Engine.prototype._releaseBuffer = function (buffer) {
  6067. buffer.references--;
  6068. if (buffer.references === 0) {
  6069. this._gl.deleteBuffer(buffer);
  6070. return true;
  6071. }
  6072. return false;
  6073. };
  6074. Engine.prototype.createInstancesBuffer = function (capacity) {
  6075. var buffer = this._gl.createBuffer();
  6076. buffer.capacity = capacity;
  6077. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6078. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6079. return buffer;
  6080. };
  6081. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6082. this._gl.deleteBuffer(buffer);
  6083. };
  6084. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6086. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6087. for (var index = 0; index < 4; index++) {
  6088. var offsetLocation = offsetLocations[index];
  6089. this._gl.enableVertexAttribArray(offsetLocation);
  6090. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6091. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6092. }
  6093. };
  6094. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6095. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6096. for (var index = 0; index < 4; index++) {
  6097. var offsetLocation = offsetLocations[index];
  6098. this._gl.disableVertexAttribArray(offsetLocation);
  6099. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6100. }
  6101. };
  6102. Engine.prototype.applyStates = function () {
  6103. this._depthCullingState.apply(this._gl);
  6104. this._alphaState.apply(this._gl);
  6105. };
  6106. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6107. // Apply states
  6108. this.applyStates();
  6109. this._drawCalls++;
  6110. // Render
  6111. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6112. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6113. if (instancesCount) {
  6114. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6115. return;
  6116. }
  6117. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6118. };
  6119. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6120. // Apply states
  6121. this.applyStates();
  6122. this._drawCalls++;
  6123. if (instancesCount) {
  6124. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6125. return;
  6126. }
  6127. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6128. };
  6129. // Shaders
  6130. Engine.prototype._releaseEffect = function (effect) {
  6131. if (this._compiledEffects[effect._key]) {
  6132. delete this._compiledEffects[effect._key];
  6133. if (effect.getProgram()) {
  6134. this._gl.deleteProgram(effect.getProgram());
  6135. }
  6136. }
  6137. };
  6138. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6139. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6140. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6141. var name = vertex + "+" + fragment + "@" + defines;
  6142. if (this._compiledEffects[name]) {
  6143. return this._compiledEffects[name];
  6144. }
  6145. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6146. effect._key = name;
  6147. this._compiledEffects[name] = effect;
  6148. return effect;
  6149. };
  6150. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6151. if (uniformsNames === void 0) { uniformsNames = []; }
  6152. if (samplers === void 0) { samplers = []; }
  6153. if (defines === void 0) { defines = ""; }
  6154. return this.createEffect({
  6155. vertex: "particles",
  6156. fragmentElement: fragmentName
  6157. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6158. };
  6159. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6160. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6161. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6162. var shaderProgram = this._gl.createProgram();
  6163. this._gl.attachShader(shaderProgram, vertexShader);
  6164. this._gl.attachShader(shaderProgram, fragmentShader);
  6165. this._gl.linkProgram(shaderProgram);
  6166. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6167. if (!linked) {
  6168. var error = this._gl.getProgramInfoLog(shaderProgram);
  6169. if (error) {
  6170. throw new Error(error);
  6171. }
  6172. }
  6173. this._gl.deleteShader(vertexShader);
  6174. this._gl.deleteShader(fragmentShader);
  6175. return shaderProgram;
  6176. };
  6177. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6178. var results = [];
  6179. for (var index = 0; index < uniformsNames.length; index++) {
  6180. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6181. }
  6182. return results;
  6183. };
  6184. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6185. var results = [];
  6186. for (var index = 0; index < attributesNames.length; index++) {
  6187. try {
  6188. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6189. }
  6190. catch (e) {
  6191. results.push(-1);
  6192. }
  6193. }
  6194. return results;
  6195. };
  6196. Engine.prototype.enableEffect = function (effect) {
  6197. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6198. if (effect && effect.onBind) {
  6199. effect.onBind(effect);
  6200. }
  6201. return;
  6202. }
  6203. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6204. // Use program
  6205. this._gl.useProgram(effect.getProgram());
  6206. for (var i in this._vertexAttribArrays) {
  6207. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6208. continue;
  6209. }
  6210. this._vertexAttribArrays[i] = false;
  6211. this._gl.disableVertexAttribArray(i);
  6212. }
  6213. var attributesCount = effect.getAttributesCount();
  6214. for (var index = 0; index < attributesCount; index++) {
  6215. // Attributes
  6216. var order = effect.getAttributeLocation(index);
  6217. if (order >= 0) {
  6218. this._vertexAttribArrays[order] = true;
  6219. this._gl.enableVertexAttribArray(order);
  6220. }
  6221. }
  6222. this._currentEffect = effect;
  6223. if (effect.onBind) {
  6224. effect.onBind(effect);
  6225. }
  6226. };
  6227. Engine.prototype.setArray = function (uniform, array) {
  6228. if (!uniform)
  6229. return;
  6230. this._gl.uniform1fv(uniform, array);
  6231. };
  6232. Engine.prototype.setArray2 = function (uniform, array) {
  6233. if (!uniform || array.length % 2 !== 0)
  6234. return;
  6235. this._gl.uniform2fv(uniform, array);
  6236. };
  6237. Engine.prototype.setArray3 = function (uniform, array) {
  6238. if (!uniform || array.length % 3 !== 0)
  6239. return;
  6240. this._gl.uniform3fv(uniform, array);
  6241. };
  6242. Engine.prototype.setArray4 = function (uniform, array) {
  6243. if (!uniform || array.length % 4 !== 0)
  6244. return;
  6245. this._gl.uniform4fv(uniform, array);
  6246. };
  6247. Engine.prototype.setMatrices = function (uniform, matrices) {
  6248. if (!uniform)
  6249. return;
  6250. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6251. };
  6252. Engine.prototype.setMatrix = function (uniform, matrix) {
  6253. if (!uniform)
  6254. return;
  6255. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6256. };
  6257. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6258. if (!uniform)
  6259. return;
  6260. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6261. };
  6262. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6263. if (!uniform)
  6264. return;
  6265. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6266. };
  6267. Engine.prototype.setFloat = function (uniform, value) {
  6268. if (!uniform)
  6269. return;
  6270. this._gl.uniform1f(uniform, value);
  6271. };
  6272. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6273. if (!uniform)
  6274. return;
  6275. this._gl.uniform2f(uniform, x, y);
  6276. };
  6277. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6278. if (!uniform)
  6279. return;
  6280. this._gl.uniform3f(uniform, x, y, z);
  6281. };
  6282. Engine.prototype.setBool = function (uniform, bool) {
  6283. if (!uniform)
  6284. return;
  6285. this._gl.uniform1i(uniform, bool);
  6286. };
  6287. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6288. if (!uniform)
  6289. return;
  6290. this._gl.uniform4f(uniform, x, y, z, w);
  6291. };
  6292. Engine.prototype.setColor3 = function (uniform, color3) {
  6293. if (!uniform)
  6294. return;
  6295. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6296. };
  6297. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6298. if (!uniform)
  6299. return;
  6300. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6301. };
  6302. // States
  6303. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6304. if (zOffset === void 0) { zOffset = 0; }
  6305. if (reverseSide === void 0) { reverseSide = false; }
  6306. // Culling
  6307. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6308. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6309. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6310. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace != cullFace) {
  6311. if (culling) {
  6312. this._depthCullingState.cullFace = cullFace;
  6313. this._depthCullingState.cull = true;
  6314. }
  6315. else {
  6316. this._depthCullingState.cull = false;
  6317. }
  6318. }
  6319. // Z offset
  6320. this._depthCullingState.zOffset = zOffset;
  6321. };
  6322. Engine.prototype.setDepthBuffer = function (enable) {
  6323. this._depthCullingState.depthTest = enable;
  6324. };
  6325. Engine.prototype.getDepthWrite = function () {
  6326. return this._depthCullingState.depthMask;
  6327. };
  6328. Engine.prototype.setDepthWrite = function (enable) {
  6329. this._depthCullingState.depthMask = enable;
  6330. };
  6331. Engine.prototype.setColorWrite = function (enable) {
  6332. this._gl.colorMask(enable, enable, enable, enable);
  6333. };
  6334. Engine.prototype.setAlphaMode = function (mode) {
  6335. if (this._alphaMode == mode) {
  6336. return;
  6337. }
  6338. switch (mode) {
  6339. case Engine.ALPHA_DISABLE:
  6340. this.setDepthWrite(true);
  6341. this._alphaState.alphaBlend = false;
  6342. break;
  6343. case Engine.ALPHA_COMBINE:
  6344. this.setDepthWrite(false);
  6345. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6346. this._alphaState.alphaBlend = true;
  6347. break;
  6348. case Engine.ALPHA_ONEONE:
  6349. this.setDepthWrite(false);
  6350. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6351. this._alphaState.alphaBlend = true;
  6352. break;
  6353. case Engine.ALPHA_ADD:
  6354. this.setDepthWrite(false);
  6355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6356. this._alphaState.alphaBlend = true;
  6357. break;
  6358. case Engine.ALPHA_SUBTRACT:
  6359. this.setDepthWrite(false);
  6360. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6361. this._alphaState.alphaBlend = true;
  6362. break;
  6363. case Engine.ALPHA_MULTIPLY:
  6364. this.setDepthWrite(false);
  6365. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6366. this._alphaState.alphaBlend = true;
  6367. break;
  6368. case Engine.ALPHA_MAXIMIZED:
  6369. this.setDepthWrite(false);
  6370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6371. this._alphaState.alphaBlend = true;
  6372. break;
  6373. }
  6374. this._alphaMode = mode;
  6375. };
  6376. Engine.prototype.getAlphaMode = function () {
  6377. return this._alphaMode;
  6378. };
  6379. Engine.prototype.setAlphaTesting = function (enable) {
  6380. this._alphaTest = enable;
  6381. };
  6382. Engine.prototype.getAlphaTesting = function () {
  6383. return this._alphaTest;
  6384. };
  6385. // Textures
  6386. Engine.prototype.wipeCaches = function () {
  6387. this._activeTexturesCache = [];
  6388. this._currentEffect = null;
  6389. this._depthCullingState.reset();
  6390. this._alphaState.reset();
  6391. this._cachedVertexBuffers = null;
  6392. this._cachedIndexBuffer = null;
  6393. this._cachedEffectForVertexBuffers = null;
  6394. };
  6395. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6396. var gl = this._gl;
  6397. gl.bindTexture(gl.TEXTURE_2D, texture);
  6398. var magFilter = gl.NEAREST;
  6399. var minFilter = gl.NEAREST;
  6400. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6401. magFilter = gl.LINEAR;
  6402. minFilter = gl.LINEAR;
  6403. }
  6404. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6405. magFilter = gl.LINEAR;
  6406. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6407. }
  6408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6410. gl.bindTexture(gl.TEXTURE_2D, null);
  6411. texture.samplingMode = samplingMode;
  6412. };
  6413. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6414. var _this = this;
  6415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6416. if (onLoad === void 0) { onLoad = null; }
  6417. if (onError === void 0) { onError = null; }
  6418. if (buffer === void 0) { buffer = null; }
  6419. var texture = this._gl.createTexture();
  6420. var extension;
  6421. var fromData = false;
  6422. if (url.substr(0, 5) === "data:") {
  6423. fromData = true;
  6424. }
  6425. if (!fromData)
  6426. extension = url.substr(url.length - 4, 4).toLowerCase();
  6427. else {
  6428. var oldUrl = url;
  6429. fromData = oldUrl.split(':');
  6430. url = oldUrl;
  6431. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6432. }
  6433. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6434. var isTGA = (extension === ".tga");
  6435. scene._addPendingData(texture);
  6436. texture.url = url;
  6437. texture.noMipmap = noMipmap;
  6438. texture.references = 1;
  6439. texture.samplingMode = samplingMode;
  6440. this._loadedTexturesCache.push(texture);
  6441. var onerror = function () {
  6442. scene._removePendingData(texture);
  6443. if (onError) {
  6444. onError();
  6445. }
  6446. };
  6447. if (isTGA) {
  6448. var callback = function (arrayBuffer) {
  6449. var data = new Uint8Array(arrayBuffer);
  6450. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6451. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6452. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6453. if (onLoad) {
  6454. onLoad();
  6455. }
  6456. }, samplingMode);
  6457. };
  6458. if (!(fromData instanceof Array))
  6459. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6460. callback(arrayBuffer);
  6461. }, onerror, scene.database, true);
  6462. else
  6463. callback(buffer);
  6464. }
  6465. else if (isDDS) {
  6466. callback = function (data) {
  6467. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6468. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6469. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6470. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6471. if (onLoad) {
  6472. onLoad();
  6473. }
  6474. }, samplingMode);
  6475. };
  6476. if (!(fromData instanceof Array))
  6477. BABYLON.Tools.LoadFile(url, function (data) {
  6478. callback(data);
  6479. }, onerror, scene.database, true);
  6480. else
  6481. callback(buffer);
  6482. }
  6483. else {
  6484. var onload = function (img) {
  6485. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6486. var isPot = (img.width === potWidth && img.height === potHeight);
  6487. if (!isPot) {
  6488. _this._prepareWorkingCanvas();
  6489. _this._workingCanvas.width = potWidth;
  6490. _this._workingCanvas.height = potHeight;
  6491. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6492. _this._workingContext.imageSmoothingEnabled = false;
  6493. _this._workingContext.mozImageSmoothingEnabled = false;
  6494. _this._workingContext.oImageSmoothingEnabled = false;
  6495. _this._workingContext.webkitImageSmoothingEnabled = false;
  6496. _this._workingContext.msImageSmoothingEnabled = false;
  6497. }
  6498. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6499. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6500. _this._workingContext.imageSmoothingEnabled = true;
  6501. _this._workingContext.mozImageSmoothingEnabled = true;
  6502. _this._workingContext.oImageSmoothingEnabled = true;
  6503. _this._workingContext.webkitImageSmoothingEnabled = true;
  6504. _this._workingContext.msImageSmoothingEnabled = true;
  6505. }
  6506. }
  6507. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6508. if (onLoad) {
  6509. onLoad();
  6510. }
  6511. }, samplingMode);
  6512. };
  6513. if (!(fromData instanceof Array))
  6514. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6515. else
  6516. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6517. }
  6518. return texture;
  6519. };
  6520. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6521. if (compression === void 0) { compression = null; }
  6522. var internalFormat = this._gl.RGBA;
  6523. switch (format) {
  6524. case Engine.TEXTUREFORMAT_ALPHA:
  6525. internalFormat = this._gl.ALPHA;
  6526. break;
  6527. case Engine.TEXTUREFORMAT_LUMINANCE:
  6528. internalFormat = this._gl.LUMINANCE;
  6529. break;
  6530. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6531. internalFormat = this._gl.LUMINANCE_ALPHA;
  6532. break;
  6533. case Engine.TEXTUREFORMAT_RGB:
  6534. internalFormat = this._gl.RGB;
  6535. break;
  6536. case Engine.TEXTUREFORMAT_RGBA:
  6537. internalFormat = this._gl.RGBA;
  6538. break;
  6539. }
  6540. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6541. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6542. if (compression) {
  6543. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6544. }
  6545. else {
  6546. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6547. }
  6548. if (texture.generateMipMaps) {
  6549. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6550. }
  6551. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6552. this._activeTexturesCache = [];
  6553. texture.isReady = true;
  6554. };
  6555. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6556. if (compression === void 0) { compression = null; }
  6557. var texture = this._gl.createTexture();
  6558. texture._baseWidth = width;
  6559. texture._baseHeight = height;
  6560. texture._width = width;
  6561. texture._height = height;
  6562. texture.references = 1;
  6563. this.updateRawTexture(texture, data, format, invertY, compression);
  6564. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6565. // Filters
  6566. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6567. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6569. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6570. texture.samplingMode = samplingMode;
  6571. this._loadedTexturesCache.push(texture);
  6572. return texture;
  6573. };
  6574. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6575. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6576. var texture = this._gl.createTexture();
  6577. texture._baseWidth = width;
  6578. texture._baseHeight = height;
  6579. if (forceExponantOfTwo) {
  6580. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6581. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6582. }
  6583. this._activeTexturesCache = [];
  6584. texture._width = width;
  6585. texture._height = height;
  6586. texture.isReady = false;
  6587. texture.generateMipMaps = generateMipMaps;
  6588. texture.references = 1;
  6589. texture.samplingMode = samplingMode;
  6590. this.updateTextureSamplingMode(samplingMode, texture);
  6591. this._loadedTexturesCache.push(texture);
  6592. return texture;
  6593. };
  6594. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6595. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6599. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6600. };
  6601. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6602. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6603. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6604. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6605. if (texture.generateMipMaps) {
  6606. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6607. }
  6608. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6609. this._activeTexturesCache = [];
  6610. texture.isReady = true;
  6611. };
  6612. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6613. if (texture._isDisabled) {
  6614. return;
  6615. }
  6616. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6617. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6618. try {
  6619. // Testing video texture support
  6620. if (this._videoTextureSupported === undefined) {
  6621. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6622. if (this._gl.getError() !== 0) {
  6623. this._videoTextureSupported = false;
  6624. }
  6625. else {
  6626. this._videoTextureSupported = true;
  6627. }
  6628. }
  6629. // Copy video through the current working canvas if video texture is not supported
  6630. if (!this._videoTextureSupported) {
  6631. if (!texture._workingCanvas) {
  6632. texture._workingCanvas = document.createElement("canvas");
  6633. texture._workingContext = texture._workingCanvas.getContext("2d");
  6634. texture._workingCanvas.width = texture._width;
  6635. texture._workingCanvas.height = texture._height;
  6636. }
  6637. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6638. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6639. }
  6640. else {
  6641. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6642. }
  6643. if (texture.generateMipMaps) {
  6644. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6645. }
  6646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6647. this._activeTexturesCache = [];
  6648. texture.isReady = true;
  6649. }
  6650. catch (ex) {
  6651. // Something unexpected
  6652. // Let's disable the texture
  6653. texture._isDisabled = true;
  6654. }
  6655. };
  6656. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6657. // old version had a "generateMipMaps" arg instead of options.
  6658. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6659. // in the same way, generateDepthBuffer is defaulted to true
  6660. var generateMipMaps = false;
  6661. var generateDepthBuffer = true;
  6662. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6663. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6664. if (options !== undefined) {
  6665. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6666. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6667. type = options.type === undefined ? type : options.type;
  6668. if (options.samplingMode !== undefined) {
  6669. samplingMode = options.samplingMode;
  6670. }
  6671. if (type === Engine.TEXTURETYPE_FLOAT) {
  6672. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6673. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6674. }
  6675. }
  6676. var gl = this._gl;
  6677. var texture = gl.createTexture();
  6678. gl.bindTexture(gl.TEXTURE_2D, texture);
  6679. var width = size.width || size;
  6680. var height = size.height || size;
  6681. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6682. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6683. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6684. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6685. }
  6686. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6688. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6690. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6691. var depthBuffer;
  6692. // Create the depth buffer
  6693. if (generateDepthBuffer) {
  6694. depthBuffer = gl.createRenderbuffer();
  6695. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6696. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6697. }
  6698. // Create the framebuffer
  6699. var framebuffer = gl.createFramebuffer();
  6700. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6701. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6702. if (generateDepthBuffer) {
  6703. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6704. }
  6705. if (generateMipMaps) {
  6706. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6707. }
  6708. // Unbind
  6709. gl.bindTexture(gl.TEXTURE_2D, null);
  6710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6711. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6712. texture._framebuffer = framebuffer;
  6713. if (generateDepthBuffer) {
  6714. texture._depthBuffer = depthBuffer;
  6715. }
  6716. texture._width = width;
  6717. texture._height = height;
  6718. texture.isReady = true;
  6719. texture.generateMipMaps = generateMipMaps;
  6720. texture.references = 1;
  6721. texture.samplingMode = samplingMode;
  6722. this._activeTexturesCache = [];
  6723. this._loadedTexturesCache.push(texture);
  6724. return texture;
  6725. };
  6726. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6727. var _this = this;
  6728. var gl = this._gl;
  6729. var texture = gl.createTexture();
  6730. texture.isCube = true;
  6731. texture.url = rootUrl;
  6732. texture.references = 1;
  6733. this._loadedTexturesCache.push(texture);
  6734. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6735. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6736. if (isDDS) {
  6737. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6738. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6739. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6740. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6741. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6742. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6743. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6744. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6745. }
  6746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6747. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6750. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6751. _this._activeTexturesCache = [];
  6752. texture._width = info.width;
  6753. texture._height = info.height;
  6754. texture.isReady = true;
  6755. }, null, null, true);
  6756. }
  6757. else {
  6758. cascadeLoad(rootUrl, scene, function (imgs) {
  6759. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6760. var height = width;
  6761. _this._prepareWorkingCanvas();
  6762. _this._workingCanvas.width = width;
  6763. _this._workingCanvas.height = height;
  6764. var faces = [
  6765. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6766. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6767. ];
  6768. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6769. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6770. for (var index = 0; index < faces.length; index++) {
  6771. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6772. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6773. }
  6774. if (!noMipmap) {
  6775. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6776. }
  6777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6781. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6782. _this._activeTexturesCache = [];
  6783. texture._width = width;
  6784. texture._height = height;
  6785. texture.isReady = true;
  6786. }, extensions);
  6787. }
  6788. return texture;
  6789. };
  6790. Engine.prototype._releaseTexture = function (texture) {
  6791. var gl = this._gl;
  6792. if (texture._framebuffer) {
  6793. gl.deleteFramebuffer(texture._framebuffer);
  6794. }
  6795. if (texture._depthBuffer) {
  6796. gl.deleteRenderbuffer(texture._depthBuffer);
  6797. }
  6798. gl.deleteTexture(texture);
  6799. // Unbind channels
  6800. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6801. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6802. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6803. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6804. this._activeTexturesCache[channel] = null;
  6805. }
  6806. var index = this._loadedTexturesCache.indexOf(texture);
  6807. if (index !== -1) {
  6808. this._loadedTexturesCache.splice(index, 1);
  6809. }
  6810. };
  6811. Engine.prototype.bindSamplers = function (effect) {
  6812. this._gl.useProgram(effect.getProgram());
  6813. var samplers = effect.getSamplers();
  6814. for (var index = 0; index < samplers.length; index++) {
  6815. var uniform = effect.getUniform(samplers[index]);
  6816. this._gl.uniform1i(uniform, index);
  6817. }
  6818. this._currentEffect = null;
  6819. };
  6820. Engine.prototype._bindTexture = function (channel, texture) {
  6821. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6822. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6823. this._activeTexturesCache[channel] = null;
  6824. };
  6825. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6826. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6827. };
  6828. Engine.prototype.setTexture = function (channel, texture) {
  6829. if (channel < 0) {
  6830. return;
  6831. }
  6832. // Not ready?
  6833. if (!texture || !texture.isReady()) {
  6834. if (this._activeTexturesCache[channel] != null) {
  6835. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6836. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6837. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6838. this._activeTexturesCache[channel] = null;
  6839. }
  6840. return;
  6841. }
  6842. // Video
  6843. if (texture instanceof BABYLON.VideoTexture) {
  6844. if (texture.update()) {
  6845. this._activeTexturesCache[channel] = null;
  6846. }
  6847. }
  6848. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6849. texture.delayLoad();
  6850. return;
  6851. }
  6852. if (this._activeTexturesCache[channel] === texture) {
  6853. return;
  6854. }
  6855. this._activeTexturesCache[channel] = texture;
  6856. var internalTexture = texture.getInternalTexture();
  6857. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6858. if (internalTexture.isCube) {
  6859. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6860. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6861. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6862. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6863. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6864. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6865. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6866. }
  6867. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6868. }
  6869. else {
  6870. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6871. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6872. internalTexture._cachedWrapU = texture.wrapU;
  6873. switch (texture.wrapU) {
  6874. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6876. break;
  6877. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6878. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6879. break;
  6880. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6881. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6882. break;
  6883. }
  6884. }
  6885. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6886. internalTexture._cachedWrapV = texture.wrapV;
  6887. switch (texture.wrapV) {
  6888. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6889. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6890. break;
  6891. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6892. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6893. break;
  6894. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6895. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6896. break;
  6897. }
  6898. }
  6899. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6900. }
  6901. };
  6902. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6903. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6904. var value = texture.anisotropicFilteringLevel;
  6905. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6906. value = 1;
  6907. }
  6908. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6909. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6910. texture._cachedAnisotropicFilteringLevel = value;
  6911. }
  6912. };
  6913. Engine.prototype.readPixels = function (x, y, width, height) {
  6914. var data = new Uint8Array(height * width * 4);
  6915. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6916. return data;
  6917. };
  6918. // Dispose
  6919. Engine.prototype.dispose = function () {
  6920. this.hideLoadingUI();
  6921. this.stopRenderLoop();
  6922. // Release scenes
  6923. while (this.scenes.length) {
  6924. this.scenes[0].dispose();
  6925. }
  6926. // Release audio engine
  6927. Engine.audioEngine.dispose();
  6928. // Release effects
  6929. for (var name in this._compiledEffects) {
  6930. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6931. }
  6932. // Unbind
  6933. for (var i in this._vertexAttribArrays) {
  6934. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6935. continue;
  6936. }
  6937. this._gl.disableVertexAttribArray(i);
  6938. }
  6939. this._gl = null;
  6940. // Events
  6941. window.removeEventListener("blur", this._onBlur);
  6942. window.removeEventListener("focus", this._onFocus);
  6943. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6944. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6945. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6946. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6947. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6948. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6949. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6950. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6951. };
  6952. // Loading screen
  6953. Engine.prototype.displayLoadingUI = function () {
  6954. var _this = this;
  6955. this._loadingDiv = document.createElement("div");
  6956. this._loadingDiv.style.opacity = "0";
  6957. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6958. // Loading text
  6959. this._loadingTextDiv = document.createElement("div");
  6960. this._loadingTextDiv.style.position = "absolute";
  6961. this._loadingTextDiv.style.left = "0";
  6962. this._loadingTextDiv.style.top = "50%";
  6963. this._loadingTextDiv.style.marginTop = "80px";
  6964. this._loadingTextDiv.style.width = "100%";
  6965. this._loadingTextDiv.style.height = "20px";
  6966. this._loadingTextDiv.style.fontFamily = "Arial";
  6967. this._loadingTextDiv.style.fontSize = "14px";
  6968. this._loadingTextDiv.style.color = "white";
  6969. this._loadingTextDiv.style.textAlign = "center";
  6970. this._loadingTextDiv.innerHTML = "Loading";
  6971. this._loadingDiv.appendChild(this._loadingTextDiv);
  6972. // Loading img
  6973. var imgBack = new Image();
  6974. 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==";
  6975. imgBack.style.position = "absolute";
  6976. imgBack.style.left = "50%";
  6977. imgBack.style.top = "50%";
  6978. imgBack.style.marginLeft = "-50px";
  6979. imgBack.style.marginTop = "-50px";
  6980. imgBack.style.transition = "transform 1.0s ease";
  6981. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6982. var deg = 360;
  6983. var onTransitionEnd = function () {
  6984. deg += 360;
  6985. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6986. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6987. };
  6988. imgBack.addEventListener("transitionend", onTransitionEnd);
  6989. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6990. this._loadingDiv.appendChild(imgBack);
  6991. // front image
  6992. var imgFront = new Image();
  6993. 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=";
  6994. imgFront.style.position = "absolute";
  6995. imgFront.style.left = "50%";
  6996. imgFront.style.top = "50%";
  6997. imgFront.style.marginLeft = "-50px";
  6998. imgFront.style.marginTop = "-50px";
  6999. this._loadingDiv.appendChild(imgFront);
  7000. // Resize
  7001. this._resizeLoadingUI = function () {
  7002. var canvasRect = _this.getRenderingCanvasClientRect();
  7003. _this._loadingDiv.style.position = "absolute";
  7004. _this._loadingDiv.style.left = canvasRect.left + "px";
  7005. _this._loadingDiv.style.top = canvasRect.top + "px";
  7006. _this._loadingDiv.style.width = canvasRect.width + "px";
  7007. _this._loadingDiv.style.height = canvasRect.height + "px";
  7008. };
  7009. this._resizeLoadingUI();
  7010. window.addEventListener("resize", this._resizeLoadingUI);
  7011. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  7012. document.body.appendChild(this._loadingDiv);
  7013. setTimeout(function () {
  7014. _this._loadingDiv.style.opacity = "1";
  7015. imgBack.style.transform = "rotateZ(360deg)";
  7016. imgBack.style.webkitTransform = "rotateZ(360deg)";
  7017. }, 0);
  7018. };
  7019. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7020. set: function (text) {
  7021. if (!this._loadingDiv) {
  7022. return;
  7023. }
  7024. this._loadingTextDiv.innerHTML = text;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7030. get: function () {
  7031. return this._loadingDivBackgroundColor;
  7032. },
  7033. set: function (color) {
  7034. this._loadingDivBackgroundColor = color;
  7035. if (!this._loadingDiv) {
  7036. return;
  7037. }
  7038. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  7039. },
  7040. enumerable: true,
  7041. configurable: true
  7042. });
  7043. Engine.prototype.hideLoadingUI = function () {
  7044. var _this = this;
  7045. if (!this._loadingDiv) {
  7046. return;
  7047. }
  7048. var onTransitionEnd = function () {
  7049. if (!_this._loadingDiv) {
  7050. return;
  7051. }
  7052. document.body.removeChild(_this._loadingDiv);
  7053. window.removeEventListener("resize", _this._resizeLoadingUI);
  7054. _this._loadingDiv = null;
  7055. };
  7056. this._loadingDiv.style.opacity = "0";
  7057. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7058. };
  7059. // FPS
  7060. Engine.prototype.getFps = function () {
  7061. return this.fps;
  7062. };
  7063. Engine.prototype.getDeltaTime = function () {
  7064. return this.deltaTime;
  7065. };
  7066. Engine.prototype._measureFps = function () {
  7067. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7068. var length = this.previousFramesDuration.length;
  7069. if (length >= 2) {
  7070. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7071. }
  7072. if (length >= this.fpsRange) {
  7073. if (length > this.fpsRange) {
  7074. this.previousFramesDuration.splice(0, 1);
  7075. length = this.previousFramesDuration.length;
  7076. }
  7077. var sum = 0;
  7078. for (var id = 0; id < length - 1; id++) {
  7079. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7080. }
  7081. this.fps = 1000.0 / (sum / (length - 1));
  7082. }
  7083. };
  7084. // Statics
  7085. Engine.isSupported = function () {
  7086. try {
  7087. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7088. if (navigator.isCocoonJS) {
  7089. return true;
  7090. }
  7091. var tempcanvas = document.createElement("canvas");
  7092. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7093. return gl != null && !!window.WebGLRenderingContext;
  7094. }
  7095. catch (e) {
  7096. return false;
  7097. }
  7098. };
  7099. // Const statics
  7100. Engine._ALPHA_DISABLE = 0;
  7101. Engine._ALPHA_ADD = 1;
  7102. Engine._ALPHA_COMBINE = 2;
  7103. Engine._ALPHA_SUBTRACT = 3;
  7104. Engine._ALPHA_MULTIPLY = 4;
  7105. Engine._ALPHA_MAXIMIZED = 5;
  7106. Engine._ALPHA_ONEONE = 6;
  7107. Engine._DELAYLOADSTATE_NONE = 0;
  7108. Engine._DELAYLOADSTATE_LOADED = 1;
  7109. Engine._DELAYLOADSTATE_LOADING = 2;
  7110. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7111. Engine._TEXTUREFORMAT_ALPHA = 0;
  7112. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7113. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7114. Engine._TEXTUREFORMAT_RGB = 4;
  7115. Engine._TEXTUREFORMAT_RGBA = 5;
  7116. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7117. Engine._TEXTURETYPE_FLOAT = 1;
  7118. // Updatable statics so stick with vars here
  7119. Engine.Epsilon = 0.001;
  7120. Engine.CollisionsEpsilon = 0.001;
  7121. Engine.CodeRepository = "src/";
  7122. Engine.ShadersRepository = "src/Shaders/";
  7123. return Engine;
  7124. })();
  7125. BABYLON.Engine = Engine;
  7126. })(BABYLON || (BABYLON = {}));
  7127. var BABYLON;
  7128. (function (BABYLON) {
  7129. /**
  7130. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7131. */
  7132. var Node = (function () {
  7133. /**
  7134. * @constructor
  7135. * @param {string} name - the name and id to be given to this node
  7136. * @param {BABYLON.Scene} the scene this node will be added to
  7137. */
  7138. function Node(name, scene) {
  7139. this.state = "";
  7140. this.animations = new Array();
  7141. this._childrenFlag = -1;
  7142. this._isEnabled = true;
  7143. this._isReady = true;
  7144. this._currentRenderId = -1;
  7145. this._parentRenderId = -1;
  7146. this.name = name;
  7147. this.id = name;
  7148. this._scene = scene;
  7149. this._initCache();
  7150. }
  7151. Node.prototype.getScene = function () {
  7152. return this._scene;
  7153. };
  7154. Node.prototype.getEngine = function () {
  7155. return this._scene.getEngine();
  7156. };
  7157. // override it in derived class
  7158. Node.prototype.getWorldMatrix = function () {
  7159. return BABYLON.Matrix.Identity();
  7160. };
  7161. // override it in derived class if you add new variables to the cache
  7162. // and call the parent class method
  7163. Node.prototype._initCache = function () {
  7164. this._cache = {};
  7165. this._cache.parent = undefined;
  7166. };
  7167. Node.prototype.updateCache = function (force) {
  7168. if (!force && this.isSynchronized())
  7169. return;
  7170. this._cache.parent = this.parent;
  7171. this._updateCache();
  7172. };
  7173. // override it in derived class if you add new variables to the cache
  7174. // and call the parent class method if !ignoreParentClass
  7175. Node.prototype._updateCache = function (ignoreParentClass) {
  7176. };
  7177. // override it in derived class if you add new variables to the cache
  7178. Node.prototype._isSynchronized = function () {
  7179. return true;
  7180. };
  7181. Node.prototype._markSyncedWithParent = function () {
  7182. this._parentRenderId = this.parent._currentRenderId;
  7183. };
  7184. Node.prototype.isSynchronizedWithParent = function () {
  7185. if (!this.parent) {
  7186. return true;
  7187. }
  7188. if (this._parentRenderId !== this.parent._currentRenderId) {
  7189. return false;
  7190. }
  7191. return this.parent.isSynchronized();
  7192. };
  7193. Node.prototype.isSynchronized = function (updateCache) {
  7194. var check = this.hasNewParent();
  7195. check = check || !this.isSynchronizedWithParent();
  7196. check = check || !this._isSynchronized();
  7197. if (updateCache)
  7198. this.updateCache(true);
  7199. return !check;
  7200. };
  7201. Node.prototype.hasNewParent = function (update) {
  7202. if (this._cache.parent === this.parent)
  7203. return false;
  7204. if (update)
  7205. this._cache.parent = this.parent;
  7206. return true;
  7207. };
  7208. /**
  7209. * Is this node ready to be used/rendered
  7210. * @return {boolean} is it ready
  7211. */
  7212. Node.prototype.isReady = function () {
  7213. return this._isReady;
  7214. };
  7215. /**
  7216. * Is this node enabled.
  7217. * If the node has a parent and is enabled, the parent will be inspected as well.
  7218. * @return {boolean} whether this node (and its parent) is enabled.
  7219. * @see setEnabled
  7220. */
  7221. Node.prototype.isEnabled = function () {
  7222. if (!this._isEnabled) {
  7223. return false;
  7224. }
  7225. if (this.parent) {
  7226. return this.parent.isEnabled();
  7227. }
  7228. return true;
  7229. };
  7230. /**
  7231. * Set the enabled state of this node.
  7232. * @param {boolean} value - the new enabled state
  7233. * @see isEnabled
  7234. */
  7235. Node.prototype.setEnabled = function (value) {
  7236. this._isEnabled = value;
  7237. };
  7238. /**
  7239. * Is this node a descendant of the given node.
  7240. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7241. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7242. * @see parent
  7243. */
  7244. Node.prototype.isDescendantOf = function (ancestor) {
  7245. if (this.parent) {
  7246. if (this.parent === ancestor) {
  7247. return true;
  7248. }
  7249. return this.parent.isDescendantOf(ancestor);
  7250. }
  7251. return false;
  7252. };
  7253. Node.prototype._getDescendants = function (list, results) {
  7254. for (var index = 0; index < list.length; index++) {
  7255. var item = list[index];
  7256. if (item.isDescendantOf(this)) {
  7257. results.push(item);
  7258. }
  7259. }
  7260. };
  7261. /**
  7262. * Will return all nodes that have this node as parent.
  7263. * @return {BABYLON.Node[]} all children nodes of all types.
  7264. */
  7265. Node.prototype.getDescendants = function () {
  7266. var results = [];
  7267. this._getDescendants(this._scene.meshes, results);
  7268. this._getDescendants(this._scene.lights, results);
  7269. this._getDescendants(this._scene.cameras, results);
  7270. return results;
  7271. };
  7272. Node.prototype._setReady = function (state) {
  7273. if (state == this._isReady) {
  7274. return;
  7275. }
  7276. if (!state) {
  7277. this._isReady = false;
  7278. return;
  7279. }
  7280. this._isReady = true;
  7281. if (this.onReady) {
  7282. this.onReady(this);
  7283. }
  7284. };
  7285. return Node;
  7286. })();
  7287. BABYLON.Node = Node;
  7288. })(BABYLON || (BABYLON = {}));
  7289. var BABYLON;
  7290. (function (BABYLON) {
  7291. var FilesInput = (function () {
  7292. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7293. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7294. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7295. this._engine = p_engine;
  7296. this._canvas = p_canvas;
  7297. this._currentScene = p_scene;
  7298. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7299. this._progressCallback = p_progressCallback;
  7300. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7301. this._textureLoadingCallback = p_textureLoadingCallback;
  7302. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7303. }
  7304. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7305. var _this = this;
  7306. if (p_elementToMonitor) {
  7307. this._elementToMonitor = p_elementToMonitor;
  7308. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7309. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7310. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7311. }
  7312. };
  7313. FilesInput.prototype.renderFunction = function () {
  7314. if (this._additionnalRenderLoopLogicCallback) {
  7315. this._additionnalRenderLoopLogicCallback();
  7316. }
  7317. if (this._currentScene) {
  7318. if (this._textureLoadingCallback) {
  7319. var remaining = this._currentScene.getWaitingItemsCount();
  7320. if (remaining > 0) {
  7321. this._textureLoadingCallback(remaining);
  7322. }
  7323. }
  7324. this._currentScene.render();
  7325. }
  7326. };
  7327. FilesInput.prototype.drag = function (e) {
  7328. e.stopPropagation();
  7329. e.preventDefault();
  7330. };
  7331. FilesInput.prototype.drop = function (eventDrop) {
  7332. eventDrop.stopPropagation();
  7333. eventDrop.preventDefault();
  7334. this.loadFiles(eventDrop);
  7335. };
  7336. FilesInput.prototype.loadFiles = function (event) {
  7337. if (this._startingProcessingFilesCallback)
  7338. this._startingProcessingFilesCallback();
  7339. // Handling data transfer via drag'n'drop
  7340. if (event && event.dataTransfer && event.dataTransfer.files) {
  7341. this._filesToLoad = event.dataTransfer.files;
  7342. }
  7343. // Handling files from input files
  7344. if (event && event.target && event.target.files) {
  7345. this._filesToLoad = event.target.files;
  7346. }
  7347. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7348. for (var i = 0; i < this._filesToLoad.length; i++) {
  7349. switch (this._filesToLoad[i].type) {
  7350. case "image/jpeg":
  7351. case "image/png":
  7352. case "image/bmp":
  7353. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7354. break;
  7355. case "image/targa":
  7356. case "image/vnd.ms-dds":
  7357. case "audio/wav":
  7358. case "audio/x-wav":
  7359. case "audio/mp3":
  7360. case "audio/mpeg":
  7361. case "audio/mpeg3":
  7362. case "audio/x-mpeg-3":
  7363. case "audio/ogg":
  7364. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7365. break;
  7366. default:
  7367. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7368. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7369. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7370. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7371. this._sceneFileToLoad = this._filesToLoad[i];
  7372. }
  7373. break;
  7374. }
  7375. }
  7376. this.reload();
  7377. }
  7378. };
  7379. FilesInput.prototype.reload = function () {
  7380. var _this = this;
  7381. var that = this;
  7382. // If a ".babylon" file has been provided
  7383. if (this._sceneFileToLoad) {
  7384. if (this._currentScene) {
  7385. if (BABYLON.Tools.errorsCount > 0) {
  7386. BABYLON.Tools.ClearLogCache();
  7387. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7388. }
  7389. this._engine.stopRenderLoop();
  7390. this._currentScene.dispose();
  7391. }
  7392. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7393. that._currentScene = newScene;
  7394. // Wait for textures and shaders to be ready
  7395. that._currentScene.executeWhenReady(function () {
  7396. // Attach camera to canvas inputs
  7397. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7398. that._currentScene.createDefaultCameraOrLight();
  7399. }
  7400. that._currentScene.activeCamera.attachControl(that._canvas);
  7401. if (that._sceneLoadedCallback) {
  7402. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7403. }
  7404. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7405. });
  7406. }, function (progress) {
  7407. if (_this._progressCallback) {
  7408. _this._progressCallback(progress);
  7409. }
  7410. });
  7411. }
  7412. else {
  7413. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7414. }
  7415. };
  7416. FilesInput.FilesTextures = new Array();
  7417. FilesInput.FilesToLoad = new Array();
  7418. return FilesInput;
  7419. })();
  7420. BABYLON.FilesInput = FilesInput;
  7421. })(BABYLON || (BABYLON = {}));
  7422. var BABYLON;
  7423. (function (BABYLON) {
  7424. var IntersectionInfo = (function () {
  7425. function IntersectionInfo(bu, bv, distance) {
  7426. this.bu = bu;
  7427. this.bv = bv;
  7428. this.distance = distance;
  7429. this.faceId = 0;
  7430. this.subMeshId = 0;
  7431. }
  7432. return IntersectionInfo;
  7433. })();
  7434. BABYLON.IntersectionInfo = IntersectionInfo;
  7435. var PickingInfo = (function () {
  7436. function PickingInfo() {
  7437. this.hit = false;
  7438. this.distance = 0;
  7439. this.pickedPoint = null;
  7440. this.pickedMesh = null;
  7441. this.bu = 0;
  7442. this.bv = 0;
  7443. this.faceId = -1;
  7444. this.subMeshId = 0;
  7445. }
  7446. // Methods
  7447. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7448. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7449. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7450. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7451. return null;
  7452. }
  7453. var indices = this.pickedMesh.getIndices();
  7454. var result;
  7455. if (useVerticesNormals) {
  7456. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7457. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7458. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7459. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7460. normal0 = normal0.scale(this.bu);
  7461. normal1 = normal1.scale(this.bv);
  7462. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7463. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7464. }
  7465. else {
  7466. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7467. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7468. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7469. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7470. var p1p2 = vertex1.subtract(vertex2);
  7471. var p3p2 = vertex3.subtract(vertex2);
  7472. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7473. }
  7474. if (useWorldCoordinates) {
  7475. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7476. }
  7477. return BABYLON.Vector3.Normalize(result);
  7478. };
  7479. PickingInfo.prototype.getTextureCoordinates = function () {
  7480. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7481. return null;
  7482. }
  7483. var indices = this.pickedMesh.getIndices();
  7484. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7485. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7486. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7487. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7488. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7489. uv1 = uv1.scale(this.bu);
  7490. uv2 = uv2.scale(this.bv);
  7491. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7492. };
  7493. return PickingInfo;
  7494. })();
  7495. BABYLON.PickingInfo = PickingInfo;
  7496. })(BABYLON || (BABYLON = {}));
  7497. var BABYLON;
  7498. (function (BABYLON) {
  7499. var BoundingSphere = (function () {
  7500. function BoundingSphere(minimum, maximum) {
  7501. this.minimum = minimum;
  7502. this.maximum = maximum;
  7503. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7504. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7505. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7506. this.radius = distance * 0.5;
  7507. this.centerWorld = BABYLON.Vector3.Zero();
  7508. this._update(BABYLON.Matrix.Identity());
  7509. }
  7510. // Methods
  7511. BoundingSphere.prototype._update = function (world) {
  7512. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7513. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7514. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7515. };
  7516. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7517. for (var i = 0; i < 6; i++) {
  7518. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7519. return false;
  7520. }
  7521. return true;
  7522. };
  7523. BoundingSphere.prototype.intersectsPoint = function (point) {
  7524. var x = this.centerWorld.x - point.x;
  7525. var y = this.centerWorld.y - point.y;
  7526. var z = this.centerWorld.z - point.z;
  7527. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7528. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7529. return false;
  7530. return true;
  7531. };
  7532. // Statics
  7533. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7534. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7535. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7536. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7537. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7538. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7539. return false;
  7540. return true;
  7541. };
  7542. return BoundingSphere;
  7543. })();
  7544. BABYLON.BoundingSphere = BoundingSphere;
  7545. })(BABYLON || (BABYLON = {}));
  7546. var BABYLON;
  7547. (function (BABYLON) {
  7548. var BoundingBox = (function () {
  7549. function BoundingBox(minimum, maximum) {
  7550. this.minimum = minimum;
  7551. this.maximum = maximum;
  7552. this.vectors = new Array();
  7553. this.vectorsWorld = new Array();
  7554. // Bounding vectors
  7555. this.vectors.push(this.minimum.clone());
  7556. this.vectors.push(this.maximum.clone());
  7557. this.vectors.push(this.minimum.clone());
  7558. this.vectors[2].x = this.maximum.x;
  7559. this.vectors.push(this.minimum.clone());
  7560. this.vectors[3].y = this.maximum.y;
  7561. this.vectors.push(this.minimum.clone());
  7562. this.vectors[4].z = this.maximum.z;
  7563. this.vectors.push(this.maximum.clone());
  7564. this.vectors[5].z = this.minimum.z;
  7565. this.vectors.push(this.maximum.clone());
  7566. this.vectors[6].x = this.minimum.x;
  7567. this.vectors.push(this.maximum.clone());
  7568. this.vectors[7].y = this.minimum.y;
  7569. // OBB
  7570. this.center = this.maximum.add(this.minimum).scale(0.5);
  7571. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7572. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7573. // World
  7574. for (var index = 0; index < this.vectors.length; index++) {
  7575. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7576. }
  7577. this.minimumWorld = BABYLON.Vector3.Zero();
  7578. this.maximumWorld = BABYLON.Vector3.Zero();
  7579. this._update(BABYLON.Matrix.Identity());
  7580. }
  7581. // Methods
  7582. BoundingBox.prototype.getWorldMatrix = function () {
  7583. return this._worldMatrix;
  7584. };
  7585. BoundingBox.prototype._update = function (world) {
  7586. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7587. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7588. for (var index = 0; index < this.vectors.length; index++) {
  7589. var v = this.vectorsWorld[index];
  7590. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7591. if (v.x < this.minimumWorld.x)
  7592. this.minimumWorld.x = v.x;
  7593. if (v.y < this.minimumWorld.y)
  7594. this.minimumWorld.y = v.y;
  7595. if (v.z < this.minimumWorld.z)
  7596. this.minimumWorld.z = v.z;
  7597. if (v.x > this.maximumWorld.x)
  7598. this.maximumWorld.x = v.x;
  7599. if (v.y > this.maximumWorld.y)
  7600. this.maximumWorld.y = v.y;
  7601. if (v.z > this.maximumWorld.z)
  7602. this.maximumWorld.z = v.z;
  7603. }
  7604. // OBB
  7605. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7606. this.center.scaleInPlace(0.5);
  7607. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7608. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7609. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7610. this._worldMatrix = world;
  7611. };
  7612. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7613. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7614. };
  7615. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7616. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7617. };
  7618. BoundingBox.prototype.intersectsPoint = function (point) {
  7619. var delta = -BABYLON.Engine.Epsilon;
  7620. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7621. return false;
  7622. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7623. return false;
  7624. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7625. return false;
  7626. return true;
  7627. };
  7628. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7629. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7630. };
  7631. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7632. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7633. return false;
  7634. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7635. return false;
  7636. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7637. return false;
  7638. return true;
  7639. };
  7640. // Statics
  7641. BoundingBox.Intersects = function (box0, box1) {
  7642. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7643. return false;
  7644. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7645. return false;
  7646. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7647. return false;
  7648. return true;
  7649. };
  7650. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7651. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7652. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7653. return (num <= (sphereRadius * sphereRadius));
  7654. };
  7655. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7656. for (var p = 0; p < 6; p++) {
  7657. for (var i = 0; i < 8; i++) {
  7658. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7659. return false;
  7660. }
  7661. }
  7662. }
  7663. return true;
  7664. };
  7665. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7666. for (var p = 0; p < 6; p++) {
  7667. var inCount = 8;
  7668. for (var i = 0; i < 8; i++) {
  7669. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7670. --inCount;
  7671. }
  7672. else {
  7673. break;
  7674. }
  7675. }
  7676. if (inCount === 0)
  7677. return false;
  7678. }
  7679. return true;
  7680. };
  7681. return BoundingBox;
  7682. })();
  7683. BABYLON.BoundingBox = BoundingBox;
  7684. })(BABYLON || (BABYLON = {}));
  7685. var BABYLON;
  7686. (function (BABYLON) {
  7687. var computeBoxExtents = function (axis, box) {
  7688. var p = BABYLON.Vector3.Dot(box.center, axis);
  7689. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7690. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7691. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7692. var r = r0 + r1 + r2;
  7693. return {
  7694. min: p - r,
  7695. max: p + r
  7696. };
  7697. };
  7698. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7699. var axisOverlap = function (axis, box0, box1) {
  7700. var result0 = computeBoxExtents(axis, box0);
  7701. var result1 = computeBoxExtents(axis, box1);
  7702. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7703. };
  7704. var BoundingInfo = (function () {
  7705. function BoundingInfo(minimum, maximum) {
  7706. this.minimum = minimum;
  7707. this.maximum = maximum;
  7708. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7709. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7710. }
  7711. // Methods
  7712. BoundingInfo.prototype._update = function (world) {
  7713. this.boundingBox._update(world);
  7714. this.boundingSphere._update(world);
  7715. };
  7716. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7717. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7718. return false;
  7719. return this.boundingBox.isInFrustum(frustumPlanes);
  7720. };
  7721. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7722. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7723. };
  7724. BoundingInfo.prototype._checkCollision = function (collider) {
  7725. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7726. };
  7727. BoundingInfo.prototype.intersectsPoint = function (point) {
  7728. if (!this.boundingSphere.centerWorld) {
  7729. return false;
  7730. }
  7731. if (!this.boundingSphere.intersectsPoint(point)) {
  7732. return false;
  7733. }
  7734. if (!this.boundingBox.intersectsPoint(point)) {
  7735. return false;
  7736. }
  7737. return true;
  7738. };
  7739. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7740. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7741. return false;
  7742. }
  7743. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7744. return false;
  7745. }
  7746. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7747. return false;
  7748. }
  7749. if (!precise) {
  7750. return true;
  7751. }
  7752. var box0 = this.boundingBox;
  7753. var box1 = boundingInfo.boundingBox;
  7754. if (!axisOverlap(box0.directions[0], box0, box1))
  7755. return false;
  7756. if (!axisOverlap(box0.directions[1], box0, box1))
  7757. return false;
  7758. if (!axisOverlap(box0.directions[2], box0, box1))
  7759. return false;
  7760. if (!axisOverlap(box1.directions[0], box0, box1))
  7761. return false;
  7762. if (!axisOverlap(box1.directions[1], box0, box1))
  7763. return false;
  7764. if (!axisOverlap(box1.directions[2], box0, box1))
  7765. return false;
  7766. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7767. return false;
  7768. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7769. return false;
  7770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7771. return false;
  7772. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7773. return false;
  7774. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7775. return false;
  7776. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7777. return false;
  7778. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7779. return false;
  7780. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7781. return false;
  7782. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7783. return false;
  7784. return true;
  7785. };
  7786. return BoundingInfo;
  7787. })();
  7788. BABYLON.BoundingInfo = BoundingInfo;
  7789. })(BABYLON || (BABYLON = {}));
  7790. var BABYLON;
  7791. (function (BABYLON) {
  7792. var AbstractMesh = (function (_super) {
  7793. __extends(AbstractMesh, _super);
  7794. function AbstractMesh(name, scene) {
  7795. var _this = this;
  7796. _super.call(this, name, scene);
  7797. // Properties
  7798. this.definedFacingForward = true; // orientation for POV movement & rotation
  7799. this.position = new BABYLON.Vector3(0, 0, 0);
  7800. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7801. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7802. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7803. this.visibility = 1.0;
  7804. this.alphaIndex = Number.MAX_VALUE;
  7805. this.infiniteDistance = false;
  7806. this.isVisible = true;
  7807. this.isPickable = true;
  7808. this.showBoundingBox = false;
  7809. this.showSubMeshesBoundingBox = false;
  7810. this.onDispose = null;
  7811. this.isBlocker = false;
  7812. this.renderingGroupId = 0;
  7813. this.receiveShadows = false;
  7814. this.renderOutline = false;
  7815. this.outlineColor = BABYLON.Color3.Red();
  7816. this.outlineWidth = 0.02;
  7817. this.renderOverlay = false;
  7818. this.overlayColor = BABYLON.Color3.Red();
  7819. this.overlayAlpha = 0.5;
  7820. this.hasVertexAlpha = false;
  7821. this.useVertexColors = true;
  7822. this.applyFog = true;
  7823. this.computeBonesUsingShaders = true;
  7824. this.scalingDeterminant = 1;
  7825. this.useOctreeForRenderingSelection = true;
  7826. this.useOctreeForPicking = true;
  7827. this.useOctreeForCollisions = true;
  7828. this.layerMask = 0x0FFFFFFF;
  7829. this.alwaysSelectAsActiveMesh = false;
  7830. // Physics
  7831. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7832. // Collisions
  7833. this._checkCollisions = false;
  7834. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7835. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7836. this._collider = new BABYLON.Collider();
  7837. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7838. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7839. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7840. // Edges
  7841. this.edgesWidth = 1;
  7842. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7843. // Cache
  7844. this._localScaling = BABYLON.Matrix.Zero();
  7845. this._localRotation = BABYLON.Matrix.Zero();
  7846. this._localTranslation = BABYLON.Matrix.Zero();
  7847. this._localBillboard = BABYLON.Matrix.Zero();
  7848. this._localPivotScaling = BABYLON.Matrix.Zero();
  7849. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7850. this._localWorld = BABYLON.Matrix.Zero();
  7851. this._worldMatrix = BABYLON.Matrix.Zero();
  7852. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7853. this._absolutePosition = BABYLON.Vector3.Zero();
  7854. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7855. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7856. this._isDirty = false;
  7857. this._pivotMatrix = BABYLON.Matrix.Identity();
  7858. this._isDisposed = false;
  7859. this._renderId = 0;
  7860. this._intersectionsInProgress = new Array();
  7861. this._onAfterWorldMatrixUpdate = new Array();
  7862. this._isWorldMatrixFrozen = false;
  7863. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7864. if (collidedMesh === void 0) { collidedMesh = null; }
  7865. //TODO move this to the collision coordinator!
  7866. if (_this.getScene().workerCollisions)
  7867. newPosition.multiplyInPlace(_this._collider.radius);
  7868. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7869. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7870. _this.position.addInPlace(_this._diffPositionForCollisions);
  7871. }
  7872. if (_this.onCollide && collidedMesh) {
  7873. _this.onCollide(collidedMesh);
  7874. }
  7875. };
  7876. scene.addMesh(this);
  7877. }
  7878. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7879. get: function () {
  7880. return AbstractMesh._BILLBOARDMODE_NONE;
  7881. },
  7882. enumerable: true,
  7883. configurable: true
  7884. });
  7885. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7886. get: function () {
  7887. return AbstractMesh._BILLBOARDMODE_X;
  7888. },
  7889. enumerable: true,
  7890. configurable: true
  7891. });
  7892. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7893. get: function () {
  7894. return AbstractMesh._BILLBOARDMODE_Y;
  7895. },
  7896. enumerable: true,
  7897. configurable: true
  7898. });
  7899. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7900. get: function () {
  7901. return AbstractMesh._BILLBOARDMODE_Z;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7907. get: function () {
  7908. return AbstractMesh._BILLBOARDMODE_ALL;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. // Methods
  7914. AbstractMesh.prototype.disableEdgesRendering = function () {
  7915. if (this._edgesRenderer !== undefined) {
  7916. this._edgesRenderer.dispose();
  7917. this._edgesRenderer = undefined;
  7918. }
  7919. };
  7920. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7921. if (epsilon === void 0) { epsilon = 0.95; }
  7922. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7923. this.disableEdgesRendering();
  7924. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7925. };
  7926. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7927. get: function () {
  7928. return false;
  7929. },
  7930. enumerable: true,
  7931. configurable: true
  7932. });
  7933. AbstractMesh.prototype.getLOD = function (camera) {
  7934. return this;
  7935. };
  7936. AbstractMesh.prototype.getTotalVertices = function () {
  7937. return 0;
  7938. };
  7939. AbstractMesh.prototype.getIndices = function () {
  7940. return null;
  7941. };
  7942. AbstractMesh.prototype.getVerticesData = function (kind) {
  7943. return null;
  7944. };
  7945. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7946. return false;
  7947. };
  7948. AbstractMesh.prototype.getBoundingInfo = function () {
  7949. if (this._masterMesh) {
  7950. return this._masterMesh.getBoundingInfo();
  7951. }
  7952. if (!this._boundingInfo) {
  7953. this._updateBoundingInfo();
  7954. }
  7955. return this._boundingInfo;
  7956. };
  7957. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7958. get: function () {
  7959. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7960. },
  7961. enumerable: true,
  7962. configurable: true
  7963. });
  7964. AbstractMesh.prototype._preActivate = function () {
  7965. };
  7966. AbstractMesh.prototype._activate = function (renderId) {
  7967. this._renderId = renderId;
  7968. };
  7969. AbstractMesh.prototype.getWorldMatrix = function () {
  7970. if (this._masterMesh) {
  7971. return this._masterMesh.getWorldMatrix();
  7972. }
  7973. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7974. this.computeWorldMatrix();
  7975. }
  7976. return this._worldMatrix;
  7977. };
  7978. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7979. get: function () {
  7980. return this._worldMatrix;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7986. get: function () {
  7987. return this._absolutePosition;
  7988. },
  7989. enumerable: true,
  7990. configurable: true
  7991. });
  7992. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7993. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7994. this.computeWorldMatrix(true);
  7995. this._isWorldMatrixFrozen = true;
  7996. };
  7997. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7998. this._isWorldMatrixFrozen = false;
  7999. this.computeWorldMatrix(true);
  8000. };
  8001. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8002. get: function () {
  8003. return this._isWorldMatrixFrozen;
  8004. },
  8005. enumerable: true,
  8006. configurable: true
  8007. });
  8008. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8009. axis.normalize();
  8010. if (!this.rotationQuaternion) {
  8011. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8012. this.rotation = BABYLON.Vector3.Zero();
  8013. }
  8014. var rotationQuaternion;
  8015. if (!space || space === BABYLON.Space.LOCAL) {
  8016. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8017. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8018. }
  8019. else {
  8020. if (this.parent) {
  8021. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8022. invertParentWorldMatrix.invert();
  8023. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8024. }
  8025. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8026. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8027. }
  8028. };
  8029. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8030. var displacementVector = axis.scale(distance);
  8031. if (!space || space === BABYLON.Space.LOCAL) {
  8032. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8033. this.setPositionWithLocalVector(tempV3);
  8034. }
  8035. else {
  8036. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8037. }
  8038. };
  8039. AbstractMesh.prototype.getAbsolutePosition = function () {
  8040. this.computeWorldMatrix();
  8041. return this._absolutePosition;
  8042. };
  8043. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8044. if (!absolutePosition) {
  8045. return;
  8046. }
  8047. var absolutePositionX;
  8048. var absolutePositionY;
  8049. var absolutePositionZ;
  8050. if (absolutePosition.x === undefined) {
  8051. if (arguments.length < 3) {
  8052. return;
  8053. }
  8054. absolutePositionX = arguments[0];
  8055. absolutePositionY = arguments[1];
  8056. absolutePositionZ = arguments[2];
  8057. }
  8058. else {
  8059. absolutePositionX = absolutePosition.x;
  8060. absolutePositionY = absolutePosition.y;
  8061. absolutePositionZ = absolutePosition.z;
  8062. }
  8063. if (this.parent) {
  8064. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8065. invertParentWorldMatrix.invert();
  8066. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8067. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8068. }
  8069. else {
  8070. this.position.x = absolutePositionX;
  8071. this.position.y = absolutePositionY;
  8072. this.position.z = absolutePositionZ;
  8073. }
  8074. };
  8075. // ================================== Point of View Movement =================================
  8076. /**
  8077. * Perform relative position change from the point of view of behind the front of the mesh.
  8078. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8079. * Supports definition of mesh facing forward or backward.
  8080. * @param {number} amountRight
  8081. * @param {number} amountUp
  8082. * @param {number} amountForward
  8083. */
  8084. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8085. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8086. };
  8087. /**
  8088. * Calculate relative position change from the point of view of behind the front of the mesh.
  8089. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8090. * Supports definition of mesh facing forward or backward.
  8091. * @param {number} amountRight
  8092. * @param {number} amountUp
  8093. * @param {number} amountForward
  8094. */
  8095. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8096. var rotMatrix = new BABYLON.Matrix();
  8097. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8098. rotQuaternion.toRotationMatrix(rotMatrix);
  8099. var translationDelta = BABYLON.Vector3.Zero();
  8100. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8102. return translationDelta;
  8103. };
  8104. // ================================== Point of View Rotation =================================
  8105. /**
  8106. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8107. * Supports definition of mesh facing forward or backward.
  8108. * @param {number} flipBack
  8109. * @param {number} twirlClockwise
  8110. * @param {number} tiltRight
  8111. */
  8112. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8113. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8114. };
  8115. /**
  8116. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8117. * Supports definition of mesh facing forward or backward.
  8118. * @param {number} flipBack
  8119. * @param {number} twirlClockwise
  8120. * @param {number} tiltRight
  8121. */
  8122. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8123. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8124. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8125. };
  8126. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8127. this._pivotMatrix = matrix;
  8128. this._cache.pivotMatrixUpdated = true;
  8129. };
  8130. AbstractMesh.prototype.getPivotMatrix = function () {
  8131. return this._pivotMatrix;
  8132. };
  8133. AbstractMesh.prototype._isSynchronized = function () {
  8134. if (this._isDirty) {
  8135. return false;
  8136. }
  8137. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8138. return false;
  8139. if (this._cache.pivotMatrixUpdated) {
  8140. return false;
  8141. }
  8142. if (this.infiniteDistance) {
  8143. return false;
  8144. }
  8145. if (!this._cache.position.equals(this.position))
  8146. return false;
  8147. if (this.rotationQuaternion) {
  8148. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8149. return false;
  8150. }
  8151. else {
  8152. if (!this._cache.rotation.equals(this.rotation))
  8153. return false;
  8154. }
  8155. if (!this._cache.scaling.equals(this.scaling))
  8156. return false;
  8157. return true;
  8158. };
  8159. AbstractMesh.prototype._initCache = function () {
  8160. _super.prototype._initCache.call(this);
  8161. this._cache.localMatrixUpdated = false;
  8162. this._cache.position = BABYLON.Vector3.Zero();
  8163. this._cache.scaling = BABYLON.Vector3.Zero();
  8164. this._cache.rotation = BABYLON.Vector3.Zero();
  8165. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8166. };
  8167. AbstractMesh.prototype.markAsDirty = function (property) {
  8168. if (property === "rotation") {
  8169. this.rotationQuaternion = null;
  8170. }
  8171. this._currentRenderId = Number.MAX_VALUE;
  8172. this._isDirty = true;
  8173. };
  8174. AbstractMesh.prototype._updateBoundingInfo = function () {
  8175. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8176. this._boundingInfo._update(this.worldMatrixFromCache);
  8177. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8178. };
  8179. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8180. if (!this.subMeshes) {
  8181. return;
  8182. }
  8183. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8184. var subMesh = this.subMeshes[subIndex];
  8185. subMesh.updateBoundingInfo(matrix);
  8186. }
  8187. };
  8188. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8189. if (this._isWorldMatrixFrozen) {
  8190. return this._worldMatrix;
  8191. }
  8192. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8193. return this._worldMatrix;
  8194. }
  8195. this._cache.position.copyFrom(this.position);
  8196. this._cache.scaling.copyFrom(this.scaling);
  8197. this._cache.pivotMatrixUpdated = false;
  8198. this._currentRenderId = this.getScene().getRenderId();
  8199. this._isDirty = false;
  8200. // Scaling
  8201. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8202. // Rotation
  8203. if (this.rotationQuaternion) {
  8204. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8205. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8206. }
  8207. else {
  8208. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8209. this._cache.rotation.copyFrom(this.rotation);
  8210. }
  8211. // Translation
  8212. if (this.infiniteDistance && !this.parent) {
  8213. var camera = this.getScene().activeCamera;
  8214. if (camera) {
  8215. var cameraWorldMatrix = camera.getWorldMatrix();
  8216. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8217. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8218. }
  8219. }
  8220. else {
  8221. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8222. }
  8223. // Composing transformations
  8224. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8225. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8226. // Billboarding
  8227. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8228. var localPosition = this.position.clone();
  8229. var zero = this.getScene().activeCamera.globalPosition.clone();
  8230. if (this.parent && this.parent.position) {
  8231. localPosition.addInPlace(this.parent.position);
  8232. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8233. }
  8234. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8235. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8236. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8237. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8238. zero.y = localPosition.y + 0.001;
  8239. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8240. zero.z = localPosition.z + 0.001;
  8241. }
  8242. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8243. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8244. this._localBillboard.invert();
  8245. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8246. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8247. }
  8248. // Local world
  8249. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8250. // Parent
  8251. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8252. this._markSyncedWithParent();
  8253. if (this._meshToBoneReferal) {
  8254. if (!this._localMeshReferalTransform) {
  8255. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8256. }
  8257. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8258. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8259. }
  8260. else {
  8261. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8262. }
  8263. }
  8264. else {
  8265. this._worldMatrix.copyFrom(this._localWorld);
  8266. }
  8267. // Bounding info
  8268. this._updateBoundingInfo();
  8269. // Absolute position
  8270. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8271. // Callbacks
  8272. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8273. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8274. }
  8275. return this._worldMatrix;
  8276. };
  8277. /**
  8278. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8279. * @param func: callback function to add
  8280. */
  8281. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8282. this._onAfterWorldMatrixUpdate.push(func);
  8283. };
  8284. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8285. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8286. if (index > -1) {
  8287. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8288. }
  8289. };
  8290. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8291. this.computeWorldMatrix();
  8292. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8293. };
  8294. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8295. this.computeWorldMatrix();
  8296. var invLocalWorldMatrix = this._localWorld.clone();
  8297. invLocalWorldMatrix.invert();
  8298. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8299. };
  8300. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8301. this.computeWorldMatrix(true);
  8302. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8303. };
  8304. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8305. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8306. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8307. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8308. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8309. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8310. /// <returns>Mesh oriented towards targetMesh</returns>
  8311. yawCor = yawCor || 0; // default to zero if undefined
  8312. pitchCor = pitchCor || 0;
  8313. rollCor = rollCor || 0;
  8314. var dv = targetPoint.subtract(this.position);
  8315. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8316. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8317. var pitch = Math.atan2(dv.y, len);
  8318. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8319. };
  8320. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8321. this._meshToBoneReferal = affectedMesh;
  8322. this.parent = bone;
  8323. if (bone.getWorldMatrix().determinant() < 0) {
  8324. this.scalingDeterminant *= -1;
  8325. }
  8326. };
  8327. AbstractMesh.prototype.detachFromBone = function () {
  8328. if (this.parent.getWorldMatrix().determinant() < 0) {
  8329. this.scalingDeterminant *= -1;
  8330. }
  8331. this._meshToBoneReferal = null;
  8332. this.parent = null;
  8333. };
  8334. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8335. return this._boundingInfo.isInFrustum(frustumPlanes);
  8336. };
  8337. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8338. if (!camera) {
  8339. camera = this.getScene().activeCamera;
  8340. }
  8341. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8342. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8343. return false;
  8344. }
  8345. return true;
  8346. };
  8347. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8348. if (!this._boundingInfo || !mesh._boundingInfo) {
  8349. return false;
  8350. }
  8351. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8352. };
  8353. AbstractMesh.prototype.intersectsPoint = function (point) {
  8354. if (!this._boundingInfo) {
  8355. return false;
  8356. }
  8357. return this._boundingInfo.intersectsPoint(point);
  8358. };
  8359. // Physics
  8360. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8361. var physicsEngine = this.getScene().getPhysicsEngine();
  8362. if (!physicsEngine) {
  8363. return null;
  8364. }
  8365. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8366. if (impostor.impostor) {
  8367. // Old API
  8368. options = impostor;
  8369. impostor = impostor.impostor;
  8370. }
  8371. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8372. physicsEngine._unregisterMesh(this);
  8373. return null;
  8374. }
  8375. if (!options) {
  8376. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8377. }
  8378. else {
  8379. if (!options.mass && options.mass !== 0)
  8380. options.mass = 0;
  8381. if (!options.friction && options.friction !== 0)
  8382. options.friction = 0.2;
  8383. if (!options.restitution && options.restitution !== 0)
  8384. options.restitution = 0.2;
  8385. }
  8386. this._physicImpostor = impostor;
  8387. this._physicsMass = options.mass;
  8388. this._physicsFriction = options.friction;
  8389. this._physicRestitution = options.restitution;
  8390. return physicsEngine._registerMesh(this, impostor, options);
  8391. };
  8392. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8393. if (!this._physicImpostor) {
  8394. return BABYLON.PhysicsEngine.NoImpostor;
  8395. }
  8396. return this._physicImpostor;
  8397. };
  8398. AbstractMesh.prototype.getPhysicsMass = function () {
  8399. if (!this._physicsMass) {
  8400. return 0;
  8401. }
  8402. return this._physicsMass;
  8403. };
  8404. AbstractMesh.prototype.getPhysicsFriction = function () {
  8405. if (!this._physicsFriction) {
  8406. return 0;
  8407. }
  8408. return this._physicsFriction;
  8409. };
  8410. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8411. if (!this._physicRestitution) {
  8412. return 0;
  8413. }
  8414. return this._physicRestitution;
  8415. };
  8416. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8417. if (!camera) {
  8418. camera = this.getScene().activeCamera;
  8419. }
  8420. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8421. };
  8422. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8423. if (!camera) {
  8424. camera = this.getScene().activeCamera;
  8425. }
  8426. return this.absolutePosition.subtract(camera.position).length();
  8427. };
  8428. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8429. if (!this._physicImpostor) {
  8430. return;
  8431. }
  8432. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8433. };
  8434. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8435. if (!this._physicImpostor) {
  8436. return;
  8437. }
  8438. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8439. };
  8440. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8441. if (!this._physicImpostor) {
  8442. return;
  8443. }
  8444. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8445. };
  8446. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8447. // Collisions
  8448. get: function () {
  8449. return this._checkCollisions;
  8450. },
  8451. set: function (collisionEnabled) {
  8452. this._checkCollisions = collisionEnabled;
  8453. if (this.getScene().workerCollisions) {
  8454. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8455. }
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8461. var globalPosition = this.getAbsolutePosition();
  8462. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8463. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8464. this._collider.radius = this.ellipsoid;
  8465. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8466. };
  8467. // Submeshes octree
  8468. /**
  8469. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8470. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8471. */
  8472. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8473. if (maxCapacity === void 0) { maxCapacity = 64; }
  8474. if (maxDepth === void 0) { maxDepth = 2; }
  8475. if (!this._submeshesOctree) {
  8476. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8477. }
  8478. this.computeWorldMatrix(true);
  8479. // Update octree
  8480. var bbox = this.getBoundingInfo().boundingBox;
  8481. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8482. return this._submeshesOctree;
  8483. };
  8484. // Collisions
  8485. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8486. this._generatePointsArray();
  8487. // Transformation
  8488. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8489. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8490. subMesh._lastColliderWorldVertices = [];
  8491. subMesh._trianglePlanes = [];
  8492. var start = subMesh.verticesStart;
  8493. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8494. for (var i = start; i < end; i++) {
  8495. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8496. }
  8497. }
  8498. // Collide
  8499. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8500. if (collider.collisionFound) {
  8501. collider.collidedMesh = this;
  8502. }
  8503. };
  8504. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8505. var subMeshes;
  8506. var len;
  8507. // Octrees
  8508. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8509. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8510. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8511. len = intersections.length;
  8512. subMeshes = intersections.data;
  8513. }
  8514. else {
  8515. subMeshes = this.subMeshes;
  8516. len = subMeshes.length;
  8517. }
  8518. for (var index = 0; index < len; index++) {
  8519. var subMesh = subMeshes[index];
  8520. // Bounding test
  8521. if (len > 1 && !subMesh._checkCollision(collider))
  8522. continue;
  8523. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8524. }
  8525. };
  8526. AbstractMesh.prototype._checkCollision = function (collider) {
  8527. // Bounding box test
  8528. if (!this._boundingInfo._checkCollision(collider))
  8529. return;
  8530. // Transformation matrix
  8531. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8532. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8533. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8534. };
  8535. // Picking
  8536. AbstractMesh.prototype._generatePointsArray = function () {
  8537. return false;
  8538. };
  8539. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8540. var pickingInfo = new BABYLON.PickingInfo();
  8541. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8542. return pickingInfo;
  8543. }
  8544. if (!this._generatePointsArray()) {
  8545. return pickingInfo;
  8546. }
  8547. var intersectInfo = null;
  8548. // Octrees
  8549. var subMeshes;
  8550. var len;
  8551. if (this._submeshesOctree && this.useOctreeForPicking) {
  8552. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8553. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8554. len = intersections.length;
  8555. subMeshes = intersections.data;
  8556. }
  8557. else {
  8558. subMeshes = this.subMeshes;
  8559. len = subMeshes.length;
  8560. }
  8561. for (var index = 0; index < len; index++) {
  8562. var subMesh = subMeshes[index];
  8563. // Bounding test
  8564. if (len > 1 && !subMesh.canIntersects(ray))
  8565. continue;
  8566. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8567. if (currentIntersectInfo) {
  8568. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8569. intersectInfo = currentIntersectInfo;
  8570. intersectInfo.subMeshId = index;
  8571. if (fastCheck) {
  8572. break;
  8573. }
  8574. }
  8575. }
  8576. }
  8577. if (intersectInfo) {
  8578. // Get picked point
  8579. var world = this.getWorldMatrix();
  8580. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8581. var direction = ray.direction.clone();
  8582. direction = direction.scale(intersectInfo.distance);
  8583. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8584. var pickedPoint = worldOrigin.add(worldDirection);
  8585. // Return result
  8586. pickingInfo.hit = true;
  8587. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8588. pickingInfo.pickedPoint = pickedPoint;
  8589. pickingInfo.pickedMesh = this;
  8590. pickingInfo.bu = intersectInfo.bu;
  8591. pickingInfo.bv = intersectInfo.bv;
  8592. pickingInfo.faceId = intersectInfo.faceId;
  8593. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8594. return pickingInfo;
  8595. }
  8596. return pickingInfo;
  8597. };
  8598. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8599. return null;
  8600. };
  8601. AbstractMesh.prototype.releaseSubMeshes = function () {
  8602. if (this.subMeshes) {
  8603. while (this.subMeshes.length) {
  8604. this.subMeshes[0].dispose();
  8605. }
  8606. }
  8607. else {
  8608. this.subMeshes = new Array();
  8609. }
  8610. };
  8611. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8612. var index;
  8613. // Physics
  8614. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8615. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8616. }
  8617. // Intersections in progress
  8618. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8619. var other = this._intersectionsInProgress[index];
  8620. var pos = other._intersectionsInProgress.indexOf(this);
  8621. other._intersectionsInProgress.splice(pos, 1);
  8622. }
  8623. this._intersectionsInProgress = [];
  8624. // Edges
  8625. if (this._edgesRenderer) {
  8626. this._edgesRenderer.dispose();
  8627. this._edgesRenderer = null;
  8628. }
  8629. // SubMeshes
  8630. this.releaseSubMeshes();
  8631. // Remove from scene
  8632. this.getScene().removeMesh(this);
  8633. if (!doNotRecurse) {
  8634. // Particles
  8635. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8636. if (this.getScene().particleSystems[index].emitter === this) {
  8637. this.getScene().particleSystems[index].dispose();
  8638. index--;
  8639. }
  8640. }
  8641. // Children
  8642. var objects = this.getScene().meshes.slice(0);
  8643. for (index = 0; index < objects.length; index++) {
  8644. if (objects[index].parent === this) {
  8645. objects[index].dispose();
  8646. }
  8647. }
  8648. }
  8649. else {
  8650. for (index = 0; index < this.getScene().meshes.length; index++) {
  8651. var obj = this.getScene().meshes[index];
  8652. if (obj.parent === this) {
  8653. obj.parent = null;
  8654. obj.computeWorldMatrix(true);
  8655. }
  8656. }
  8657. }
  8658. this._onAfterWorldMatrixUpdate = [];
  8659. this._isDisposed = true;
  8660. // Callback
  8661. if (this.onDispose) {
  8662. this.onDispose();
  8663. }
  8664. };
  8665. // Statics
  8666. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8667. AbstractMesh._BILLBOARDMODE_X = 1;
  8668. AbstractMesh._BILLBOARDMODE_Y = 2;
  8669. AbstractMesh._BILLBOARDMODE_Z = 4;
  8670. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8671. return AbstractMesh;
  8672. })(BABYLON.Node);
  8673. BABYLON.AbstractMesh = AbstractMesh;
  8674. })(BABYLON || (BABYLON = {}));
  8675. var BABYLON;
  8676. (function (BABYLON) {
  8677. var Light = (function (_super) {
  8678. __extends(Light, _super);
  8679. function Light(name, scene) {
  8680. _super.call(this, name, scene);
  8681. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8682. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8683. this.intensity = 1.0;
  8684. this.range = Number.MAX_VALUE;
  8685. this.includeOnlyWithLayerMask = 0;
  8686. this.includedOnlyMeshes = new Array();
  8687. this.excludedMeshes = new Array();
  8688. this.excludeWithLayerMask = 0;
  8689. this._excludedMeshesIds = new Array();
  8690. this._includedOnlyMeshesIds = new Array();
  8691. scene.addLight(this);
  8692. }
  8693. Light.prototype.getShadowGenerator = function () {
  8694. return this._shadowGenerator;
  8695. };
  8696. Light.prototype.getAbsolutePosition = function () {
  8697. return BABYLON.Vector3.Zero();
  8698. };
  8699. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8700. };
  8701. Light.prototype._getWorldMatrix = function () {
  8702. return BABYLON.Matrix.Identity();
  8703. };
  8704. Light.prototype.canAffectMesh = function (mesh) {
  8705. if (!mesh) {
  8706. return true;
  8707. }
  8708. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8709. return false;
  8710. }
  8711. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8712. return false;
  8713. }
  8714. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8715. return false;
  8716. }
  8717. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8718. return false;
  8719. }
  8720. return true;
  8721. };
  8722. Light.prototype.getWorldMatrix = function () {
  8723. this._currentRenderId = this.getScene().getRenderId();
  8724. var worldMatrix = this._getWorldMatrix();
  8725. if (this.parent && this.parent.getWorldMatrix) {
  8726. if (!this._parentedWorldMatrix) {
  8727. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8728. }
  8729. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8730. this._markSyncedWithParent();
  8731. return this._parentedWorldMatrix;
  8732. }
  8733. return worldMatrix;
  8734. };
  8735. Light.prototype.dispose = function () {
  8736. if (this._shadowGenerator) {
  8737. this._shadowGenerator.dispose();
  8738. this._shadowGenerator = null;
  8739. }
  8740. // Remove from scene
  8741. this.getScene().removeLight(this);
  8742. };
  8743. return Light;
  8744. })(BABYLON.Node);
  8745. BABYLON.Light = Light;
  8746. })(BABYLON || (BABYLON = {}));
  8747. var BABYLON;
  8748. (function (BABYLON) {
  8749. var PointLight = (function (_super) {
  8750. __extends(PointLight, _super);
  8751. function PointLight(name, position, scene) {
  8752. _super.call(this, name, scene);
  8753. this.position = position;
  8754. }
  8755. PointLight.prototype.getAbsolutePosition = function () {
  8756. return this._transformedPosition ? this._transformedPosition : this.position;
  8757. };
  8758. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8759. if (this.parent && this.parent.getWorldMatrix) {
  8760. if (!this._transformedPosition) {
  8761. this._transformedPosition = BABYLON.Vector3.Zero();
  8762. }
  8763. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8764. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8765. return;
  8766. }
  8767. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8768. };
  8769. PointLight.prototype.getShadowGenerator = function () {
  8770. return null;
  8771. };
  8772. PointLight.prototype._getWorldMatrix = function () {
  8773. if (!this._worldMatrix) {
  8774. this._worldMatrix = BABYLON.Matrix.Identity();
  8775. }
  8776. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8777. return this._worldMatrix;
  8778. };
  8779. return PointLight;
  8780. })(BABYLON.Light);
  8781. BABYLON.PointLight = PointLight;
  8782. })(BABYLON || (BABYLON = {}));
  8783. var BABYLON;
  8784. (function (BABYLON) {
  8785. var SpotLight = (function (_super) {
  8786. __extends(SpotLight, _super);
  8787. function SpotLight(name, position, direction, angle, exponent, scene) {
  8788. _super.call(this, name, scene);
  8789. this.position = position;
  8790. this.direction = direction;
  8791. this.angle = angle;
  8792. this.exponent = exponent;
  8793. }
  8794. SpotLight.prototype.getAbsolutePosition = function () {
  8795. return this.transformedPosition ? this.transformedPosition : this.position;
  8796. };
  8797. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8798. var activeCamera = this.getScene().activeCamera;
  8799. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8800. };
  8801. SpotLight.prototype.supportsVSM = function () {
  8802. return true;
  8803. };
  8804. SpotLight.prototype.needRefreshPerFrame = function () {
  8805. return false;
  8806. };
  8807. SpotLight.prototype.setDirectionToTarget = function (target) {
  8808. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8809. return this.direction;
  8810. };
  8811. SpotLight.prototype.computeTransformedPosition = function () {
  8812. if (this.parent && this.parent.getWorldMatrix) {
  8813. if (!this.transformedPosition) {
  8814. this.transformedPosition = BABYLON.Vector3.Zero();
  8815. }
  8816. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8817. return true;
  8818. }
  8819. return false;
  8820. };
  8821. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8822. var normalizeDirection;
  8823. if (this.parent && this.parent.getWorldMatrix) {
  8824. if (!this._transformedDirection) {
  8825. this._transformedDirection = BABYLON.Vector3.Zero();
  8826. }
  8827. this.computeTransformedPosition();
  8828. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8829. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8830. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8831. }
  8832. else {
  8833. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8834. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8835. }
  8836. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8837. };
  8838. SpotLight.prototype._getWorldMatrix = function () {
  8839. if (!this._worldMatrix) {
  8840. this._worldMatrix = BABYLON.Matrix.Identity();
  8841. }
  8842. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8843. return this._worldMatrix;
  8844. };
  8845. return SpotLight;
  8846. })(BABYLON.Light);
  8847. BABYLON.SpotLight = SpotLight;
  8848. })(BABYLON || (BABYLON = {}));
  8849. var BABYLON;
  8850. (function (BABYLON) {
  8851. var HemisphericLight = (function (_super) {
  8852. __extends(HemisphericLight, _super);
  8853. function HemisphericLight(name, direction, scene) {
  8854. _super.call(this, name, scene);
  8855. this.direction = direction;
  8856. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8857. }
  8858. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8859. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8860. return this.direction;
  8861. };
  8862. HemisphericLight.prototype.getShadowGenerator = function () {
  8863. return null;
  8864. };
  8865. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8866. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8867. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8868. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8869. };
  8870. HemisphericLight.prototype._getWorldMatrix = function () {
  8871. if (!this._worldMatrix) {
  8872. this._worldMatrix = BABYLON.Matrix.Identity();
  8873. }
  8874. return this._worldMatrix;
  8875. };
  8876. return HemisphericLight;
  8877. })(BABYLON.Light);
  8878. BABYLON.HemisphericLight = HemisphericLight;
  8879. })(BABYLON || (BABYLON = {}));
  8880. var BABYLON;
  8881. (function (BABYLON) {
  8882. var DirectionalLight = (function (_super) {
  8883. __extends(DirectionalLight, _super);
  8884. function DirectionalLight(name, direction, scene) {
  8885. _super.call(this, name, scene);
  8886. this.direction = direction;
  8887. this.shadowOrthoScale = 0.5;
  8888. this.position = direction.scale(-1);
  8889. }
  8890. DirectionalLight.prototype.getAbsolutePosition = function () {
  8891. return this.transformedPosition ? this.transformedPosition : this.position;
  8892. };
  8893. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8894. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8895. return this.direction;
  8896. };
  8897. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8898. var orthoLeft = Number.MAX_VALUE;
  8899. var orthoRight = Number.MIN_VALUE;
  8900. var orthoTop = Number.MIN_VALUE;
  8901. var orthoBottom = Number.MAX_VALUE;
  8902. var tempVector3 = BABYLON.Vector3.Zero();
  8903. var activeCamera = this.getScene().activeCamera;
  8904. // Check extends
  8905. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8906. var mesh = renderList[meshIndex];
  8907. if (!mesh) {
  8908. continue;
  8909. }
  8910. var boundingInfo = mesh.getBoundingInfo();
  8911. if (!boundingInfo) {
  8912. continue;
  8913. }
  8914. var boundingBox = boundingInfo.boundingBox;
  8915. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8916. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8917. if (tempVector3.x < orthoLeft)
  8918. orthoLeft = tempVector3.x;
  8919. if (tempVector3.y < orthoBottom)
  8920. orthoBottom = tempVector3.y;
  8921. if (tempVector3.x > orthoRight)
  8922. orthoRight = tempVector3.x;
  8923. if (tempVector3.y > orthoTop)
  8924. orthoTop = tempVector3.y;
  8925. }
  8926. }
  8927. var xOffset = orthoRight - orthoLeft;
  8928. var yOffset = orthoTop - orthoBottom;
  8929. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8930. };
  8931. DirectionalLight.prototype.supportsVSM = function () {
  8932. return true;
  8933. };
  8934. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8935. return true;
  8936. };
  8937. DirectionalLight.prototype.computeTransformedPosition = function () {
  8938. if (this.parent && this.parent.getWorldMatrix) {
  8939. if (!this.transformedPosition) {
  8940. this.transformedPosition = BABYLON.Vector3.Zero();
  8941. }
  8942. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8943. return true;
  8944. }
  8945. return false;
  8946. };
  8947. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8948. if (this.parent && this.parent.getWorldMatrix) {
  8949. if (!this._transformedDirection) {
  8950. this._transformedDirection = BABYLON.Vector3.Zero();
  8951. }
  8952. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8953. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8954. return;
  8955. }
  8956. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8957. };
  8958. DirectionalLight.prototype._getWorldMatrix = function () {
  8959. if (!this._worldMatrix) {
  8960. this._worldMatrix = BABYLON.Matrix.Identity();
  8961. }
  8962. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8963. return this._worldMatrix;
  8964. };
  8965. return DirectionalLight;
  8966. })(BABYLON.Light);
  8967. BABYLON.DirectionalLight = DirectionalLight;
  8968. })(BABYLON || (BABYLON = {}));
  8969. var BABYLON;
  8970. (function (BABYLON) {
  8971. var ShadowGenerator = (function () {
  8972. function ShadowGenerator(mapSize, light) {
  8973. var _this = this;
  8974. // Members
  8975. this._filter = ShadowGenerator.FILTER_NONE;
  8976. this.blurScale = 2;
  8977. this._blurBoxOffset = 0;
  8978. this._bias = 0.00005;
  8979. this._lightDirection = BABYLON.Vector3.Zero();
  8980. this._darkness = 0;
  8981. this._transparencyShadow = false;
  8982. this._viewMatrix = BABYLON.Matrix.Zero();
  8983. this._projectionMatrix = BABYLON.Matrix.Zero();
  8984. this._transformMatrix = BABYLON.Matrix.Zero();
  8985. this._worldViewProjection = BABYLON.Matrix.Zero();
  8986. this._light = light;
  8987. this._scene = light.getScene();
  8988. this._mapSize = mapSize;
  8989. light._shadowGenerator = this;
  8990. // Render target
  8991. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8992. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8993. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8994. this._shadowMap.anisotropicFilteringLevel = 1;
  8995. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8996. this._shadowMap.renderParticles = false;
  8997. this._shadowMap.onAfterUnbind = function () {
  8998. if (!_this.useBlurVarianceShadowMap) {
  8999. return;
  9000. }
  9001. if (!_this._shadowMap2) {
  9002. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9003. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9004. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9005. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9006. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9007. _this._downSamplePostprocess.onApply = function (effect) {
  9008. effect.setTexture("textureSampler", _this._shadowMap);
  9009. };
  9010. _this.blurBoxOffset = 1;
  9011. }
  9012. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9013. };
  9014. // Custom render function
  9015. var renderSubMesh = function (subMesh) {
  9016. var mesh = subMesh.getRenderingMesh();
  9017. var scene = _this._scene;
  9018. var engine = scene.getEngine();
  9019. // Culling
  9020. engine.setState(subMesh.getMaterial().backFaceCulling);
  9021. // Managing instances
  9022. var batch = mesh._getInstancesRenderList(subMesh._id);
  9023. if (batch.mustReturn) {
  9024. return;
  9025. }
  9026. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  9027. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9028. engine.enableEffect(_this._effect);
  9029. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9030. var material = subMesh.getMaterial();
  9031. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9032. // Alpha test
  9033. if (material && material.needAlphaTesting()) {
  9034. var alphaTexture = material.getAlphaTestTexture();
  9035. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9036. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9037. }
  9038. // Bones
  9039. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9040. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9041. }
  9042. // Draw
  9043. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9044. }
  9045. else {
  9046. // Need to reset refresh rate of the shadowMap
  9047. _this._shadowMap.resetRefreshCounter();
  9048. }
  9049. };
  9050. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9051. var index;
  9052. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9053. renderSubMesh(opaqueSubMeshes.data[index]);
  9054. }
  9055. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9056. renderSubMesh(alphaTestSubMeshes.data[index]);
  9057. }
  9058. if (_this._transparencyShadow) {
  9059. for (index = 0; index < transparentSubMeshes.length; index++) {
  9060. renderSubMesh(transparentSubMeshes.data[index]);
  9061. }
  9062. }
  9063. };
  9064. this._shadowMap.onClear = function (engine) {
  9065. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9066. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9067. }
  9068. else {
  9069. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9070. }
  9071. };
  9072. }
  9073. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9074. // Static
  9075. get: function () {
  9076. return ShadowGenerator._FILTER_NONE;
  9077. },
  9078. enumerable: true,
  9079. configurable: true
  9080. });
  9081. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9082. get: function () {
  9083. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9084. },
  9085. enumerable: true,
  9086. configurable: true
  9087. });
  9088. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9089. get: function () {
  9090. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9091. },
  9092. enumerable: true,
  9093. configurable: true
  9094. });
  9095. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9096. get: function () {
  9097. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9103. get: function () {
  9104. return this._bias;
  9105. },
  9106. set: function (bias) {
  9107. this._bias = bias;
  9108. },
  9109. enumerable: true,
  9110. configurable: true
  9111. });
  9112. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9113. get: function () {
  9114. return this._blurBoxOffset;
  9115. },
  9116. set: function (value) {
  9117. var _this = this;
  9118. if (this._blurBoxOffset === value) {
  9119. return;
  9120. }
  9121. this._blurBoxOffset = value;
  9122. if (this._boxBlurPostprocess) {
  9123. this._boxBlurPostprocess.dispose();
  9124. }
  9125. 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);
  9126. this._boxBlurPostprocess.onApply = function (effect) {
  9127. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9128. };
  9129. },
  9130. enumerable: true,
  9131. configurable: true
  9132. });
  9133. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9134. get: function () {
  9135. return this._filter;
  9136. },
  9137. set: function (value) {
  9138. if (this._filter === value) {
  9139. return;
  9140. }
  9141. this._filter = value;
  9142. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9143. this._shadowMap.anisotropicFilteringLevel = 16;
  9144. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9145. }
  9146. else {
  9147. this._shadowMap.anisotropicFilteringLevel = 1;
  9148. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9149. }
  9150. },
  9151. enumerable: true,
  9152. configurable: true
  9153. });
  9154. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9155. get: function () {
  9156. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9157. },
  9158. set: function (value) {
  9159. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9160. },
  9161. enumerable: true,
  9162. configurable: true
  9163. });
  9164. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9165. get: function () {
  9166. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9167. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9168. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9169. },
  9170. set: function (value) {
  9171. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9172. },
  9173. enumerable: true,
  9174. configurable: true
  9175. });
  9176. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9177. get: function () {
  9178. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9179. },
  9180. set: function (value) {
  9181. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9182. },
  9183. enumerable: true,
  9184. configurable: true
  9185. });
  9186. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9187. var defines = [];
  9188. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9189. defines.push("#define VSM");
  9190. }
  9191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9192. var mesh = subMesh.getMesh();
  9193. var material = subMesh.getMaterial();
  9194. // Alpha test
  9195. if (material && material.needAlphaTesting()) {
  9196. defines.push("#define ALPHATEST");
  9197. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9198. attribs.push(BABYLON.VertexBuffer.UVKind);
  9199. defines.push("#define UV1");
  9200. }
  9201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9202. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9203. defines.push("#define UV2");
  9204. }
  9205. }
  9206. // Bones
  9207. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9210. defines.push("#define BONES");
  9211. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9212. }
  9213. // Instances
  9214. if (useInstances) {
  9215. defines.push("#define INSTANCES");
  9216. attribs.push("world0");
  9217. attribs.push("world1");
  9218. attribs.push("world2");
  9219. attribs.push("world3");
  9220. }
  9221. // Get correct effect
  9222. var join = defines.join("\n");
  9223. if (this._cachedDefines !== join) {
  9224. this._cachedDefines = join;
  9225. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9226. }
  9227. return this._effect.isReady();
  9228. };
  9229. ShadowGenerator.prototype.getShadowMap = function () {
  9230. return this._shadowMap;
  9231. };
  9232. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9233. if (this._shadowMap2) {
  9234. return this._shadowMap2;
  9235. }
  9236. return this._shadowMap;
  9237. };
  9238. ShadowGenerator.prototype.getLight = function () {
  9239. return this._light;
  9240. };
  9241. // Methods
  9242. ShadowGenerator.prototype.getTransformMatrix = function () {
  9243. var scene = this._scene;
  9244. if (this._currentRenderID === scene.getRenderId()) {
  9245. return this._transformMatrix;
  9246. }
  9247. this._currentRenderID = scene.getRenderId();
  9248. var lightPosition = this._light.position;
  9249. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9250. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9251. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9252. }
  9253. if (this._light.computeTransformedPosition()) {
  9254. lightPosition = this._light.transformedPosition;
  9255. }
  9256. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9257. this._cachedPosition = lightPosition.clone();
  9258. this._cachedDirection = this._lightDirection.clone();
  9259. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9260. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9261. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9262. }
  9263. return this._transformMatrix;
  9264. };
  9265. ShadowGenerator.prototype.getDarkness = function () {
  9266. return this._darkness;
  9267. };
  9268. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9269. if (darkness >= 1.0)
  9270. this._darkness = 1.0;
  9271. else if (darkness <= 0.0)
  9272. this._darkness = 0.0;
  9273. else
  9274. this._darkness = darkness;
  9275. };
  9276. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9277. this._transparencyShadow = hasShadow;
  9278. };
  9279. ShadowGenerator.prototype._packHalf = function (depth) {
  9280. var scale = depth * 255.0;
  9281. var fract = scale - Math.floor(scale);
  9282. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9283. };
  9284. ShadowGenerator.prototype.dispose = function () {
  9285. this._shadowMap.dispose();
  9286. if (this._shadowMap2) {
  9287. this._shadowMap2.dispose();
  9288. }
  9289. if (this._downSamplePostprocess) {
  9290. this._downSamplePostprocess.dispose();
  9291. }
  9292. if (this._boxBlurPostprocess) {
  9293. this._boxBlurPostprocess.dispose();
  9294. }
  9295. };
  9296. ShadowGenerator._FILTER_NONE = 0;
  9297. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9298. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9299. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9300. return ShadowGenerator;
  9301. })();
  9302. BABYLON.ShadowGenerator = ShadowGenerator;
  9303. })(BABYLON || (BABYLON = {}));
  9304. var BABYLON;
  9305. (function (BABYLON) {
  9306. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9307. if (boxMin.x > sphereCenter.x + sphereRadius)
  9308. return false;
  9309. if (sphereCenter.x - sphereRadius > boxMax.x)
  9310. return false;
  9311. if (boxMin.y > sphereCenter.y + sphereRadius)
  9312. return false;
  9313. if (sphereCenter.y - sphereRadius > boxMax.y)
  9314. return false;
  9315. if (boxMin.z > sphereCenter.z + sphereRadius)
  9316. return false;
  9317. if (sphereCenter.z - sphereRadius > boxMax.z)
  9318. return false;
  9319. return true;
  9320. };
  9321. var getLowestRoot = function (a, b, c, maxR) {
  9322. var determinant = b * b - 4.0 * a * c;
  9323. var result = { root: 0, found: false };
  9324. if (determinant < 0)
  9325. return result;
  9326. var sqrtD = Math.sqrt(determinant);
  9327. var r1 = (-b - sqrtD) / (2.0 * a);
  9328. var r2 = (-b + sqrtD) / (2.0 * a);
  9329. if (r1 > r2) {
  9330. var temp = r2;
  9331. r2 = r1;
  9332. r1 = temp;
  9333. }
  9334. if (r1 > 0 && r1 < maxR) {
  9335. result.root = r1;
  9336. result.found = true;
  9337. return result;
  9338. }
  9339. if (r2 > 0 && r2 < maxR) {
  9340. result.root = r2;
  9341. result.found = true;
  9342. return result;
  9343. }
  9344. return result;
  9345. };
  9346. var Collider = (function () {
  9347. function Collider() {
  9348. this.radius = new BABYLON.Vector3(1, 1, 1);
  9349. this.retry = 0;
  9350. this.basePointWorld = BABYLON.Vector3.Zero();
  9351. this.velocityWorld = BABYLON.Vector3.Zero();
  9352. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9353. this._collisionPoint = BABYLON.Vector3.Zero();
  9354. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9355. this._tempVector = BABYLON.Vector3.Zero();
  9356. this._tempVector2 = BABYLON.Vector3.Zero();
  9357. this._tempVector3 = BABYLON.Vector3.Zero();
  9358. this._tempVector4 = BABYLON.Vector3.Zero();
  9359. this._edge = BABYLON.Vector3.Zero();
  9360. this._baseToVertex = BABYLON.Vector3.Zero();
  9361. this._destinationPoint = BABYLON.Vector3.Zero();
  9362. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9363. this._displacementVector = BABYLON.Vector3.Zero();
  9364. }
  9365. // Methods
  9366. Collider.prototype._initialize = function (source, dir, e) {
  9367. this.velocity = dir;
  9368. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9369. this.basePoint = source;
  9370. source.multiplyToRef(this.radius, this.basePointWorld);
  9371. dir.multiplyToRef(this.radius, this.velocityWorld);
  9372. this.velocityWorldLength = this.velocityWorld.length();
  9373. this.epsilon = e;
  9374. this.collisionFound = false;
  9375. };
  9376. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9377. pa.subtractToRef(point, this._tempVector);
  9378. pb.subtractToRef(point, this._tempVector2);
  9379. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9380. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9381. if (d < 0)
  9382. return false;
  9383. pc.subtractToRef(point, this._tempVector3);
  9384. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9385. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9386. if (d < 0)
  9387. return false;
  9388. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9389. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9390. return d >= 0;
  9391. };
  9392. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9393. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9394. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9395. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9396. return false;
  9397. }
  9398. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9399. return false;
  9400. return true;
  9401. };
  9402. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9403. var t0;
  9404. var embeddedInPlane = false;
  9405. //defensive programming, actually not needed.
  9406. if (!trianglePlaneArray) {
  9407. trianglePlaneArray = [];
  9408. }
  9409. if (!trianglePlaneArray[faceIndex]) {
  9410. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9411. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9412. }
  9413. var trianglePlane = trianglePlaneArray[faceIndex];
  9414. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9415. return;
  9416. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9417. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9418. if (normalDotVelocity == 0) {
  9419. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9420. return;
  9421. embeddedInPlane = true;
  9422. t0 = 0;
  9423. }
  9424. else {
  9425. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9426. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9427. if (t0 > t1) {
  9428. var temp = t1;
  9429. t1 = t0;
  9430. t0 = temp;
  9431. }
  9432. if (t0 > 1.0 || t1 < 0.0)
  9433. return;
  9434. if (t0 < 0)
  9435. t0 = 0;
  9436. if (t0 > 1.0)
  9437. t0 = 1.0;
  9438. }
  9439. this._collisionPoint.copyFromFloats(0, 0, 0);
  9440. var found = false;
  9441. var t = 1.0;
  9442. if (!embeddedInPlane) {
  9443. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9444. this.velocity.scaleToRef(t0, this._tempVector);
  9445. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9446. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9447. found = true;
  9448. t = t0;
  9449. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9450. }
  9451. }
  9452. if (!found) {
  9453. var velocitySquaredLength = this.velocity.lengthSquared();
  9454. var a = velocitySquaredLength;
  9455. this.basePoint.subtractToRef(p1, this._tempVector);
  9456. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9457. var c = this._tempVector.lengthSquared() - 1.0;
  9458. var lowestRoot = getLowestRoot(a, b, c, t);
  9459. if (lowestRoot.found) {
  9460. t = lowestRoot.root;
  9461. found = true;
  9462. this._collisionPoint.copyFrom(p1);
  9463. }
  9464. this.basePoint.subtractToRef(p2, this._tempVector);
  9465. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9466. c = this._tempVector.lengthSquared() - 1.0;
  9467. lowestRoot = getLowestRoot(a, b, c, t);
  9468. if (lowestRoot.found) {
  9469. t = lowestRoot.root;
  9470. found = true;
  9471. this._collisionPoint.copyFrom(p2);
  9472. }
  9473. this.basePoint.subtractToRef(p3, this._tempVector);
  9474. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9475. c = this._tempVector.lengthSquared() - 1.0;
  9476. lowestRoot = getLowestRoot(a, b, c, t);
  9477. if (lowestRoot.found) {
  9478. t = lowestRoot.root;
  9479. found = true;
  9480. this._collisionPoint.copyFrom(p3);
  9481. }
  9482. p2.subtractToRef(p1, this._edge);
  9483. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9484. var edgeSquaredLength = this._edge.lengthSquared();
  9485. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9486. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9487. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9488. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9489. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9490. lowestRoot = getLowestRoot(a, b, c, t);
  9491. if (lowestRoot.found) {
  9492. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9493. if (f >= 0.0 && f <= 1.0) {
  9494. t = lowestRoot.root;
  9495. found = true;
  9496. this._edge.scaleInPlace(f);
  9497. p1.addToRef(this._edge, this._collisionPoint);
  9498. }
  9499. }
  9500. p3.subtractToRef(p2, this._edge);
  9501. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9502. edgeSquaredLength = this._edge.lengthSquared();
  9503. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9504. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9505. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9506. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9507. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9508. lowestRoot = getLowestRoot(a, b, c, t);
  9509. if (lowestRoot.found) {
  9510. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9511. if (f >= 0.0 && f <= 1.0) {
  9512. t = lowestRoot.root;
  9513. found = true;
  9514. this._edge.scaleInPlace(f);
  9515. p2.addToRef(this._edge, this._collisionPoint);
  9516. }
  9517. }
  9518. p1.subtractToRef(p3, this._edge);
  9519. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9520. edgeSquaredLength = this._edge.lengthSquared();
  9521. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9522. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9523. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9524. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9525. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9526. lowestRoot = getLowestRoot(a, b, c, t);
  9527. if (lowestRoot.found) {
  9528. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9529. if (f >= 0.0 && f <= 1.0) {
  9530. t = lowestRoot.root;
  9531. found = true;
  9532. this._edge.scaleInPlace(f);
  9533. p3.addToRef(this._edge, this._collisionPoint);
  9534. }
  9535. }
  9536. }
  9537. if (found) {
  9538. var distToCollision = t * this.velocity.length();
  9539. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9540. if (!this.intersectionPoint) {
  9541. this.intersectionPoint = this._collisionPoint.clone();
  9542. }
  9543. else {
  9544. this.intersectionPoint.copyFrom(this._collisionPoint);
  9545. }
  9546. this.nearestDistance = distToCollision;
  9547. this.collisionFound = true;
  9548. }
  9549. }
  9550. };
  9551. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9552. for (var i = indexStart; i < indexEnd; i += 3) {
  9553. var p1 = pts[indices[i] - decal];
  9554. var p2 = pts[indices[i + 1] - decal];
  9555. var p3 = pts[indices[i + 2] - decal];
  9556. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9557. }
  9558. };
  9559. Collider.prototype._getResponse = function (pos, vel) {
  9560. pos.addToRef(vel, this._destinationPoint);
  9561. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9562. this.basePoint.addToRef(vel, pos);
  9563. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9564. this._slidePlaneNormal.normalize();
  9565. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9566. pos.addInPlace(this._displacementVector);
  9567. this.intersectionPoint.addInPlace(this._displacementVector);
  9568. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9569. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9570. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9571. };
  9572. return Collider;
  9573. })();
  9574. BABYLON.Collider = Collider;
  9575. })(BABYLON || (BABYLON = {}));
  9576. var BABYLON;
  9577. (function (BABYLON) {
  9578. //WebWorker code will be inserted to this variable.
  9579. BABYLON.CollisionWorker = "";
  9580. (function (WorkerTaskType) {
  9581. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9582. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9583. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9584. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9585. var WorkerTaskType = BABYLON.WorkerTaskType;
  9586. (function (WorkerReplyType) {
  9587. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9588. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9589. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9590. var WorkerReplyType = BABYLON.WorkerReplyType;
  9591. var CollisionCoordinatorWorker = (function () {
  9592. function CollisionCoordinatorWorker() {
  9593. var _this = this;
  9594. this._scaledPosition = BABYLON.Vector3.Zero();
  9595. this._scaledVelocity = BABYLON.Vector3.Zero();
  9596. this.onMeshUpdated = function (mesh) {
  9597. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9598. };
  9599. this.onGeometryUpdated = function (geometry) {
  9600. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9601. };
  9602. this._afterRender = function () {
  9603. if (!_this._init)
  9604. return;
  9605. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9606. return;
  9607. }
  9608. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9609. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9610. if (_this._runningUpdated > 4) {
  9611. return;
  9612. }
  9613. ++_this._runningUpdated;
  9614. var payload = {
  9615. updatedMeshes: _this._addUpdateMeshesList,
  9616. updatedGeometries: _this._addUpdateGeometriesList,
  9617. removedGeometries: _this._toRemoveGeometryArray,
  9618. removedMeshes: _this._toRemoveMeshesArray
  9619. };
  9620. var message = {
  9621. payload: payload,
  9622. taskType: WorkerTaskType.UPDATE
  9623. };
  9624. var serializable = [];
  9625. for (var id in payload.updatedGeometries) {
  9626. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9627. //prepare transferables
  9628. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9629. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9630. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9631. }
  9632. }
  9633. _this._worker.postMessage(message, serializable);
  9634. _this._addUpdateMeshesList = {};
  9635. _this._addUpdateGeometriesList = {};
  9636. _this._toRemoveGeometryArray = [];
  9637. _this._toRemoveMeshesArray = [];
  9638. };
  9639. this._onMessageFromWorker = function (e) {
  9640. var returnData = e.data;
  9641. if (returnData.error != WorkerReplyType.SUCCESS) {
  9642. //TODO what errors can be returned from the worker?
  9643. BABYLON.Tools.Warn("error returned from worker!");
  9644. return;
  9645. }
  9646. switch (returnData.taskType) {
  9647. case WorkerTaskType.INIT:
  9648. _this._init = true;
  9649. //Update the worked with ALL of the scene's current state
  9650. _this._scene.meshes.forEach(function (mesh) {
  9651. _this.onMeshAdded(mesh);
  9652. });
  9653. _this._scene.getGeometries().forEach(function (geometry) {
  9654. _this.onGeometryAdded(geometry);
  9655. });
  9656. break;
  9657. case WorkerTaskType.UPDATE:
  9658. _this._runningUpdated--;
  9659. break;
  9660. case WorkerTaskType.COLLIDE:
  9661. _this._runningCollisionTask = false;
  9662. var returnPayload = returnData.payload;
  9663. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9664. return;
  9665. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9666. //cleanup
  9667. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9668. break;
  9669. }
  9670. };
  9671. this._collisionsCallbackArray = [];
  9672. this._init = false;
  9673. this._runningUpdated = 0;
  9674. this._runningCollisionTask = false;
  9675. this._addUpdateMeshesList = {};
  9676. this._addUpdateGeometriesList = {};
  9677. this._toRemoveGeometryArray = [];
  9678. this._toRemoveMeshesArray = [];
  9679. }
  9680. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9681. if (!this._init)
  9682. return;
  9683. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9684. return;
  9685. position.divideToRef(collider.radius, this._scaledPosition);
  9686. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9687. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9688. var payload = {
  9689. collider: {
  9690. position: this._scaledPosition.asArray(),
  9691. velocity: this._scaledVelocity.asArray(),
  9692. radius: collider.radius.asArray()
  9693. },
  9694. collisionId: collisionIndex,
  9695. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9696. maximumRetry: maximumRetry
  9697. };
  9698. var message = {
  9699. payload: payload,
  9700. taskType: WorkerTaskType.COLLIDE
  9701. };
  9702. this._worker.postMessage(message);
  9703. };
  9704. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9705. this._scene = scene;
  9706. this._scene.registerAfterRender(this._afterRender);
  9707. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9708. this._worker = new Worker(workerUrl);
  9709. this._worker.onmessage = this._onMessageFromWorker;
  9710. var message = {
  9711. payload: {},
  9712. taskType: WorkerTaskType.INIT
  9713. };
  9714. this._worker.postMessage(message);
  9715. };
  9716. CollisionCoordinatorWorker.prototype.destroy = function () {
  9717. this._scene.unregisterAfterRender(this._afterRender);
  9718. this._worker.terminate();
  9719. };
  9720. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9721. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9722. this.onMeshUpdated(mesh);
  9723. };
  9724. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9725. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9726. };
  9727. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9728. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9729. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9730. this.onGeometryUpdated(geometry);
  9731. };
  9732. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9733. this._toRemoveGeometryArray.push(geometry.id);
  9734. };
  9735. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9736. var submeshes = [];
  9737. if (mesh.subMeshes) {
  9738. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9739. return {
  9740. position: idx,
  9741. verticesStart: sm.verticesStart,
  9742. verticesCount: sm.verticesCount,
  9743. indexStart: sm.indexStart,
  9744. indexCount: sm.indexCount,
  9745. hasMaterial: !!sm.getMaterial(),
  9746. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9747. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9748. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9749. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9750. };
  9751. });
  9752. }
  9753. var geometryId = null;
  9754. if (mesh instanceof BABYLON.Mesh) {
  9755. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9756. }
  9757. else if (mesh instanceof BABYLON.InstancedMesh) {
  9758. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9759. }
  9760. return {
  9761. uniqueId: mesh.uniqueId,
  9762. id: mesh.id,
  9763. name: mesh.name,
  9764. geometryId: geometryId,
  9765. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9766. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9767. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9768. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9769. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9770. subMeshes: submeshes,
  9771. checkCollisions: mesh.checkCollisions
  9772. };
  9773. };
  9774. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9775. return {
  9776. id: geometry.id,
  9777. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9778. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9779. indices: new Int32Array(geometry.getIndices() || []),
  9780. };
  9781. };
  9782. return CollisionCoordinatorWorker;
  9783. })();
  9784. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9785. var CollisionCoordinatorLegacy = (function () {
  9786. function CollisionCoordinatorLegacy() {
  9787. this._scaledPosition = BABYLON.Vector3.Zero();
  9788. this._scaledVelocity = BABYLON.Vector3.Zero();
  9789. this._finalPosition = BABYLON.Vector3.Zero();
  9790. }
  9791. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9792. position.divideToRef(collider.radius, this._scaledPosition);
  9793. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9794. collider.collidedMesh = null;
  9795. collider.retry = 0;
  9796. collider.initialVelocity = this._scaledVelocity;
  9797. collider.initialPosition = this._scaledPosition;
  9798. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9799. this._finalPosition.multiplyInPlace(collider.radius);
  9800. //run the callback
  9801. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9802. };
  9803. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9804. this._scene = scene;
  9805. };
  9806. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9807. //Legacy need no destruction method.
  9808. };
  9809. //No update in legacy mode
  9810. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9811. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9812. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9813. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9814. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9815. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9816. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9817. if (excludedMesh === void 0) { excludedMesh = null; }
  9818. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9819. if (collider.retry >= maximumRetry) {
  9820. finalPosition.copyFrom(position);
  9821. return;
  9822. }
  9823. collider._initialize(position, velocity, closeDistance);
  9824. // Check all meshes
  9825. for (var index = 0; index < this._scene.meshes.length; index++) {
  9826. var mesh = this._scene.meshes[index];
  9827. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9828. mesh._checkCollision(collider);
  9829. }
  9830. }
  9831. if (!collider.collisionFound) {
  9832. position.addToRef(velocity, finalPosition);
  9833. return;
  9834. }
  9835. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9836. collider._getResponse(position, velocity);
  9837. }
  9838. if (velocity.length() <= closeDistance) {
  9839. finalPosition.copyFrom(position);
  9840. return;
  9841. }
  9842. collider.retry++;
  9843. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9844. };
  9845. return CollisionCoordinatorLegacy;
  9846. })();
  9847. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9848. })(BABYLON || (BABYLON = {}));
  9849. var BABYLON;
  9850. (function (BABYLON) {
  9851. var VRCameraMetrics = (function () {
  9852. function VRCameraMetrics() {
  9853. this.compensateDistorsion = true;
  9854. }
  9855. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9856. get: function () {
  9857. return this.hResolution / (2 * this.vResolution);
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9863. get: function () {
  9864. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9870. get: function () {
  9871. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9872. var h = (4 * meters) / this.hScreenSize;
  9873. return BABYLON.Matrix.Translation(h, 0, 0);
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9879. get: function () {
  9880. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9881. var h = (4 * meters) / this.hScreenSize;
  9882. return BABYLON.Matrix.Translation(-h, 0, 0);
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9888. get: function () {
  9889. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9895. get: function () {
  9896. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. VRCameraMetrics.GetDefault = function () {
  9902. var result = new VRCameraMetrics();
  9903. result.hResolution = 1280;
  9904. result.vResolution = 800;
  9905. result.hScreenSize = 0.149759993;
  9906. result.vScreenSize = 0.0935999975;
  9907. result.vScreenCenter = 0.0467999987,
  9908. result.eyeToScreenDistance = 0.0410000011;
  9909. result.lensSeparationDistance = 0.0635000020;
  9910. result.interpupillaryDistance = 0.0640000030;
  9911. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9912. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9913. result.postProcessScaleFactor = 1.714605507808412;
  9914. result.lensCenterOffset = 0.151976421;
  9915. return result;
  9916. };
  9917. return VRCameraMetrics;
  9918. })();
  9919. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9920. var Camera = (function (_super) {
  9921. __extends(Camera, _super);
  9922. function Camera(name, position, scene) {
  9923. _super.call(this, name, scene);
  9924. this.position = position;
  9925. // Members
  9926. this.upVector = BABYLON.Vector3.Up();
  9927. this.orthoLeft = null;
  9928. this.orthoRight = null;
  9929. this.orthoBottom = null;
  9930. this.orthoTop = null;
  9931. this.fov = 0.8;
  9932. this.minZ = 1.0;
  9933. this.maxZ = 10000.0;
  9934. this.inertia = 0.9;
  9935. this.mode = Camera.PERSPECTIVE_CAMERA;
  9936. this.isIntermediate = false;
  9937. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9938. this.layerMask = 0x0FFFFFFF;
  9939. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9940. // Camera rig members
  9941. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9942. this._rigCameras = new Array();
  9943. // Cache
  9944. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9945. this._projectionMatrix = new BABYLON.Matrix();
  9946. this._postProcesses = new Array();
  9947. this._postProcessesTakenIndices = [];
  9948. this._activeMeshes = new BABYLON.SmartArray(256);
  9949. this._globalPosition = BABYLON.Vector3.Zero();
  9950. scene.addCamera(this);
  9951. if (!scene.activeCamera) {
  9952. scene.activeCamera = this;
  9953. }
  9954. }
  9955. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9956. get: function () {
  9957. return Camera._PERSPECTIVE_CAMERA;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9963. get: function () {
  9964. return Camera._ORTHOGRAPHIC_CAMERA;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9970. get: function () {
  9971. return Camera._FOVMODE_VERTICAL_FIXED;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9977. get: function () {
  9978. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9984. get: function () {
  9985. return Camera._RIG_MODE_NONE;
  9986. },
  9987. enumerable: true,
  9988. configurable: true
  9989. });
  9990. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9991. get: function () {
  9992. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9998. get: function () {
  9999. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10005. get: function () {
  10006. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10012. get: function () {
  10013. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10019. get: function () {
  10020. return Camera._RIG_MODE_VR;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. Object.defineProperty(Camera.prototype, "globalPosition", {
  10026. get: function () {
  10027. return this._globalPosition;
  10028. },
  10029. enumerable: true,
  10030. configurable: true
  10031. });
  10032. Camera.prototype.getActiveMeshes = function () {
  10033. return this._activeMeshes;
  10034. };
  10035. Camera.prototype.isActiveMesh = function (mesh) {
  10036. return (this._activeMeshes.indexOf(mesh) !== -1);
  10037. };
  10038. //Cache
  10039. Camera.prototype._initCache = function () {
  10040. _super.prototype._initCache.call(this);
  10041. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10042. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10043. this._cache.mode = undefined;
  10044. this._cache.minZ = undefined;
  10045. this._cache.maxZ = undefined;
  10046. this._cache.fov = undefined;
  10047. this._cache.aspectRatio = undefined;
  10048. this._cache.orthoLeft = undefined;
  10049. this._cache.orthoRight = undefined;
  10050. this._cache.orthoBottom = undefined;
  10051. this._cache.orthoTop = undefined;
  10052. this._cache.renderWidth = undefined;
  10053. this._cache.renderHeight = undefined;
  10054. };
  10055. Camera.prototype._updateCache = function (ignoreParentClass) {
  10056. if (!ignoreParentClass) {
  10057. _super.prototype._updateCache.call(this);
  10058. }
  10059. var engine = this.getEngine();
  10060. this._cache.position.copyFrom(this.position);
  10061. this._cache.upVector.copyFrom(this.upVector);
  10062. this._cache.mode = this.mode;
  10063. this._cache.minZ = this.minZ;
  10064. this._cache.maxZ = this.maxZ;
  10065. this._cache.fov = this.fov;
  10066. this._cache.aspectRatio = engine.getAspectRatio(this);
  10067. this._cache.orthoLeft = this.orthoLeft;
  10068. this._cache.orthoRight = this.orthoRight;
  10069. this._cache.orthoBottom = this.orthoBottom;
  10070. this._cache.orthoTop = this.orthoTop;
  10071. this._cache.renderWidth = engine.getRenderWidth();
  10072. this._cache.renderHeight = engine.getRenderHeight();
  10073. };
  10074. Camera.prototype._updateFromScene = function () {
  10075. this.updateCache();
  10076. this._update();
  10077. };
  10078. // Synchronized
  10079. Camera.prototype._isSynchronized = function () {
  10080. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10081. };
  10082. Camera.prototype._isSynchronizedViewMatrix = function () {
  10083. if (!_super.prototype._isSynchronized.call(this))
  10084. return false;
  10085. return this._cache.position.equals(this.position)
  10086. && this._cache.upVector.equals(this.upVector)
  10087. && this.isSynchronizedWithParent();
  10088. };
  10089. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10090. var check = this._cache.mode === this.mode
  10091. && this._cache.minZ === this.minZ
  10092. && this._cache.maxZ === this.maxZ;
  10093. if (!check) {
  10094. return false;
  10095. }
  10096. var engine = this.getEngine();
  10097. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10098. check = this._cache.fov === this.fov
  10099. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10100. }
  10101. else {
  10102. check = this._cache.orthoLeft === this.orthoLeft
  10103. && this._cache.orthoRight === this.orthoRight
  10104. && this._cache.orthoBottom === this.orthoBottom
  10105. && this._cache.orthoTop === this.orthoTop
  10106. && this._cache.renderWidth === engine.getRenderWidth()
  10107. && this._cache.renderHeight === engine.getRenderHeight();
  10108. }
  10109. return check;
  10110. };
  10111. // Controls
  10112. Camera.prototype.attachControl = function (element) {
  10113. };
  10114. Camera.prototype.detachControl = function (element) {
  10115. };
  10116. Camera.prototype._update = function () {
  10117. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10118. this._updateRigCameras();
  10119. }
  10120. this._checkInputs();
  10121. };
  10122. Camera.prototype._checkInputs = function () {
  10123. };
  10124. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10125. if (insertAt === void 0) { insertAt = null; }
  10126. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10127. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10128. return 0;
  10129. }
  10130. if (insertAt == null || insertAt < 0) {
  10131. this._postProcesses.push(postProcess);
  10132. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10133. return this._postProcesses.length - 1;
  10134. }
  10135. var add = 0;
  10136. if (this._postProcesses[insertAt]) {
  10137. var start = this._postProcesses.length - 1;
  10138. for (var i = start; i >= insertAt + 1; --i) {
  10139. this._postProcesses[i + 1] = this._postProcesses[i];
  10140. }
  10141. add = 1;
  10142. }
  10143. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10144. if (this._postProcessesTakenIndices[i] < insertAt) {
  10145. continue;
  10146. }
  10147. start = this._postProcessesTakenIndices.length - 1;
  10148. for (var j = start; j >= i; --j) {
  10149. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10150. }
  10151. this._postProcessesTakenIndices[i] = insertAt;
  10152. break;
  10153. }
  10154. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10155. this._postProcessesTakenIndices.push(insertAt);
  10156. }
  10157. var result = insertAt + add;
  10158. this._postProcesses[result] = postProcess;
  10159. return result;
  10160. };
  10161. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10162. if (atIndices === void 0) { atIndices = null; }
  10163. var result = [];
  10164. if (!atIndices) {
  10165. var length = this._postProcesses.length;
  10166. for (var i = 0; i < length; i++) {
  10167. if (this._postProcesses[i] !== postProcess) {
  10168. continue;
  10169. }
  10170. delete this._postProcesses[i];
  10171. var index = this._postProcessesTakenIndices.indexOf(i);
  10172. this._postProcessesTakenIndices.splice(index, 1);
  10173. }
  10174. }
  10175. else {
  10176. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10177. for (i = 0; i < atIndices.length; i++) {
  10178. var foundPostProcess = this._postProcesses[atIndices[i]];
  10179. if (foundPostProcess !== postProcess) {
  10180. result.push(i);
  10181. continue;
  10182. }
  10183. delete this._postProcesses[atIndices[i]];
  10184. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10185. this._postProcessesTakenIndices.splice(index, 1);
  10186. }
  10187. }
  10188. return result;
  10189. };
  10190. Camera.prototype.getWorldMatrix = function () {
  10191. if (!this._worldMatrix) {
  10192. this._worldMatrix = BABYLON.Matrix.Identity();
  10193. }
  10194. var viewMatrix = this.getViewMatrix();
  10195. viewMatrix.invertToRef(this._worldMatrix);
  10196. return this._worldMatrix;
  10197. };
  10198. Camera.prototype._getViewMatrix = function () {
  10199. return BABYLON.Matrix.Identity();
  10200. };
  10201. Camera.prototype.getViewMatrix = function (force) {
  10202. this._computedViewMatrix = this._computeViewMatrix(force);
  10203. if (!force && this._isSynchronizedViewMatrix()) {
  10204. return this._computedViewMatrix;
  10205. }
  10206. if (!this.parent || !this.parent.getWorldMatrix) {
  10207. this._globalPosition.copyFrom(this.position);
  10208. }
  10209. else {
  10210. if (!this._worldMatrix) {
  10211. this._worldMatrix = BABYLON.Matrix.Identity();
  10212. }
  10213. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10214. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10215. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10216. this._computedViewMatrix.invert();
  10217. this._markSyncedWithParent();
  10218. }
  10219. this._currentRenderId = this.getScene().getRenderId();
  10220. return this._computedViewMatrix;
  10221. };
  10222. Camera.prototype._computeViewMatrix = function (force) {
  10223. if (!force && this._isSynchronizedViewMatrix()) {
  10224. return this._computedViewMatrix;
  10225. }
  10226. this._computedViewMatrix = this._getViewMatrix();
  10227. this._currentRenderId = this.getScene().getRenderId();
  10228. return this._computedViewMatrix;
  10229. };
  10230. Camera.prototype.getProjectionMatrix = function (force) {
  10231. if (!force && this._isSynchronizedProjectionMatrix()) {
  10232. return this._projectionMatrix;
  10233. }
  10234. var engine = this.getEngine();
  10235. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10236. if (this.minZ <= 0) {
  10237. this.minZ = 0.1;
  10238. }
  10239. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10240. return this._projectionMatrix;
  10241. }
  10242. var halfWidth = engine.getRenderWidth() / 2.0;
  10243. var halfHeight = engine.getRenderHeight() / 2.0;
  10244. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10245. return this._projectionMatrix;
  10246. };
  10247. Camera.prototype.dispose = function () {
  10248. // Remove from scene
  10249. this.getScene().removeCamera(this);
  10250. while (this._rigCameras.length > 0) {
  10251. this._rigCameras.pop().dispose();
  10252. }
  10253. // Postprocesses
  10254. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10255. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10256. }
  10257. };
  10258. // ---- Camera rigs section ----
  10259. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10260. while (this._rigCameras.length > 0) {
  10261. this._rigCameras.pop().dispose();
  10262. }
  10263. this.cameraRigMode = mode;
  10264. this._cameraRigParams = {};
  10265. switch (this.cameraRigMode) {
  10266. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10267. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10268. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10269. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10270. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10271. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10272. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10273. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10274. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10275. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10276. break;
  10277. }
  10278. var postProcesses = new Array();
  10279. switch (this.cameraRigMode) {
  10280. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10281. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10282. this._rigCameras[0].isIntermediate = true;
  10283. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10284. postProcesses[1].onApply = function (effect) {
  10285. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10286. };
  10287. break;
  10288. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10289. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10290. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10291. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10292. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10293. var secondCamIndex = 1 - firstCamIndex;
  10294. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10295. this._rigCameras[firstCamIndex].isIntermediate = true;
  10296. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10297. break;
  10298. case Camera.RIG_MODE_VR:
  10299. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10300. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10301. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10302. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10303. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10304. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10305. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10306. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10307. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10308. if (metrics.compensateDistorsion) {
  10309. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10310. }
  10311. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10312. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10313. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10314. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10315. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10316. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10317. if (metrics.compensateDistorsion) {
  10318. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10319. }
  10320. break;
  10321. }
  10322. this._update();
  10323. };
  10324. Camera.prototype._getVRProjectionMatrix = function () {
  10325. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10326. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10327. return this._projectionMatrix;
  10328. };
  10329. Camera.prototype.setCameraRigParameter = function (name, value) {
  10330. this._cameraRigParams[name] = value;
  10331. //provisionnally:
  10332. if (name === "interaxialDistance") {
  10333. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10334. }
  10335. };
  10336. /**
  10337. * May needs to be overridden by children so sub has required properties to be copied
  10338. */
  10339. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10340. return null;
  10341. };
  10342. /**
  10343. * May needs to be overridden by children
  10344. */
  10345. Camera.prototype._updateRigCameras = function () {
  10346. for (var i = 0; i < this._rigCameras.length; i++) {
  10347. this._rigCameras[i].minZ = this.minZ;
  10348. this._rigCameras[i].maxZ = this.maxZ;
  10349. this._rigCameras[i].fov = this.fov;
  10350. }
  10351. // only update viewport when ANAGLYPH
  10352. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10353. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10354. }
  10355. };
  10356. // Statics
  10357. Camera._PERSPECTIVE_CAMERA = 0;
  10358. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10359. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10360. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10361. Camera._RIG_MODE_NONE = 0;
  10362. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10363. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10364. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10365. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10366. Camera._RIG_MODE_VR = 20;
  10367. return Camera;
  10368. })(BABYLON.Node);
  10369. BABYLON.Camera = Camera;
  10370. })(BABYLON || (BABYLON = {}));
  10371. var BABYLON;
  10372. (function (BABYLON) {
  10373. var TargetCamera = (function (_super) {
  10374. __extends(TargetCamera, _super);
  10375. function TargetCamera(name, position, scene) {
  10376. _super.call(this, name, position, scene);
  10377. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10378. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10379. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10380. this.speed = 2.0;
  10381. this.noRotationConstraint = false;
  10382. this.lockedTarget = null;
  10383. this._currentTarget = BABYLON.Vector3.Zero();
  10384. this._viewMatrix = BABYLON.Matrix.Zero();
  10385. this._camMatrix = BABYLON.Matrix.Zero();
  10386. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10387. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10388. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10389. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10390. this._lookAtTemp = BABYLON.Matrix.Zero();
  10391. this._tempMatrix = BABYLON.Matrix.Zero();
  10392. }
  10393. TargetCamera.prototype.getFrontPosition = function (distance) {
  10394. var direction = this.getTarget().subtract(this.position);
  10395. direction.normalize();
  10396. direction.scaleInPlace(distance);
  10397. return this.globalPosition.add(direction);
  10398. };
  10399. TargetCamera.prototype._getLockedTargetPosition = function () {
  10400. if (!this.lockedTarget) {
  10401. return null;
  10402. }
  10403. return this.lockedTarget.position || this.lockedTarget;
  10404. };
  10405. // Cache
  10406. TargetCamera.prototype._initCache = function () {
  10407. _super.prototype._initCache.call(this);
  10408. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10409. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10410. };
  10411. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10412. if (!ignoreParentClass) {
  10413. _super.prototype._updateCache.call(this);
  10414. }
  10415. var lockedTargetPosition = this._getLockedTargetPosition();
  10416. if (!lockedTargetPosition) {
  10417. this._cache.lockedTarget = null;
  10418. }
  10419. else {
  10420. if (!this._cache.lockedTarget) {
  10421. this._cache.lockedTarget = lockedTargetPosition.clone();
  10422. }
  10423. else {
  10424. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10425. }
  10426. }
  10427. this._cache.rotation.copyFrom(this.rotation);
  10428. };
  10429. // Synchronized
  10430. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10431. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10432. return false;
  10433. }
  10434. var lockedTargetPosition = this._getLockedTargetPosition();
  10435. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10436. && this._cache.rotation.equals(this.rotation);
  10437. };
  10438. // Methods
  10439. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10440. var engine = this.getEngine();
  10441. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10442. };
  10443. // Target
  10444. TargetCamera.prototype.setTarget = function (target) {
  10445. this.upVector.normalize();
  10446. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10447. this._camMatrix.invert();
  10448. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10449. var vDir = target.subtract(this.position);
  10450. if (vDir.x >= 0.0) {
  10451. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10452. }
  10453. else {
  10454. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10455. }
  10456. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10457. if (isNaN(this.rotation.x)) {
  10458. this.rotation.x = 0;
  10459. }
  10460. if (isNaN(this.rotation.y)) {
  10461. this.rotation.y = 0;
  10462. }
  10463. if (isNaN(this.rotation.z)) {
  10464. this.rotation.z = 0;
  10465. }
  10466. };
  10467. TargetCamera.prototype.getTarget = function () {
  10468. return this._currentTarget;
  10469. };
  10470. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10471. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10472. };
  10473. TargetCamera.prototype._updatePosition = function () {
  10474. this.position.addInPlace(this.cameraDirection);
  10475. };
  10476. TargetCamera.prototype._checkInputs = function () {
  10477. var needToMove = this._decideIfNeedsToMove();
  10478. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10479. // Move
  10480. if (needToMove) {
  10481. this._updatePosition();
  10482. }
  10483. // Rotate
  10484. if (needToRotate) {
  10485. this.rotation.x += this.cameraRotation.x;
  10486. this.rotation.y += this.cameraRotation.y;
  10487. if (!this.noRotationConstraint) {
  10488. var limit = (Math.PI / 2) * 0.95;
  10489. if (this.rotation.x > limit)
  10490. this.rotation.x = limit;
  10491. if (this.rotation.x < -limit)
  10492. this.rotation.x = -limit;
  10493. }
  10494. }
  10495. // Inertia
  10496. if (needToMove) {
  10497. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10498. this.cameraDirection.x = 0;
  10499. }
  10500. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10501. this.cameraDirection.y = 0;
  10502. }
  10503. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10504. this.cameraDirection.z = 0;
  10505. }
  10506. this.cameraDirection.scaleInPlace(this.inertia);
  10507. }
  10508. if (needToRotate) {
  10509. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10510. this.cameraRotation.x = 0;
  10511. }
  10512. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10513. this.cameraRotation.y = 0;
  10514. }
  10515. this.cameraRotation.scaleInPlace(this.inertia);
  10516. }
  10517. _super.prototype._checkInputs.call(this);
  10518. };
  10519. TargetCamera.prototype._getViewMatrix = function () {
  10520. if (!this.lockedTarget) {
  10521. // Compute
  10522. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10523. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10524. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10525. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10526. this._lookAtTemp.invert();
  10527. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10528. }
  10529. else {
  10530. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10531. }
  10532. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10533. // Computing target and final matrix
  10534. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10535. }
  10536. else {
  10537. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10538. }
  10539. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10540. return this._viewMatrix;
  10541. };
  10542. TargetCamera.prototype._getVRViewMatrix = function () {
  10543. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10544. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10545. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10546. // Computing target and final matrix
  10547. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10548. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10549. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10550. return this._viewMatrix;
  10551. };
  10552. /**
  10553. * @override
  10554. * Override Camera.createRigCamera
  10555. */
  10556. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10557. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10558. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10559. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10560. rigCamera._cameraRigParams = {};
  10561. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10562. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10563. }
  10564. return rigCamera;
  10565. }
  10566. return null;
  10567. };
  10568. /**
  10569. * @override
  10570. * Override Camera._updateRigCameras
  10571. */
  10572. TargetCamera.prototype._updateRigCameras = function () {
  10573. switch (this.cameraRigMode) {
  10574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10575. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10576. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10578. case BABYLON.Camera.RIG_MODE_VR:
  10579. var camLeft = this._rigCameras[0];
  10580. var camRight = this._rigCameras[1];
  10581. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10582. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10583. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10584. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10585. camLeft.position.copyFrom(this.position);
  10586. camRight.position.copyFrom(this.position);
  10587. }
  10588. else {
  10589. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10590. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10591. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10592. camLeft.setTarget(this.getTarget());
  10593. camRight.setTarget(this.getTarget());
  10594. }
  10595. break;
  10596. }
  10597. _super.prototype._updateRigCameras.call(this);
  10598. };
  10599. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10600. if (!this._rigCamTransformMatrix) {
  10601. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10602. }
  10603. var target = this.getTarget();
  10604. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10605. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10606. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10607. };
  10608. return TargetCamera;
  10609. })(BABYLON.Camera);
  10610. BABYLON.TargetCamera = TargetCamera;
  10611. })(BABYLON || (BABYLON = {}));
  10612. var BABYLON;
  10613. (function (BABYLON) {
  10614. var FreeCamera = (function (_super) {
  10615. __extends(FreeCamera, _super);
  10616. function FreeCamera(name, position, scene) {
  10617. var _this = this;
  10618. _super.call(this, name, position, scene);
  10619. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10620. this.keysUp = [38];
  10621. this.keysDown = [40];
  10622. this.keysLeft = [37];
  10623. this.keysRight = [39];
  10624. this.checkCollisions = false;
  10625. this.applyGravity = false;
  10626. this.angularSensibility = 2000.0;
  10627. this._keys = [];
  10628. this._collider = new BABYLON.Collider();
  10629. this._needMoveForGravity = false;
  10630. this._oldPosition = BABYLON.Vector3.Zero();
  10631. this._diffPosition = BABYLON.Vector3.Zero();
  10632. this._newPosition = BABYLON.Vector3.Zero();
  10633. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10634. if (collidedMesh === void 0) { collidedMesh = null; }
  10635. //TODO move this to the collision coordinator!
  10636. if (_this.getScene().workerCollisions)
  10637. newPosition.multiplyInPlace(_this._collider.radius);
  10638. var updatePosition = function (newPos) {
  10639. _this._newPosition.copyFrom(newPos);
  10640. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10641. var oldPosition = _this.position.clone();
  10642. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10643. _this.position.addInPlace(_this._diffPosition);
  10644. if (_this.onCollide && collidedMesh) {
  10645. _this.onCollide(collidedMesh);
  10646. }
  10647. }
  10648. };
  10649. updatePosition(newPosition);
  10650. };
  10651. }
  10652. // Controls
  10653. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10654. var _this = this;
  10655. var previousPosition;
  10656. var engine = this.getEngine();
  10657. if (this._attachedElement) {
  10658. return;
  10659. }
  10660. this._attachedElement = element;
  10661. if (this._onMouseDown === undefined) {
  10662. this._onMouseDown = function (evt) {
  10663. previousPosition = {
  10664. x: evt.clientX,
  10665. y: evt.clientY
  10666. };
  10667. if (!noPreventDefault) {
  10668. evt.preventDefault();
  10669. }
  10670. };
  10671. this._onMouseUp = function (evt) {
  10672. previousPosition = null;
  10673. if (!noPreventDefault) {
  10674. evt.preventDefault();
  10675. }
  10676. };
  10677. this._onMouseOut = function (evt) {
  10678. previousPosition = null;
  10679. _this._keys = [];
  10680. if (!noPreventDefault) {
  10681. evt.preventDefault();
  10682. }
  10683. };
  10684. this._onMouseMove = function (evt) {
  10685. if (!previousPosition && !engine.isPointerLock) {
  10686. return;
  10687. }
  10688. var offsetX;
  10689. var offsetY;
  10690. if (!engine.isPointerLock) {
  10691. offsetX = evt.clientX - previousPosition.x;
  10692. offsetY = evt.clientY - previousPosition.y;
  10693. }
  10694. else {
  10695. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10696. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10697. }
  10698. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10699. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10700. previousPosition = {
  10701. x: evt.clientX,
  10702. y: evt.clientY
  10703. };
  10704. if (!noPreventDefault) {
  10705. evt.preventDefault();
  10706. }
  10707. };
  10708. this._onKeyDown = function (evt) {
  10709. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10710. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10711. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10712. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10713. var index = _this._keys.indexOf(evt.keyCode);
  10714. if (index === -1) {
  10715. _this._keys.push(evt.keyCode);
  10716. }
  10717. if (!noPreventDefault) {
  10718. evt.preventDefault();
  10719. }
  10720. }
  10721. };
  10722. this._onKeyUp = function (evt) {
  10723. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10724. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10725. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10726. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10727. var index = _this._keys.indexOf(evt.keyCode);
  10728. if (index >= 0) {
  10729. _this._keys.splice(index, 1);
  10730. }
  10731. if (!noPreventDefault) {
  10732. evt.preventDefault();
  10733. }
  10734. }
  10735. };
  10736. this._onLostFocus = function () {
  10737. _this._keys = [];
  10738. };
  10739. this._reset = function () {
  10740. _this._keys = [];
  10741. previousPosition = null;
  10742. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10743. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10744. };
  10745. }
  10746. element.addEventListener("mousedown", this._onMouseDown, false);
  10747. element.addEventListener("mouseup", this._onMouseUp, false);
  10748. element.addEventListener("mouseout", this._onMouseOut, false);
  10749. element.addEventListener("mousemove", this._onMouseMove, false);
  10750. BABYLON.Tools.RegisterTopRootEvents([
  10751. { name: "keydown", handler: this._onKeyDown },
  10752. { name: "keyup", handler: this._onKeyUp },
  10753. { name: "blur", handler: this._onLostFocus }
  10754. ]);
  10755. };
  10756. FreeCamera.prototype.detachControl = function (element) {
  10757. if (this._attachedElement != element) {
  10758. return;
  10759. }
  10760. element.removeEventListener("mousedown", this._onMouseDown);
  10761. element.removeEventListener("mouseup", this._onMouseUp);
  10762. element.removeEventListener("mouseout", this._onMouseOut);
  10763. element.removeEventListener("mousemove", this._onMouseMove);
  10764. BABYLON.Tools.UnregisterTopRootEvents([
  10765. { name: "keydown", handler: this._onKeyDown },
  10766. { name: "keyup", handler: this._onKeyUp },
  10767. { name: "blur", handler: this._onLostFocus }
  10768. ]);
  10769. this._attachedElement = null;
  10770. if (this._reset) {
  10771. this._reset();
  10772. }
  10773. };
  10774. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10775. var globalPosition;
  10776. if (this.parent) {
  10777. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10778. }
  10779. else {
  10780. globalPosition = this.position;
  10781. }
  10782. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10783. this._collider.radius = this.ellipsoid;
  10784. //add gravity to the velocity to prevent the dual-collision checking
  10785. if (this.applyGravity) {
  10786. velocity.addInPlace(this.getScene().gravity);
  10787. }
  10788. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10789. };
  10790. FreeCamera.prototype._checkInputs = function () {
  10791. if (!this._localDirection) {
  10792. this._localDirection = BABYLON.Vector3.Zero();
  10793. this._transformedDirection = BABYLON.Vector3.Zero();
  10794. }
  10795. // Keyboard
  10796. for (var index = 0; index < this._keys.length; index++) {
  10797. var keyCode = this._keys[index];
  10798. var speed = this._computeLocalCameraSpeed();
  10799. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10800. this._localDirection.copyFromFloats(-speed, 0, 0);
  10801. }
  10802. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10803. this._localDirection.copyFromFloats(0, 0, speed);
  10804. }
  10805. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10806. this._localDirection.copyFromFloats(speed, 0, 0);
  10807. }
  10808. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10809. this._localDirection.copyFromFloats(0, 0, -speed);
  10810. }
  10811. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10812. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10813. this.cameraDirection.addInPlace(this._transformedDirection);
  10814. }
  10815. _super.prototype._checkInputs.call(this);
  10816. };
  10817. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10818. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10819. };
  10820. FreeCamera.prototype._updatePosition = function () {
  10821. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10822. this._collideWithWorld(this.cameraDirection);
  10823. }
  10824. else {
  10825. this.position.addInPlace(this.cameraDirection);
  10826. }
  10827. };
  10828. return FreeCamera;
  10829. })(BABYLON.TargetCamera);
  10830. BABYLON.FreeCamera = FreeCamera;
  10831. })(BABYLON || (BABYLON = {}));
  10832. var BABYLON;
  10833. (function (BABYLON) {
  10834. var FollowCamera = (function (_super) {
  10835. __extends(FollowCamera, _super);
  10836. function FollowCamera(name, position, scene) {
  10837. _super.call(this, name, position, scene);
  10838. this.radius = 12;
  10839. this.rotationOffset = 0;
  10840. this.heightOffset = 4;
  10841. this.cameraAcceleration = 0.05;
  10842. this.maxCameraSpeed = 20;
  10843. }
  10844. FollowCamera.prototype.getRadians = function (degrees) {
  10845. return degrees * Math.PI / 180;
  10846. };
  10847. FollowCamera.prototype.follow = function (cameraTarget) {
  10848. if (!cameraTarget)
  10849. return;
  10850. var yRotation;
  10851. if (cameraTarget.rotationQuaternion) {
  10852. var rotMatrix = new BABYLON.Matrix();
  10853. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10854. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10855. }
  10856. else {
  10857. yRotation = cameraTarget.rotation.y;
  10858. }
  10859. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10860. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10861. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10862. var dx = targetX - this.position.x;
  10863. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10864. var dz = (targetZ) - this.position.z;
  10865. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10866. var vy = dy * this.cameraAcceleration;
  10867. var vz = dz * this.cameraAcceleration * 2;
  10868. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10869. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10870. }
  10871. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10872. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10873. }
  10874. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10875. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10876. }
  10877. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10878. this.setTarget(cameraTarget.position);
  10879. };
  10880. FollowCamera.prototype._checkInputs = function () {
  10881. _super.prototype._checkInputs.call(this);
  10882. this.follow(this.target);
  10883. };
  10884. return FollowCamera;
  10885. })(BABYLON.TargetCamera);
  10886. BABYLON.FollowCamera = FollowCamera;
  10887. var ArcFollowCamera = (function (_super) {
  10888. __extends(ArcFollowCamera, _super);
  10889. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10890. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10891. this.alpha = alpha;
  10892. this.beta = beta;
  10893. this.radius = radius;
  10894. this.target = target;
  10895. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10896. this.follow();
  10897. }
  10898. ArcFollowCamera.prototype.follow = function () {
  10899. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10900. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10901. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10902. this.position = this.target.position.add(this._cartesianCoordinates);
  10903. this.setTarget(this.target.position);
  10904. };
  10905. ArcFollowCamera.prototype._checkInputs = function () {
  10906. _super.prototype._checkInputs.call(this);
  10907. this.follow();
  10908. };
  10909. return ArcFollowCamera;
  10910. })(BABYLON.TargetCamera);
  10911. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10912. })(BABYLON || (BABYLON = {}));
  10913. var BABYLON;
  10914. (function (BABYLON) {
  10915. // We're mainly based on the logic defined into the FreeCamera code
  10916. var TouchCamera = (function (_super) {
  10917. __extends(TouchCamera, _super);
  10918. function TouchCamera(name, position, scene) {
  10919. _super.call(this, name, position, scene);
  10920. this._offsetX = null;
  10921. this._offsetY = null;
  10922. this._pointerCount = 0;
  10923. this._pointerPressed = [];
  10924. this.angularSensibility = 200000.0;
  10925. this.moveSensibility = 500.0;
  10926. }
  10927. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10928. var _this = this;
  10929. var previousPosition;
  10930. if (this._attachedCanvas) {
  10931. return;
  10932. }
  10933. this._attachedCanvas = canvas;
  10934. if (this._onPointerDown === undefined) {
  10935. this._onPointerDown = function (evt) {
  10936. if (!noPreventDefault) {
  10937. evt.preventDefault();
  10938. }
  10939. _this._pointerPressed.push(evt.pointerId);
  10940. if (_this._pointerPressed.length !== 1) {
  10941. return;
  10942. }
  10943. previousPosition = {
  10944. x: evt.clientX,
  10945. y: evt.clientY
  10946. };
  10947. };
  10948. this._onPointerUp = function (evt) {
  10949. if (!noPreventDefault) {
  10950. evt.preventDefault();
  10951. }
  10952. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10953. if (index === -1) {
  10954. return;
  10955. }
  10956. _this._pointerPressed.splice(index, 1);
  10957. if (index != 0) {
  10958. return;
  10959. }
  10960. previousPosition = null;
  10961. _this._offsetX = null;
  10962. _this._offsetY = null;
  10963. };
  10964. this._onPointerMove = function (evt) {
  10965. if (!noPreventDefault) {
  10966. evt.preventDefault();
  10967. }
  10968. if (!previousPosition) {
  10969. return;
  10970. }
  10971. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10972. if (index != 0) {
  10973. return;
  10974. }
  10975. _this._offsetX = evt.clientX - previousPosition.x;
  10976. _this._offsetY = -(evt.clientY - previousPosition.y);
  10977. };
  10978. this._onLostFocus = function () {
  10979. _this._offsetX = null;
  10980. _this._offsetY = null;
  10981. };
  10982. }
  10983. canvas.addEventListener("pointerdown", this._onPointerDown);
  10984. canvas.addEventListener("pointerup", this._onPointerUp);
  10985. canvas.addEventListener("pointerout", this._onPointerUp);
  10986. canvas.addEventListener("pointermove", this._onPointerMove);
  10987. BABYLON.Tools.RegisterTopRootEvents([
  10988. { name: "blur", handler: this._onLostFocus }
  10989. ]);
  10990. };
  10991. TouchCamera.prototype.detachControl = function (canvas) {
  10992. if (this._attachedCanvas != canvas) {
  10993. return;
  10994. }
  10995. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10996. canvas.removeEventListener("pointerup", this._onPointerUp);
  10997. canvas.removeEventListener("pointerout", this._onPointerUp);
  10998. canvas.removeEventListener("pointermove", this._onPointerMove);
  10999. BABYLON.Tools.UnregisterTopRootEvents([
  11000. { name: "blur", handler: this._onLostFocus }
  11001. ]);
  11002. this._attachedCanvas = null;
  11003. };
  11004. TouchCamera.prototype._checkInputs = function () {
  11005. if (this._offsetX) {
  11006. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11007. if (this._pointerPressed.length > 1) {
  11008. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11009. }
  11010. else {
  11011. var speed = this._computeLocalCameraSpeed();
  11012. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11013. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11014. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11015. }
  11016. }
  11017. _super.prototype._checkInputs.call(this);
  11018. };
  11019. return TouchCamera;
  11020. })(BABYLON.FreeCamera);
  11021. BABYLON.TouchCamera = TouchCamera;
  11022. })(BABYLON || (BABYLON = {}));
  11023. var BABYLON;
  11024. (function (BABYLON) {
  11025. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11026. var ArcRotateCamera = (function (_super) {
  11027. __extends(ArcRotateCamera, _super);
  11028. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11029. var _this = this;
  11030. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11031. this.alpha = alpha;
  11032. this.beta = beta;
  11033. this.radius = radius;
  11034. this.target = target;
  11035. this.inertialAlphaOffset = 0;
  11036. this.inertialBetaOffset = 0;
  11037. this.inertialRadiusOffset = 0;
  11038. this.lowerAlphaLimit = null;
  11039. this.upperAlphaLimit = null;
  11040. this.lowerBetaLimit = 0.01;
  11041. this.upperBetaLimit = Math.PI;
  11042. this.lowerRadiusLimit = null;
  11043. this.upperRadiusLimit = null;
  11044. this.angularSensibilityX = 1000.0;
  11045. this.angularSensibilityY = 1000.0;
  11046. this.wheelPrecision = 3.0;
  11047. this.pinchPrecision = 2.0;
  11048. this.panningSensibility = 50.0;
  11049. this.inertialPanningX = 0;
  11050. this.inertialPanningY = 0;
  11051. this.keysUp = [38];
  11052. this.keysDown = [40];
  11053. this.keysLeft = [37];
  11054. this.keysRight = [39];
  11055. this.zoomOnFactor = 1;
  11056. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11057. this.pinchInwards = true;
  11058. this.allowUpsideDown = true;
  11059. this._keys = [];
  11060. this._viewMatrix = new BABYLON.Matrix();
  11061. this._isRightClick = false;
  11062. this._isCtrlPushed = false;
  11063. this.checkCollisions = false;
  11064. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11065. this._collider = new BABYLON.Collider();
  11066. this._previousPosition = BABYLON.Vector3.Zero();
  11067. this._collisionVelocity = BABYLON.Vector3.Zero();
  11068. this._newPosition = BABYLON.Vector3.Zero();
  11069. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11070. if (collidedMesh === void 0) { collidedMesh = null; }
  11071. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11072. newPosition.multiplyInPlace(_this._collider.radius);
  11073. }
  11074. if (!collidedMesh) {
  11075. _this._previousPosition.copyFrom(_this.position);
  11076. }
  11077. else {
  11078. _this.setPosition(_this.position);
  11079. if (_this.onCollide) {
  11080. _this.onCollide(collidedMesh);
  11081. }
  11082. }
  11083. // Recompute because of constraints
  11084. var cosa = Math.cos(_this.alpha);
  11085. var sina = Math.sin(_this.alpha);
  11086. var cosb = Math.cos(_this.beta);
  11087. var sinb = Math.sin(_this.beta);
  11088. var target = _this._getTargetPosition();
  11089. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11090. _this.position.copyFrom(_this._newPosition);
  11091. var up = _this.upVector;
  11092. if (_this.allowUpsideDown && _this.beta < 0) {
  11093. var up = up.clone();
  11094. up = up.negate();
  11095. }
  11096. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11097. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11098. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11099. _this._collisionTriggered = false;
  11100. };
  11101. if (!this.target) {
  11102. this.target = BABYLON.Vector3.Zero();
  11103. }
  11104. this.getViewMatrix();
  11105. }
  11106. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11107. //deprecated angularSensibility support
  11108. get: function () {
  11109. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11110. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11111. },
  11112. //deprecated angularSensibility support
  11113. set: function (value) {
  11114. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11115. this.angularSensibilityX = value;
  11116. this.angularSensibilityY = value;
  11117. },
  11118. enumerable: true,
  11119. configurable: true
  11120. });
  11121. ArcRotateCamera.prototype._getTargetPosition = function () {
  11122. return this.target.position || this.target;
  11123. };
  11124. // Cache
  11125. ArcRotateCamera.prototype._initCache = function () {
  11126. _super.prototype._initCache.call(this);
  11127. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11128. this._cache.alpha = undefined;
  11129. this._cache.beta = undefined;
  11130. this._cache.radius = undefined;
  11131. this._cache.targetScreenOffset = undefined;
  11132. };
  11133. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11134. if (!ignoreParentClass) {
  11135. _super.prototype._updateCache.call(this);
  11136. }
  11137. this._cache.target.copyFrom(this._getTargetPosition());
  11138. this._cache.alpha = this.alpha;
  11139. this._cache.beta = this.beta;
  11140. this._cache.radius = this.radius;
  11141. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11142. };
  11143. // Synchronized
  11144. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11145. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11146. return false;
  11147. return this._cache.target.equals(this._getTargetPosition())
  11148. && this._cache.alpha === this.alpha
  11149. && this._cache.beta === this.beta
  11150. && this._cache.radius === this.radius
  11151. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11152. };
  11153. // Methods
  11154. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11155. var _this = this;
  11156. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11157. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11158. var previousPinchDistance = 0;
  11159. var pointers = new BABYLON.SmartCollection();
  11160. if (this._attachedElement) {
  11161. return;
  11162. }
  11163. this._attachedElement = element;
  11164. var engine = this.getEngine();
  11165. if (this._onPointerDown === undefined) {
  11166. this._onPointerDown = function (evt) {
  11167. // Manage panning with right click
  11168. _this._isRightClick = evt.button === 2 ? true : false;
  11169. // manage pointers
  11170. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11171. cacheSoloPointer = pointers.item(evt.pointerId);
  11172. if (!noPreventDefault) {
  11173. evt.preventDefault();
  11174. }
  11175. };
  11176. this._onPointerUp = function (evt) {
  11177. cacheSoloPointer = null;
  11178. previousPinchDistance = 0;
  11179. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11180. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11181. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11182. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11183. pointers.empty();
  11184. if (!noPreventDefault) {
  11185. evt.preventDefault();
  11186. }
  11187. };
  11188. this._onContextMenu = function (evt) {
  11189. evt.preventDefault();
  11190. };
  11191. this._onPointerMove = function (evt) {
  11192. if (!noPreventDefault) {
  11193. evt.preventDefault();
  11194. }
  11195. switch (pointers.count) {
  11196. case 1:
  11197. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11198. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11199. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11200. }
  11201. else {
  11202. var offsetX = evt.clientX - cacheSoloPointer.x;
  11203. var offsetY = evt.clientY - cacheSoloPointer.y;
  11204. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11205. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11206. }
  11207. cacheSoloPointer.x = evt.clientX;
  11208. cacheSoloPointer.y = evt.clientY;
  11209. break;
  11210. case 2:
  11211. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11212. pointers.item(evt.pointerId).x = evt.clientX;
  11213. pointers.item(evt.pointerId).y = evt.clientY;
  11214. var direction = _this.pinchInwards ? 1 : -1;
  11215. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11216. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11217. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11218. if (previousPinchDistance === 0) {
  11219. previousPinchDistance = pinchSquaredDistance;
  11220. return;
  11221. }
  11222. if (pinchSquaredDistance !== previousPinchDistance) {
  11223. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11224. previousPinchDistance = pinchSquaredDistance;
  11225. }
  11226. break;
  11227. default:
  11228. if (pointers.item(evt.pointerId)) {
  11229. pointers.item(evt.pointerId).x = evt.clientX;
  11230. pointers.item(evt.pointerId).y = evt.clientY;
  11231. }
  11232. }
  11233. };
  11234. this._onMouseMove = function (evt) {
  11235. if (!engine.isPointerLock) {
  11236. return;
  11237. }
  11238. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11239. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11240. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11241. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11242. if (!noPreventDefault) {
  11243. evt.preventDefault();
  11244. }
  11245. };
  11246. this._wheel = function (event) {
  11247. var delta = 0;
  11248. if (event.wheelDelta) {
  11249. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11250. }
  11251. else if (event.detail) {
  11252. delta = -event.detail / _this.wheelPrecision;
  11253. }
  11254. if (delta)
  11255. _this.inertialRadiusOffset += delta;
  11256. if (event.preventDefault) {
  11257. if (!noPreventDefault) {
  11258. event.preventDefault();
  11259. }
  11260. }
  11261. };
  11262. this._onKeyDown = function (evt) {
  11263. _this._isCtrlPushed = evt.ctrlKey;
  11264. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11265. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11266. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11267. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11268. var index = _this._keys.indexOf(evt.keyCode);
  11269. if (index === -1) {
  11270. _this._keys.push(evt.keyCode);
  11271. }
  11272. if (evt.preventDefault) {
  11273. if (!noPreventDefault) {
  11274. evt.preventDefault();
  11275. }
  11276. }
  11277. }
  11278. };
  11279. this._onKeyUp = function (evt) {
  11280. _this._isCtrlPushed = evt.ctrlKey;
  11281. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11282. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11283. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11284. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11285. var index = _this._keys.indexOf(evt.keyCode);
  11286. if (index >= 0) {
  11287. _this._keys.splice(index, 1);
  11288. }
  11289. if (evt.preventDefault) {
  11290. if (!noPreventDefault) {
  11291. evt.preventDefault();
  11292. }
  11293. }
  11294. }
  11295. };
  11296. this._onLostFocus = function () {
  11297. _this._keys = [];
  11298. pointers.empty();
  11299. previousPinchDistance = 0;
  11300. cacheSoloPointer = null;
  11301. };
  11302. this._onGestureStart = function (e) {
  11303. if (window.MSGesture === undefined) {
  11304. return;
  11305. }
  11306. if (!_this._MSGestureHandler) {
  11307. _this._MSGestureHandler = new MSGesture();
  11308. _this._MSGestureHandler.target = element;
  11309. }
  11310. _this._MSGestureHandler.addPointer(e.pointerId);
  11311. };
  11312. this._onGesture = function (e) {
  11313. _this.radius *= e.scale;
  11314. if (e.preventDefault) {
  11315. if (!noPreventDefault) {
  11316. e.stopPropagation();
  11317. e.preventDefault();
  11318. }
  11319. }
  11320. };
  11321. this._reset = function () {
  11322. _this._keys = [];
  11323. _this.inertialAlphaOffset = 0;
  11324. _this.inertialBetaOffset = 0;
  11325. _this.inertialRadiusOffset = 0;
  11326. pointers.empty();
  11327. previousPinchDistance = 0;
  11328. cacheSoloPointer = null;
  11329. };
  11330. }
  11331. if (!useCtrlForPanning) {
  11332. element.addEventListener("contextmenu", this._onContextMenu, false);
  11333. }
  11334. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11335. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11336. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11337. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11338. element.addEventListener("mousemove", this._onMouseMove, false);
  11339. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11340. element.addEventListener("MSGestureChange", this._onGesture, false);
  11341. element.addEventListener('mousewheel', this._wheel, false);
  11342. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11343. BABYLON.Tools.RegisterTopRootEvents([
  11344. { name: "keydown", handler: this._onKeyDown },
  11345. { name: "keyup", handler: this._onKeyUp },
  11346. { name: "blur", handler: this._onLostFocus }
  11347. ]);
  11348. };
  11349. ArcRotateCamera.prototype.detachControl = function (element) {
  11350. if (this._attachedElement !== element) {
  11351. return;
  11352. }
  11353. element.removeEventListener("contextmenu", this._onContextMenu);
  11354. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11355. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11356. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11357. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11358. element.removeEventListener("mousemove", this._onMouseMove);
  11359. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11360. element.removeEventListener("MSGestureChange", this._onGesture);
  11361. element.removeEventListener('mousewheel', this._wheel);
  11362. element.removeEventListener('DOMMouseScroll', this._wheel);
  11363. BABYLON.Tools.UnregisterTopRootEvents([
  11364. { name: "keydown", handler: this._onKeyDown },
  11365. { name: "keyup", handler: this._onKeyUp },
  11366. { name: "blur", handler: this._onLostFocus }
  11367. ]);
  11368. this._MSGestureHandler = null;
  11369. this._attachedElement = null;
  11370. if (this._reset) {
  11371. this._reset();
  11372. }
  11373. };
  11374. ArcRotateCamera.prototype._checkInputs = function () {
  11375. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11376. if (this._collisionTriggered) {
  11377. return;
  11378. }
  11379. // Keyboard
  11380. for (var index = 0; index < this._keys.length; index++) {
  11381. var keyCode = this._keys[index];
  11382. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11383. this.inertialAlphaOffset -= 0.01;
  11384. }
  11385. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11386. this.inertialBetaOffset -= 0.01;
  11387. }
  11388. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11389. this.inertialAlphaOffset += 0.01;
  11390. }
  11391. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11392. this.inertialBetaOffset += 0.01;
  11393. }
  11394. }
  11395. // Inertia
  11396. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11397. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11398. this.beta += this.inertialBetaOffset;
  11399. this.radius -= this.inertialRadiusOffset;
  11400. this.inertialAlphaOffset *= this.inertia;
  11401. this.inertialBetaOffset *= this.inertia;
  11402. this.inertialRadiusOffset *= this.inertia;
  11403. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11404. this.inertialAlphaOffset = 0;
  11405. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11406. this.inertialBetaOffset = 0;
  11407. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11408. this.inertialRadiusOffset = 0;
  11409. }
  11410. // Panning inertia
  11411. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11412. if (!this._localDirection) {
  11413. this._localDirection = BABYLON.Vector3.Zero();
  11414. this._transformedDirection = BABYLON.Vector3.Zero();
  11415. }
  11416. this.inertialPanningX *= this.inertia;
  11417. this.inertialPanningY *= this.inertia;
  11418. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11419. this.inertialPanningX = 0;
  11420. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11421. this.inertialPanningY = 0;
  11422. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11423. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11424. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11425. this.target.addInPlace(this._transformedDirection);
  11426. }
  11427. // Limits
  11428. this._checkLimits();
  11429. _super.prototype._checkInputs.call(this);
  11430. };
  11431. ArcRotateCamera.prototype._checkLimits = function () {
  11432. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11433. if (this.allowUpsideDown && this.beta > Math.PI) {
  11434. this.beta = this.beta - (2 * Math.PI);
  11435. }
  11436. }
  11437. else {
  11438. if (this.beta < this.lowerBetaLimit) {
  11439. this.beta = this.lowerBetaLimit;
  11440. }
  11441. }
  11442. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11443. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11444. this.beta = this.beta + (2 * Math.PI);
  11445. }
  11446. }
  11447. else {
  11448. if (this.beta > this.upperBetaLimit) {
  11449. this.beta = this.upperBetaLimit;
  11450. }
  11451. }
  11452. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11453. this.alpha = this.lowerAlphaLimit;
  11454. }
  11455. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11456. this.alpha = this.upperAlphaLimit;
  11457. }
  11458. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11459. this.radius = this.lowerRadiusLimit;
  11460. }
  11461. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11462. this.radius = this.upperRadiusLimit;
  11463. }
  11464. };
  11465. ArcRotateCamera.prototype.setPosition = function (position) {
  11466. var radiusv3 = position.subtract(this._getTargetPosition());
  11467. this.radius = radiusv3.length();
  11468. // Alpha
  11469. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11470. if (radiusv3.z < 0) {
  11471. this.alpha = 2 * Math.PI - this.alpha;
  11472. }
  11473. // Beta
  11474. this.beta = Math.acos(radiusv3.y / this.radius);
  11475. this._checkLimits();
  11476. };
  11477. ArcRotateCamera.prototype.setTarget = function (target) {
  11478. this.target = target;
  11479. };
  11480. ArcRotateCamera.prototype._getViewMatrix = function () {
  11481. // Compute
  11482. var cosa = Math.cos(this.alpha);
  11483. var sina = Math.sin(this.alpha);
  11484. var cosb = Math.cos(this.beta);
  11485. var sinb = Math.sin(this.beta);
  11486. var target = this._getTargetPosition();
  11487. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11488. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11489. this._collider.radius = this.collisionRadius;
  11490. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11491. this._collisionTriggered = true;
  11492. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11493. }
  11494. else {
  11495. this.position.copyFrom(this._newPosition);
  11496. var up = this.upVector;
  11497. if (this.allowUpsideDown && this.beta < 0) {
  11498. var up = up.clone();
  11499. up = up.negate();
  11500. }
  11501. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11502. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11503. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11504. }
  11505. return this._viewMatrix;
  11506. };
  11507. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11508. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11509. meshes = meshes || this.getScene().meshes;
  11510. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11511. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11512. this.radius = distance * this.zoomOnFactor;
  11513. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11514. };
  11515. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11516. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11517. var meshesOrMinMaxVector;
  11518. var distance;
  11519. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11520. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11521. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11522. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11523. }
  11524. else {
  11525. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11526. distance = meshesOrMinMaxVectorAndDistance.distance;
  11527. }
  11528. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11529. if (!doNotUpdateMaxZ) {
  11530. this.maxZ = distance * 2;
  11531. }
  11532. };
  11533. /**
  11534. * @override
  11535. * Override Camera.createRigCamera
  11536. */
  11537. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11538. switch (this.cameraRigMode) {
  11539. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11540. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11541. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11542. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11543. case BABYLON.Camera.RIG_MODE_VR:
  11544. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11545. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11546. }
  11547. };
  11548. /**
  11549. * @override
  11550. * Override Camera._updateRigCameras
  11551. */
  11552. ArcRotateCamera.prototype._updateRigCameras = function () {
  11553. switch (this.cameraRigMode) {
  11554. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11555. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11558. case BABYLON.Camera.RIG_MODE_VR:
  11559. var camLeft = this._rigCameras[0];
  11560. var camRight = this._rigCameras[1];
  11561. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11562. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11563. camLeft.beta = camRight.beta = this.beta;
  11564. camLeft.radius = camRight.radius = this.radius;
  11565. break;
  11566. }
  11567. _super.prototype._updateRigCameras.call(this);
  11568. };
  11569. return ArcRotateCamera;
  11570. })(BABYLON.TargetCamera);
  11571. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11572. })(BABYLON || (BABYLON = {}));
  11573. var BABYLON;
  11574. (function (BABYLON) {
  11575. // We're mainly based on the logic defined into the FreeCamera code
  11576. var DeviceOrientationCamera = (function (_super) {
  11577. __extends(DeviceOrientationCamera, _super);
  11578. function DeviceOrientationCamera(name, position, scene) {
  11579. var _this = this;
  11580. _super.call(this, name, position, scene);
  11581. this._offsetX = null;
  11582. this._offsetY = null;
  11583. this._orientationGamma = 0;
  11584. this._orientationBeta = 0;
  11585. this._initialOrientationGamma = 0;
  11586. this._initialOrientationBeta = 0;
  11587. this.angularSensibility = 10000.0;
  11588. this.moveSensibility = 50.0;
  11589. window.addEventListener("resize", function () {
  11590. _this._initialOrientationGamma = null;
  11591. }, false);
  11592. }
  11593. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11594. var _this = this;
  11595. if (this._attachedCanvas) {
  11596. return;
  11597. }
  11598. this._attachedCanvas = canvas;
  11599. if (!this._orientationChanged) {
  11600. this._orientationChanged = function (evt) {
  11601. if (!_this._initialOrientationGamma) {
  11602. _this._initialOrientationGamma = evt.gamma;
  11603. _this._initialOrientationBeta = evt.beta;
  11604. }
  11605. _this._orientationGamma = evt.gamma;
  11606. _this._orientationBeta = evt.beta;
  11607. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11608. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11609. };
  11610. }
  11611. window.addEventListener("deviceorientation", this._orientationChanged);
  11612. };
  11613. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11614. if (this._attachedCanvas != canvas) {
  11615. return;
  11616. }
  11617. window.removeEventListener("deviceorientation", this._orientationChanged);
  11618. this._attachedCanvas = null;
  11619. this._orientationGamma = 0;
  11620. this._orientationBeta = 0;
  11621. this._initialOrientationGamma = 0;
  11622. this._initialOrientationBeta = 0;
  11623. };
  11624. DeviceOrientationCamera.prototype._checkInputs = function () {
  11625. if (!this._offsetX) {
  11626. return;
  11627. }
  11628. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11629. var speed = this._computeLocalCameraSpeed();
  11630. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11631. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11632. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11633. _super.prototype._checkInputs.call(this);
  11634. };
  11635. return DeviceOrientationCamera;
  11636. })(BABYLON.FreeCamera);
  11637. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11638. })(BABYLON || (BABYLON = {}));
  11639. var BABYLON;
  11640. (function (BABYLON) {
  11641. var Gamepads = (function () {
  11642. function Gamepads(ongamedpadconnected) {
  11643. var _this = this;
  11644. this.babylonGamepads = [];
  11645. this.oneGamepadConnected = false;
  11646. this.isMonitoring = false;
  11647. this.gamepadEventSupported = 'GamepadEvent' in window;
  11648. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11649. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11650. 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=";
  11651. this._callbackGamepadConnected = ongamedpadconnected;
  11652. if (this.gamepadSupportAvailable) {
  11653. // Checking if the gamepad connected event is supported (like in Firefox)
  11654. if (this.gamepadEventSupported) {
  11655. window.addEventListener('gamepadconnected', function (evt) {
  11656. _this._onGamepadConnected(evt);
  11657. }, false);
  11658. window.addEventListener('gamepaddisconnected', function (evt) {
  11659. _this._onGamepadDisconnected(evt);
  11660. }, false);
  11661. }
  11662. else {
  11663. this._startMonitoringGamepads();
  11664. }
  11665. if (!this.oneGamepadConnected) {
  11666. this._insertGamepadDOMInstructions();
  11667. }
  11668. }
  11669. else {
  11670. this._insertGamepadDOMNotSupported();
  11671. }
  11672. }
  11673. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11674. Gamepads.gamepadDOMInfo = document.createElement("div");
  11675. var buttonAImage = document.createElement("img");
  11676. buttonAImage.src = this.buttonADataURL;
  11677. var spanMessage = document.createElement("span");
  11678. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11679. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11680. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11681. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11682. Gamepads.gamepadDOMInfo.style.width = "100%";
  11683. Gamepads.gamepadDOMInfo.style.height = "48px";
  11684. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11685. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11686. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11687. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11688. buttonAImage.style.position = "relative";
  11689. buttonAImage.style.bottom = "8px";
  11690. spanMessage.style.position = "relative";
  11691. spanMessage.style.fontSize = "32px";
  11692. spanMessage.style.bottom = "32px";
  11693. spanMessage.style.color = "green";
  11694. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11695. };
  11696. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11697. Gamepads.gamepadDOMInfo = document.createElement("div");
  11698. var spanMessage = document.createElement("span");
  11699. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11700. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11701. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11702. Gamepads.gamepadDOMInfo.style.width = "100%";
  11703. Gamepads.gamepadDOMInfo.style.height = "40px";
  11704. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11705. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11706. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11707. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11708. spanMessage.style.position = "relative";
  11709. spanMessage.style.fontSize = "32px";
  11710. spanMessage.style.color = "red";
  11711. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11712. };
  11713. Gamepads.prototype.dispose = function () {
  11714. if (Gamepads.gamepadDOMInfo) {
  11715. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11716. }
  11717. };
  11718. Gamepads.prototype._onGamepadConnected = function (evt) {
  11719. var newGamepad = this._addNewGamepad(evt.gamepad);
  11720. if (this._callbackGamepadConnected)
  11721. this._callbackGamepadConnected(newGamepad);
  11722. this._startMonitoringGamepads();
  11723. };
  11724. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11725. if (!this.oneGamepadConnected) {
  11726. this.oneGamepadConnected = true;
  11727. if (Gamepads.gamepadDOMInfo) {
  11728. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11729. Gamepads.gamepadDOMInfo = null;
  11730. }
  11731. }
  11732. var newGamepad;
  11733. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11734. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11735. }
  11736. else {
  11737. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11738. }
  11739. this.babylonGamepads.push(newGamepad);
  11740. return newGamepad;
  11741. };
  11742. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11743. // Remove the gamepad from the list of gamepads to monitor.
  11744. for (var i in this.babylonGamepads) {
  11745. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11746. this.babylonGamepads.splice(i, 1);
  11747. break;
  11748. }
  11749. }
  11750. // If no gamepads are left, stop the polling loop.
  11751. if (this.babylonGamepads.length == 0) {
  11752. this._stopMonitoringGamepads();
  11753. }
  11754. };
  11755. Gamepads.prototype._startMonitoringGamepads = function () {
  11756. if (!this.isMonitoring) {
  11757. this.isMonitoring = true;
  11758. this._checkGamepadsStatus();
  11759. }
  11760. };
  11761. Gamepads.prototype._stopMonitoringGamepads = function () {
  11762. this.isMonitoring = false;
  11763. };
  11764. Gamepads.prototype._checkGamepadsStatus = function () {
  11765. var _this = this;
  11766. // updating gamepad objects
  11767. this._updateGamepadObjects();
  11768. for (var i in this.babylonGamepads) {
  11769. this.babylonGamepads[i].update();
  11770. }
  11771. if (this.isMonitoring) {
  11772. if (window.requestAnimationFrame) {
  11773. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11774. }
  11775. else if (window.mozRequestAnimationFrame) {
  11776. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11777. }
  11778. else if (window.webkitRequestAnimationFrame) {
  11779. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11780. }
  11781. }
  11782. };
  11783. // This function is called only on Chrome, which does not yet support
  11784. // connection/disconnection events, but requires you to monitor
  11785. // an array for changes.
  11786. Gamepads.prototype._updateGamepadObjects = function () {
  11787. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11788. for (var i = 0; i < gamepads.length; i++) {
  11789. if (gamepads[i]) {
  11790. if (!(gamepads[i].index in this.babylonGamepads)) {
  11791. var newGamepad = this._addNewGamepad(gamepads[i]);
  11792. if (this._callbackGamepadConnected) {
  11793. this._callbackGamepadConnected(newGamepad);
  11794. }
  11795. }
  11796. else {
  11797. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11798. }
  11799. }
  11800. }
  11801. };
  11802. return Gamepads;
  11803. })();
  11804. BABYLON.Gamepads = Gamepads;
  11805. var StickValues = (function () {
  11806. function StickValues(x, y) {
  11807. this.x = x;
  11808. this.y = y;
  11809. }
  11810. return StickValues;
  11811. })();
  11812. BABYLON.StickValues = StickValues;
  11813. var Gamepad = (function () {
  11814. function Gamepad(id, index, browserGamepad) {
  11815. this.id = id;
  11816. this.index = index;
  11817. this.browserGamepad = browserGamepad;
  11818. if (this.browserGamepad.axes.length >= 2) {
  11819. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11820. }
  11821. if (this.browserGamepad.axes.length >= 4) {
  11822. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11823. }
  11824. }
  11825. Gamepad.prototype.onleftstickchanged = function (callback) {
  11826. this._onleftstickchanged = callback;
  11827. };
  11828. Gamepad.prototype.onrightstickchanged = function (callback) {
  11829. this._onrightstickchanged = callback;
  11830. };
  11831. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11832. get: function () {
  11833. return this._leftStick;
  11834. },
  11835. set: function (newValues) {
  11836. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11837. this._onleftstickchanged(newValues);
  11838. }
  11839. this._leftStick = newValues;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11845. get: function () {
  11846. return this._rightStick;
  11847. },
  11848. set: function (newValues) {
  11849. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11850. this._onrightstickchanged(newValues);
  11851. }
  11852. this._rightStick = newValues;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Gamepad.prototype.update = function () {
  11858. if (this._leftStick) {
  11859. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11860. }
  11861. if (this._rightStick) {
  11862. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11863. }
  11864. };
  11865. return Gamepad;
  11866. })();
  11867. BABYLON.Gamepad = Gamepad;
  11868. var GenericPad = (function (_super) {
  11869. __extends(GenericPad, _super);
  11870. function GenericPad(id, index, gamepad) {
  11871. _super.call(this, id, index, gamepad);
  11872. this.id = id;
  11873. this.index = index;
  11874. this.gamepad = gamepad;
  11875. this._buttons = new Array(gamepad.buttons.length);
  11876. }
  11877. GenericPad.prototype.onbuttondown = function (callback) {
  11878. this._onbuttondown = callback;
  11879. };
  11880. GenericPad.prototype.onbuttonup = function (callback) {
  11881. this._onbuttonup = callback;
  11882. };
  11883. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11884. if (newValue !== currentValue) {
  11885. if (this._onbuttondown && newValue === 1) {
  11886. this._onbuttondown(buttonIndex);
  11887. }
  11888. if (this._onbuttonup && newValue === 0) {
  11889. this._onbuttonup(buttonIndex);
  11890. }
  11891. }
  11892. return newValue;
  11893. };
  11894. GenericPad.prototype.update = function () {
  11895. _super.prototype.update.call(this);
  11896. for (var index = 0; index < this._buttons.length; index++) {
  11897. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11898. }
  11899. };
  11900. return GenericPad;
  11901. })(Gamepad);
  11902. BABYLON.GenericPad = GenericPad;
  11903. (function (Xbox360Button) {
  11904. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11905. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11906. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11907. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11908. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11909. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11910. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11911. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11912. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11913. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11914. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11915. var Xbox360Button = BABYLON.Xbox360Button;
  11916. (function (Xbox360Dpad) {
  11917. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11918. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11919. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11920. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11921. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11922. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11923. var Xbox360Pad = (function (_super) {
  11924. __extends(Xbox360Pad, _super);
  11925. function Xbox360Pad() {
  11926. _super.apply(this, arguments);
  11927. this._leftTrigger = 0;
  11928. this._rightTrigger = 0;
  11929. this._buttonA = 0;
  11930. this._buttonB = 0;
  11931. this._buttonX = 0;
  11932. this._buttonY = 0;
  11933. this._buttonBack = 0;
  11934. this._buttonStart = 0;
  11935. this._buttonLB = 0;
  11936. this._buttonRB = 0;
  11937. this._buttonLeftStick = 0;
  11938. this._buttonRightStick = 0;
  11939. this._dPadUp = 0;
  11940. this._dPadDown = 0;
  11941. this._dPadLeft = 0;
  11942. this._dPadRight = 0;
  11943. }
  11944. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11945. this._onlefttriggerchanged = callback;
  11946. };
  11947. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11948. this._onrighttriggerchanged = callback;
  11949. };
  11950. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11951. get: function () {
  11952. return this._leftTrigger;
  11953. },
  11954. set: function (newValue) {
  11955. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11956. this._onlefttriggerchanged(newValue);
  11957. }
  11958. this._leftTrigger = newValue;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11964. get: function () {
  11965. return this._rightTrigger;
  11966. },
  11967. set: function (newValue) {
  11968. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11969. this._onrighttriggerchanged(newValue);
  11970. }
  11971. this._rightTrigger = newValue;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11977. this._onbuttondown = callback;
  11978. };
  11979. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11980. this._onbuttonup = callback;
  11981. };
  11982. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11983. this._ondpaddown = callback;
  11984. };
  11985. Xbox360Pad.prototype.ondpadup = function (callback) {
  11986. this._ondpadup = callback;
  11987. };
  11988. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11989. if (newValue !== currentValue) {
  11990. if (this._onbuttondown && newValue === 1) {
  11991. this._onbuttondown(buttonType);
  11992. }
  11993. if (this._onbuttonup && newValue === 0) {
  11994. this._onbuttonup(buttonType);
  11995. }
  11996. }
  11997. return newValue;
  11998. };
  11999. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  12000. if (newValue !== currentValue) {
  12001. if (this._ondpaddown && newValue === 1) {
  12002. this._ondpaddown(buttonType);
  12003. }
  12004. if (this._ondpadup && newValue === 0) {
  12005. this._ondpadup(buttonType);
  12006. }
  12007. }
  12008. return newValue;
  12009. };
  12010. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  12011. get: function () {
  12012. return this._buttonA;
  12013. },
  12014. set: function (value) {
  12015. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  12021. get: function () {
  12022. return this._buttonB;
  12023. },
  12024. set: function (value) {
  12025. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  12031. get: function () {
  12032. return this._buttonX;
  12033. },
  12034. set: function (value) {
  12035. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  12041. get: function () {
  12042. return this._buttonY;
  12043. },
  12044. set: function (value) {
  12045. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  12051. get: function () {
  12052. return this._buttonStart;
  12053. },
  12054. set: function (value) {
  12055. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12061. get: function () {
  12062. return this._buttonBack;
  12063. },
  12064. set: function (value) {
  12065. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12071. get: function () {
  12072. return this._buttonLB;
  12073. },
  12074. set: function (value) {
  12075. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12081. get: function () {
  12082. return this._buttonRB;
  12083. },
  12084. set: function (value) {
  12085. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12091. get: function () {
  12092. return this._buttonLeftStick;
  12093. },
  12094. set: function (value) {
  12095. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12101. get: function () {
  12102. return this._buttonRightStick;
  12103. },
  12104. set: function (value) {
  12105. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12111. get: function () {
  12112. return this._dPadUp;
  12113. },
  12114. set: function (value) {
  12115. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12121. get: function () {
  12122. return this._dPadDown;
  12123. },
  12124. set: function (value) {
  12125. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12126. },
  12127. enumerable: true,
  12128. configurable: true
  12129. });
  12130. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12131. get: function () {
  12132. return this._dPadLeft;
  12133. },
  12134. set: function (value) {
  12135. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12141. get: function () {
  12142. return this._dPadRight;
  12143. },
  12144. set: function (value) {
  12145. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Xbox360Pad.prototype.update = function () {
  12151. _super.prototype.update.call(this);
  12152. this.buttonA = this.browserGamepad.buttons[0].value;
  12153. this.buttonB = this.browserGamepad.buttons[1].value;
  12154. this.buttonX = this.browserGamepad.buttons[2].value;
  12155. this.buttonY = this.browserGamepad.buttons[3].value;
  12156. this.buttonLB = this.browserGamepad.buttons[4].value;
  12157. this.buttonRB = this.browserGamepad.buttons[5].value;
  12158. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12159. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12160. this.buttonBack = this.browserGamepad.buttons[8].value;
  12161. this.buttonStart = this.browserGamepad.buttons[9].value;
  12162. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12163. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12164. this.dPadUp = this.browserGamepad.buttons[12].value;
  12165. this.dPadDown = this.browserGamepad.buttons[13].value;
  12166. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12167. this.dPadRight = this.browserGamepad.buttons[15].value;
  12168. };
  12169. return Xbox360Pad;
  12170. })(Gamepad);
  12171. BABYLON.Xbox360Pad = Xbox360Pad;
  12172. })(BABYLON || (BABYLON = {}));
  12173. var BABYLON;
  12174. (function (BABYLON) {
  12175. // We're mainly based on the logic defined into the FreeCamera code
  12176. var GamepadCamera = (function (_super) {
  12177. __extends(GamepadCamera, _super);
  12178. function GamepadCamera(name, position, scene) {
  12179. var _this = this;
  12180. _super.call(this, name, position, scene);
  12181. this.angularSensibility = 200;
  12182. this.moveSensibility = 75;
  12183. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12184. }
  12185. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12186. // Only the first gamepad can control the camera
  12187. if (gamepad.index === 0) {
  12188. this._gamepad = gamepad;
  12189. }
  12190. };
  12191. GamepadCamera.prototype._checkInputs = function () {
  12192. if (this._gamepad) {
  12193. var LSValues = this._gamepad.leftStick;
  12194. var normalizedLX = LSValues.x / this.moveSensibility;
  12195. var normalizedLY = LSValues.y / this.moveSensibility;
  12196. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12197. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12198. var RSValues = this._gamepad.rightStick;
  12199. var normalizedRX = RSValues.x / this.angularSensibility;
  12200. var normalizedRY = RSValues.y / this.angularSensibility;
  12201. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12202. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12203. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12204. var speed = this._computeLocalCameraSpeed() * 50.0;
  12205. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12206. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12207. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12208. }
  12209. _super.prototype._checkInputs.call(this);
  12210. };
  12211. GamepadCamera.prototype.dispose = function () {
  12212. this._gamepads.dispose();
  12213. _super.prototype.dispose.call(this);
  12214. };
  12215. return GamepadCamera;
  12216. })(BABYLON.FreeCamera);
  12217. BABYLON.GamepadCamera = GamepadCamera;
  12218. })(BABYLON || (BABYLON = {}));
  12219. var BABYLON;
  12220. (function (BABYLON) {
  12221. var RenderingManager = (function () {
  12222. function RenderingManager(scene) {
  12223. this._renderingGroups = new Array();
  12224. this._scene = scene;
  12225. }
  12226. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12227. if (this._scene._activeParticleSystems.length === 0) {
  12228. return;
  12229. }
  12230. // Particles
  12231. var activeCamera = this._scene.activeCamera;
  12232. var beforeParticlesDate = BABYLON.Tools.Now;
  12233. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12234. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12235. if (particleSystem.renderingGroupId !== index) {
  12236. continue;
  12237. }
  12238. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12239. continue;
  12240. }
  12241. this._clearDepthBuffer();
  12242. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12243. this._scene._activeParticles += particleSystem.render();
  12244. }
  12245. }
  12246. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12247. };
  12248. RenderingManager.prototype._renderSprites = function (index) {
  12249. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12250. return;
  12251. }
  12252. // Sprites
  12253. var activeCamera = this._scene.activeCamera;
  12254. var beforeSpritessDate = BABYLON.Tools.Now;
  12255. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12256. var spriteManager = this._scene.spriteManagers[id];
  12257. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12258. this._clearDepthBuffer();
  12259. spriteManager.render();
  12260. }
  12261. }
  12262. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12263. };
  12264. RenderingManager.prototype._clearDepthBuffer = function () {
  12265. if (this._depthBufferAlreadyCleaned) {
  12266. return;
  12267. }
  12268. this._scene.getEngine().clear(0, false, true);
  12269. this._depthBufferAlreadyCleaned = true;
  12270. };
  12271. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12272. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12273. this._depthBufferAlreadyCleaned = false;
  12274. var renderingGroup = this._renderingGroups[index];
  12275. var needToStepBack = false;
  12276. if (renderingGroup) {
  12277. this._clearDepthBuffer();
  12278. if (!renderingGroup.render(customRenderFunction)) {
  12279. this._renderingGroups.splice(index, 1);
  12280. needToStepBack = true;
  12281. }
  12282. }
  12283. if (renderSprites) {
  12284. this._renderSprites(index);
  12285. }
  12286. if (renderParticles) {
  12287. this._renderParticles(index, activeMeshes);
  12288. }
  12289. if (needToStepBack) {
  12290. index--;
  12291. }
  12292. }
  12293. };
  12294. RenderingManager.prototype.reset = function () {
  12295. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12296. if (renderingGroup) {
  12297. renderingGroup.prepare();
  12298. }
  12299. });
  12300. };
  12301. RenderingManager.prototype.dispatch = function (subMesh) {
  12302. var mesh = subMesh.getMesh();
  12303. var renderingGroupId = mesh.renderingGroupId || 0;
  12304. if (!this._renderingGroups[renderingGroupId]) {
  12305. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12306. }
  12307. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12308. };
  12309. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12310. return RenderingManager;
  12311. })();
  12312. BABYLON.RenderingManager = RenderingManager;
  12313. })(BABYLON || (BABYLON = {}));
  12314. var BABYLON;
  12315. (function (BABYLON) {
  12316. var RenderingGroup = (function () {
  12317. function RenderingGroup(index, scene) {
  12318. this.index = index;
  12319. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12320. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12321. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12322. this._scene = scene;
  12323. }
  12324. RenderingGroup.prototype.render = function (customRenderFunction) {
  12325. if (customRenderFunction) {
  12326. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12327. return true;
  12328. }
  12329. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12330. return false;
  12331. }
  12332. var engine = this._scene.getEngine();
  12333. // Opaque
  12334. var subIndex;
  12335. var submesh;
  12336. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12337. submesh = this._opaqueSubMeshes.data[subIndex];
  12338. submesh.render(false);
  12339. }
  12340. // Alpha test
  12341. engine.setAlphaTesting(true);
  12342. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12343. submesh = this._alphaTestSubMeshes.data[subIndex];
  12344. submesh.render(false);
  12345. }
  12346. engine.setAlphaTesting(false);
  12347. // Transparent
  12348. if (this._transparentSubMeshes.length) {
  12349. // Sorting
  12350. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12351. submesh = this._transparentSubMeshes.data[subIndex];
  12352. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12353. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12354. }
  12355. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12356. sortedArray.sort(function (a, b) {
  12357. // Alpha index first
  12358. if (a._alphaIndex > b._alphaIndex) {
  12359. return 1;
  12360. }
  12361. if (a._alphaIndex < b._alphaIndex) {
  12362. return -1;
  12363. }
  12364. // Then distance to camera
  12365. if (a._distanceToCamera < b._distanceToCamera) {
  12366. return 1;
  12367. }
  12368. if (a._distanceToCamera > b._distanceToCamera) {
  12369. return -1;
  12370. }
  12371. return 0;
  12372. });
  12373. // Rendering
  12374. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12375. submesh = sortedArray[subIndex];
  12376. submesh.render(true);
  12377. }
  12378. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12379. }
  12380. return true;
  12381. };
  12382. RenderingGroup.prototype.prepare = function () {
  12383. this._opaqueSubMeshes.reset();
  12384. this._transparentSubMeshes.reset();
  12385. this._alphaTestSubMeshes.reset();
  12386. };
  12387. RenderingGroup.prototype.dispatch = function (subMesh) {
  12388. var material = subMesh.getMaterial();
  12389. var mesh = subMesh.getMesh();
  12390. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12391. this._transparentSubMeshes.push(subMesh);
  12392. }
  12393. else if (material.needAlphaTesting()) {
  12394. this._alphaTestSubMeshes.push(subMesh);
  12395. }
  12396. else {
  12397. this._opaqueSubMeshes.push(subMesh); // Opaque
  12398. }
  12399. };
  12400. return RenderingGroup;
  12401. })();
  12402. BABYLON.RenderingGroup = RenderingGroup;
  12403. })(BABYLON || (BABYLON = {}));
  12404. var BABYLON;
  12405. (function (BABYLON) {
  12406. /**
  12407. * Represents a scene to be rendered by the engine.
  12408. * @see http://doc.babylonjs.com/page.php?p=21911
  12409. */
  12410. var Scene = (function () {
  12411. /**
  12412. * @constructor
  12413. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12414. */
  12415. function Scene(engine) {
  12416. // Members
  12417. this.autoClear = true;
  12418. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12419. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12420. this.forceWireframe = false;
  12421. this.forcePointsCloud = false;
  12422. this.forceShowBoundingBoxes = false;
  12423. this.animationsEnabled = true;
  12424. 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
  12425. // Fog
  12426. /**
  12427. * is fog enabled on this scene.
  12428. * @type {boolean}
  12429. */
  12430. this.fogEnabled = true;
  12431. this.fogMode = Scene.FOGMODE_NONE;
  12432. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12433. this.fogDensity = 0.1;
  12434. this.fogStart = 0;
  12435. this.fogEnd = 1000.0;
  12436. // Lights
  12437. /**
  12438. * is shadow enabled on this scene.
  12439. * @type {boolean}
  12440. */
  12441. this.shadowsEnabled = true;
  12442. /**
  12443. * is light enabled on this scene.
  12444. * @type {boolean}
  12445. */
  12446. this.lightsEnabled = true;
  12447. /**
  12448. * All of the lights added to this scene.
  12449. * @see BABYLON.Light
  12450. * @type {BABYLON.Light[]}
  12451. */
  12452. this.lights = new Array();
  12453. // Cameras
  12454. /**
  12455. * All of the cameras added to this scene.
  12456. * @see BABYLON.Camera
  12457. * @type {BABYLON.Camera[]}
  12458. */
  12459. this.cameras = new Array();
  12460. this.activeCameras = new Array();
  12461. // Meshes
  12462. /**
  12463. * All of the (abstract) meshes added to this scene.
  12464. * @see BABYLON.AbstractMesh
  12465. * @type {BABYLON.AbstractMesh[]}
  12466. */
  12467. this.meshes = new Array();
  12468. // Geometries
  12469. this._geometries = new Array();
  12470. this.materials = new Array();
  12471. this.multiMaterials = new Array();
  12472. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12473. // Textures
  12474. this.texturesEnabled = true;
  12475. this.textures = new Array();
  12476. // Particles
  12477. this.particlesEnabled = true;
  12478. this.particleSystems = new Array();
  12479. // Sprites
  12480. this.spritesEnabled = true;
  12481. this.spriteManagers = new Array();
  12482. // Layers
  12483. this.layers = new Array();
  12484. // Skeletons
  12485. this.skeletonsEnabled = true;
  12486. this.skeletons = new Array();
  12487. // Lens flares
  12488. this.lensFlaresEnabled = true;
  12489. this.lensFlareSystems = new Array();
  12490. // Collisions
  12491. this.collisionsEnabled = true;
  12492. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12493. // Postprocesses
  12494. this.postProcessesEnabled = true;
  12495. // Customs render targets
  12496. this.renderTargetsEnabled = true;
  12497. this.dumpNextRenderTargets = false;
  12498. this.customRenderTargets = new Array();
  12499. // Imported meshes
  12500. this.importedMeshesFiles = new Array();
  12501. this._actionManagers = new Array();
  12502. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12503. // Procedural textures
  12504. this.proceduralTexturesEnabled = true;
  12505. this._proceduralTextures = new Array();
  12506. this.soundTracks = new Array();
  12507. this._audioEnabled = true;
  12508. this._headphone = false;
  12509. this._totalVertices = 0;
  12510. this._activeIndices = 0;
  12511. this._activeParticles = 0;
  12512. this._lastFrameDuration = 0;
  12513. this._evaluateActiveMeshesDuration = 0;
  12514. this._renderTargetsDuration = 0;
  12515. this._particlesDuration = 0;
  12516. this._renderDuration = 0;
  12517. this._spritesDuration = 0;
  12518. this._animationRatio = 0;
  12519. this._renderId = 0;
  12520. this._executeWhenReadyTimeoutId = -1;
  12521. this._toBeDisposed = new BABYLON.SmartArray(256);
  12522. this._onReadyCallbacks = new Array();
  12523. this._pendingData = []; //ANY
  12524. this._onBeforeRenderCallbacks = new Array();
  12525. this._onAfterRenderCallbacks = new Array();
  12526. this._activeMeshes = new BABYLON.SmartArray(256);
  12527. this._processedMaterials = new BABYLON.SmartArray(256);
  12528. this._renderTargets = new BABYLON.SmartArray(256);
  12529. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12530. this._activeSkeletons = new BABYLON.SmartArray(32);
  12531. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12532. this._activeBones = 0;
  12533. this._activeAnimatables = new Array();
  12534. this._transformMatrix = BABYLON.Matrix.Zero();
  12535. this._edgesRenderers = new BABYLON.SmartArray(16);
  12536. this._uniqueIdCounter = 0;
  12537. this._engine = engine;
  12538. engine.scenes.push(this);
  12539. this._renderingManager = new BABYLON.RenderingManager(this);
  12540. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12541. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12542. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12543. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12544. this.attachControl();
  12545. this._debugLayer = new BABYLON.DebugLayer(this);
  12546. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12547. //simplification queue
  12548. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12549. //collision coordinator initialization. For now legacy per default.
  12550. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12551. }
  12552. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12553. get: function () {
  12554. return Scene._FOGMODE_NONE;
  12555. },
  12556. enumerable: true,
  12557. configurable: true
  12558. });
  12559. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12560. get: function () {
  12561. return Scene._FOGMODE_EXP;
  12562. },
  12563. enumerable: true,
  12564. configurable: true
  12565. });
  12566. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12567. get: function () {
  12568. return Scene._FOGMODE_EXP2;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12574. get: function () {
  12575. return Scene._FOGMODE_LINEAR;
  12576. },
  12577. enumerable: true,
  12578. configurable: true
  12579. });
  12580. Object.defineProperty(Scene.prototype, "debugLayer", {
  12581. // Properties
  12582. get: function () {
  12583. return this._debugLayer;
  12584. },
  12585. enumerable: true,
  12586. configurable: true
  12587. });
  12588. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12589. get: function () {
  12590. return this._workerCollisions;
  12591. },
  12592. set: function (enabled) {
  12593. enabled = (enabled && !!Worker);
  12594. this._workerCollisions = enabled;
  12595. if (this.collisionCoordinator) {
  12596. this.collisionCoordinator.destroy();
  12597. }
  12598. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12599. this.collisionCoordinator.init(this);
  12600. },
  12601. enumerable: true,
  12602. configurable: true
  12603. });
  12604. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12605. get: function () {
  12606. return this._selectionOctree;
  12607. },
  12608. enumerable: true,
  12609. configurable: true
  12610. });
  12611. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12612. /**
  12613. * The mesh that is currently under the pointer.
  12614. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12615. */
  12616. get: function () {
  12617. return this._meshUnderPointer;
  12618. },
  12619. enumerable: true,
  12620. configurable: true
  12621. });
  12622. Object.defineProperty(Scene.prototype, "pointerX", {
  12623. /**
  12624. * Current on-screen X position of the pointer
  12625. * @return {number} X position of the pointer
  12626. */
  12627. get: function () {
  12628. return this._pointerX;
  12629. },
  12630. enumerable: true,
  12631. configurable: true
  12632. });
  12633. Object.defineProperty(Scene.prototype, "pointerY", {
  12634. /**
  12635. * Current on-screen Y position of the pointer
  12636. * @return {number} Y position of the pointer
  12637. */
  12638. get: function () {
  12639. return this._pointerY;
  12640. },
  12641. enumerable: true,
  12642. configurable: true
  12643. });
  12644. Scene.prototype.getCachedMaterial = function () {
  12645. return this._cachedMaterial;
  12646. };
  12647. Scene.prototype.getBoundingBoxRenderer = function () {
  12648. return this._boundingBoxRenderer;
  12649. };
  12650. Scene.prototype.getOutlineRenderer = function () {
  12651. return this._outlineRenderer;
  12652. };
  12653. Scene.prototype.getEngine = function () {
  12654. return this._engine;
  12655. };
  12656. Scene.prototype.getTotalVertices = function () {
  12657. return this._totalVertices;
  12658. };
  12659. Scene.prototype.getActiveIndices = function () {
  12660. return this._activeIndices;
  12661. };
  12662. Scene.prototype.getActiveParticles = function () {
  12663. return this._activeParticles;
  12664. };
  12665. Scene.prototype.getActiveBones = function () {
  12666. return this._activeBones;
  12667. };
  12668. // Stats
  12669. Scene.prototype.getLastFrameDuration = function () {
  12670. return this._lastFrameDuration;
  12671. };
  12672. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12673. return this._evaluateActiveMeshesDuration;
  12674. };
  12675. Scene.prototype.getActiveMeshes = function () {
  12676. return this._activeMeshes;
  12677. };
  12678. Scene.prototype.getRenderTargetsDuration = function () {
  12679. return this._renderTargetsDuration;
  12680. };
  12681. Scene.prototype.getRenderDuration = function () {
  12682. return this._renderDuration;
  12683. };
  12684. Scene.prototype.getParticlesDuration = function () {
  12685. return this._particlesDuration;
  12686. };
  12687. Scene.prototype.getSpritesDuration = function () {
  12688. return this._spritesDuration;
  12689. };
  12690. Scene.prototype.getAnimationRatio = function () {
  12691. return this._animationRatio;
  12692. };
  12693. Scene.prototype.getRenderId = function () {
  12694. return this._renderId;
  12695. };
  12696. Scene.prototype.incrementRenderId = function () {
  12697. this._renderId++;
  12698. };
  12699. Scene.prototype._updatePointerPosition = function (evt) {
  12700. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12701. this._pointerX = evt.clientX - canvasRect.left;
  12702. this._pointerY = evt.clientY - canvasRect.top;
  12703. if (this.cameraToUseForPointers) {
  12704. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12705. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12706. }
  12707. };
  12708. // Pointers handling
  12709. Scene.prototype.attachControl = function () {
  12710. var _this = this;
  12711. this._onPointerMove = function (evt) {
  12712. var canvas = _this._engine.getRenderingCanvas();
  12713. _this._updatePointerPosition(evt);
  12714. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12715. if (pickResult.hit) {
  12716. _this._meshUnderPointer = pickResult.pickedMesh;
  12717. _this.setPointerOverMesh(pickResult.pickedMesh);
  12718. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12719. canvas.style.cursor = "pointer";
  12720. }
  12721. else {
  12722. canvas.style.cursor = "";
  12723. }
  12724. }
  12725. else {
  12726. _this.setPointerOverMesh(null);
  12727. canvas.style.cursor = "";
  12728. _this._meshUnderPointer = null;
  12729. }
  12730. };
  12731. this._onPointerDown = function (evt) {
  12732. var predicate = null;
  12733. if (!_this.onPointerDown) {
  12734. predicate = function (mesh) {
  12735. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12736. };
  12737. }
  12738. _this._updatePointerPosition(evt);
  12739. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12740. if (pickResult.hit) {
  12741. if (pickResult.pickedMesh.actionManager) {
  12742. switch (evt.button) {
  12743. case 0:
  12744. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12745. break;
  12746. case 1:
  12747. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12748. break;
  12749. case 2:
  12750. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12751. break;
  12752. }
  12753. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12754. }
  12755. }
  12756. if (_this.onPointerDown) {
  12757. _this.onPointerDown(evt, pickResult);
  12758. }
  12759. };
  12760. this._onPointerUp = function (evt) {
  12761. var predicate = null;
  12762. if (!_this.onPointerUp) {
  12763. predicate = function (mesh) {
  12764. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12765. };
  12766. }
  12767. _this._updatePointerPosition(evt);
  12768. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12769. if (pickResult.hit) {
  12770. if (pickResult.pickedMesh.actionManager) {
  12771. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12772. }
  12773. }
  12774. if (_this.onPointerUp) {
  12775. _this.onPointerUp(evt, pickResult);
  12776. }
  12777. };
  12778. this._onKeyDown = function (evt) {
  12779. if (_this.actionManager) {
  12780. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12781. }
  12782. };
  12783. this._onKeyUp = function (evt) {
  12784. if (_this.actionManager) {
  12785. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12786. }
  12787. };
  12788. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12789. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12790. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12791. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12792. // Wheel
  12793. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12794. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12795. BABYLON.Tools.RegisterTopRootEvents([
  12796. { name: "keydown", handler: this._onKeyDown },
  12797. { name: "keyup", handler: this._onKeyUp }
  12798. ]);
  12799. };
  12800. Scene.prototype.detachControl = function () {
  12801. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12802. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12803. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12804. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12805. // Wheel
  12806. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12807. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12808. BABYLON.Tools.UnregisterTopRootEvents([
  12809. { name: "keydown", handler: this._onKeyDown },
  12810. { name: "keyup", handler: this._onKeyUp }
  12811. ]);
  12812. };
  12813. // Ready
  12814. Scene.prototype.isReady = function () {
  12815. if (this._pendingData.length > 0) {
  12816. return false;
  12817. }
  12818. var index;
  12819. for (index = 0; index < this._geometries.length; index++) {
  12820. var geometry = this._geometries[index];
  12821. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12822. return false;
  12823. }
  12824. }
  12825. for (index = 0; index < this.meshes.length; index++) {
  12826. var mesh = this.meshes[index];
  12827. if (!mesh.isReady()) {
  12828. return false;
  12829. }
  12830. var mat = mesh.material;
  12831. if (mat) {
  12832. if (!mat.isReady(mesh)) {
  12833. return false;
  12834. }
  12835. }
  12836. }
  12837. return true;
  12838. };
  12839. Scene.prototype.resetCachedMaterial = function () {
  12840. this._cachedMaterial = null;
  12841. };
  12842. Scene.prototype.registerBeforeRender = function (func) {
  12843. this._onBeforeRenderCallbacks.push(func);
  12844. };
  12845. Scene.prototype.unregisterBeforeRender = function (func) {
  12846. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12847. if (index > -1) {
  12848. this._onBeforeRenderCallbacks.splice(index, 1);
  12849. }
  12850. };
  12851. Scene.prototype.registerAfterRender = function (func) {
  12852. this._onAfterRenderCallbacks.push(func);
  12853. };
  12854. Scene.prototype.unregisterAfterRender = function (func) {
  12855. var index = this._onAfterRenderCallbacks.indexOf(func);
  12856. if (index > -1) {
  12857. this._onAfterRenderCallbacks.splice(index, 1);
  12858. }
  12859. };
  12860. Scene.prototype._addPendingData = function (data) {
  12861. this._pendingData.push(data);
  12862. };
  12863. Scene.prototype._removePendingData = function (data) {
  12864. var index = this._pendingData.indexOf(data);
  12865. if (index !== -1) {
  12866. this._pendingData.splice(index, 1);
  12867. }
  12868. };
  12869. Scene.prototype.getWaitingItemsCount = function () {
  12870. return this._pendingData.length;
  12871. };
  12872. /**
  12873. * Registers a function to be executed when the scene is ready.
  12874. * @param {Function} func - the function to be executed.
  12875. */
  12876. Scene.prototype.executeWhenReady = function (func) {
  12877. var _this = this;
  12878. this._onReadyCallbacks.push(func);
  12879. if (this._executeWhenReadyTimeoutId !== -1) {
  12880. return;
  12881. }
  12882. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12883. _this._checkIsReady();
  12884. }, 150);
  12885. };
  12886. Scene.prototype._checkIsReady = function () {
  12887. var _this = this;
  12888. if (this.isReady()) {
  12889. this._onReadyCallbacks.forEach(function (func) {
  12890. func();
  12891. });
  12892. this._onReadyCallbacks = [];
  12893. this._executeWhenReadyTimeoutId = -1;
  12894. return;
  12895. }
  12896. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12897. _this._checkIsReady();
  12898. }, 150);
  12899. };
  12900. // Animations
  12901. /**
  12902. * Will start the animation sequence of a given target
  12903. * @param target - the target
  12904. * @param {number} from - from which frame should animation start
  12905. * @param {number} to - till which frame should animation run.
  12906. * @param {boolean} [loop] - should the animation loop
  12907. * @param {number} [speedRatio] - the speed in which to run the animation
  12908. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12909. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12910. * @return {BABYLON.Animatable} the animatable object created for this animation
  12911. * @see BABYLON.Animatable
  12912. * @see http://doc.babylonjs.com/page.php?p=22081
  12913. */
  12914. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12915. if (speedRatio === undefined) {
  12916. speedRatio = 1.0;
  12917. }
  12918. this.stopAnimation(target);
  12919. if (!animatable) {
  12920. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12921. }
  12922. // Local animations
  12923. if (target.animations) {
  12924. animatable.appendAnimations(target, target.animations);
  12925. }
  12926. // Children animations
  12927. if (target.getAnimatables) {
  12928. var animatables = target.getAnimatables();
  12929. for (var index = 0; index < animatables.length; index++) {
  12930. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12931. }
  12932. }
  12933. return animatable;
  12934. };
  12935. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12936. if (speedRatio === undefined) {
  12937. speedRatio = 1.0;
  12938. }
  12939. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12940. return animatable;
  12941. };
  12942. Scene.prototype.getAnimatableByTarget = function (target) {
  12943. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12944. if (this._activeAnimatables[index].target === target) {
  12945. return this._activeAnimatables[index];
  12946. }
  12947. }
  12948. return null;
  12949. };
  12950. /**
  12951. * Will stop the animation of the given target
  12952. * @param target - the target
  12953. * @see beginAnimation
  12954. */
  12955. Scene.prototype.stopAnimation = function (target) {
  12956. var animatable = this.getAnimatableByTarget(target);
  12957. if (animatable) {
  12958. animatable.stop();
  12959. }
  12960. };
  12961. Scene.prototype._animate = function () {
  12962. if (!this.animationsEnabled) {
  12963. return;
  12964. }
  12965. if (!this._animationStartDate) {
  12966. this._animationStartDate = BABYLON.Tools.Now;
  12967. }
  12968. // Getting time
  12969. var now = BABYLON.Tools.Now;
  12970. var delay = now - this._animationStartDate;
  12971. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12972. this._activeAnimatables[index]._animate(delay);
  12973. }
  12974. };
  12975. // Matrix
  12976. Scene.prototype.getViewMatrix = function () {
  12977. return this._viewMatrix;
  12978. };
  12979. Scene.prototype.getProjectionMatrix = function () {
  12980. return this._projectionMatrix;
  12981. };
  12982. Scene.prototype.getTransformMatrix = function () {
  12983. return this._transformMatrix;
  12984. };
  12985. Scene.prototype.setTransformMatrix = function (view, projection) {
  12986. this._viewMatrix = view;
  12987. this._projectionMatrix = projection;
  12988. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12989. };
  12990. // Methods
  12991. Scene.prototype.addMesh = function (newMesh) {
  12992. newMesh.uniqueId = this._uniqueIdCounter++;
  12993. var position = this.meshes.push(newMesh);
  12994. //notify the collision coordinator
  12995. this.collisionCoordinator.onMeshAdded(newMesh);
  12996. if (this.onNewMeshAdded) {
  12997. this.onNewMeshAdded(newMesh, position, this);
  12998. }
  12999. };
  13000. Scene.prototype.removeMesh = function (toRemove) {
  13001. var index = this.meshes.indexOf(toRemove);
  13002. if (index !== -1) {
  13003. // Remove from the scene if mesh found
  13004. this.meshes.splice(index, 1);
  13005. }
  13006. //notify the collision coordinator
  13007. this.collisionCoordinator.onMeshRemoved(toRemove);
  13008. if (this.onMeshRemoved) {
  13009. this.onMeshRemoved(toRemove);
  13010. }
  13011. return index;
  13012. };
  13013. Scene.prototype.removeLight = function (toRemove) {
  13014. var index = this.lights.indexOf(toRemove);
  13015. if (index !== -1) {
  13016. // Remove from the scene if mesh found
  13017. this.lights.splice(index, 1);
  13018. }
  13019. if (this.onLightRemoved) {
  13020. this.onLightRemoved(toRemove);
  13021. }
  13022. return index;
  13023. };
  13024. Scene.prototype.removeCamera = function (toRemove) {
  13025. var index = this.cameras.indexOf(toRemove);
  13026. if (index !== -1) {
  13027. // Remove from the scene if mesh found
  13028. this.cameras.splice(index, 1);
  13029. }
  13030. // Remove from activeCameras
  13031. var index2 = this.activeCameras.indexOf(toRemove);
  13032. if (index2 !== -1) {
  13033. // Remove from the scene if mesh found
  13034. this.activeCameras.splice(index2, 1);
  13035. }
  13036. // Reset the activeCamera
  13037. if (this.activeCamera === toRemove) {
  13038. if (this.cameras.length > 0) {
  13039. this.activeCamera = this.cameras[0];
  13040. }
  13041. else {
  13042. this.activeCamera = null;
  13043. }
  13044. }
  13045. if (this.onCameraRemoved) {
  13046. this.onCameraRemoved(toRemove);
  13047. }
  13048. return index;
  13049. };
  13050. Scene.prototype.addLight = function (newLight) {
  13051. newLight.uniqueId = this._uniqueIdCounter++;
  13052. var position = this.lights.push(newLight);
  13053. if (this.onNewLightAdded) {
  13054. this.onNewLightAdded(newLight, position, this);
  13055. }
  13056. };
  13057. Scene.prototype.addCamera = function (newCamera) {
  13058. newCamera.uniqueId = this._uniqueIdCounter++;
  13059. var position = this.cameras.push(newCamera);
  13060. if (this.onNewCameraAdded) {
  13061. this.onNewCameraAdded(newCamera, position, this);
  13062. }
  13063. };
  13064. /**
  13065. * sets the active camera of the scene using its ID
  13066. * @param {string} id - the camera's ID
  13067. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13068. * @see activeCamera
  13069. */
  13070. Scene.prototype.setActiveCameraByID = function (id) {
  13071. var camera = this.getCameraByID(id);
  13072. if (camera) {
  13073. this.activeCamera = camera;
  13074. return camera;
  13075. }
  13076. return null;
  13077. };
  13078. /**
  13079. * sets the active camera of the scene using its name
  13080. * @param {string} name - the camera's name
  13081. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13082. * @see activeCamera
  13083. */
  13084. Scene.prototype.setActiveCameraByName = function (name) {
  13085. var camera = this.getCameraByName(name);
  13086. if (camera) {
  13087. this.activeCamera = camera;
  13088. return camera;
  13089. }
  13090. return null;
  13091. };
  13092. /**
  13093. * get a material using its id
  13094. * @param {string} the material's ID
  13095. * @return {BABYLON.Material|null} the material or null if none found.
  13096. */
  13097. Scene.prototype.getMaterialByID = function (id) {
  13098. for (var index = 0; index < this.materials.length; index++) {
  13099. if (this.materials[index].id === id) {
  13100. return this.materials[index];
  13101. }
  13102. }
  13103. return null;
  13104. };
  13105. /**
  13106. * get a material using its name
  13107. * @param {string} the material's name
  13108. * @return {BABYLON.Material|null} the material or null if none found.
  13109. */
  13110. Scene.prototype.getMaterialByName = function (name) {
  13111. for (var index = 0; index < this.materials.length; index++) {
  13112. if (this.materials[index].name === name) {
  13113. return this.materials[index];
  13114. }
  13115. }
  13116. return null;
  13117. };
  13118. Scene.prototype.getLensFlareSystemByName = function (name) {
  13119. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13120. if (this.lensFlareSystems[index].name === name) {
  13121. return this.lensFlareSystems[index];
  13122. }
  13123. }
  13124. return null;
  13125. };
  13126. Scene.prototype.getCameraByID = function (id) {
  13127. for (var index = 0; index < this.cameras.length; index++) {
  13128. if (this.cameras[index].id === id) {
  13129. return this.cameras[index];
  13130. }
  13131. }
  13132. return null;
  13133. };
  13134. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13135. for (var index = 0; index < this.cameras.length; index++) {
  13136. if (this.cameras[index].uniqueId === uniqueId) {
  13137. return this.cameras[index];
  13138. }
  13139. }
  13140. return null;
  13141. };
  13142. /**
  13143. * get a camera using its name
  13144. * @param {string} the camera's name
  13145. * @return {BABYLON.Camera|null} the camera or null if none found.
  13146. */
  13147. Scene.prototype.getCameraByName = function (name) {
  13148. for (var index = 0; index < this.cameras.length; index++) {
  13149. if (this.cameras[index].name === name) {
  13150. return this.cameras[index];
  13151. }
  13152. }
  13153. return null;
  13154. };
  13155. /**
  13156. * get a light node using its name
  13157. * @param {string} the light's name
  13158. * @return {BABYLON.Light|null} the light or null if none found.
  13159. */
  13160. Scene.prototype.getLightByName = function (name) {
  13161. for (var index = 0; index < this.lights.length; index++) {
  13162. if (this.lights[index].name === name) {
  13163. return this.lights[index];
  13164. }
  13165. }
  13166. return null;
  13167. };
  13168. /**
  13169. * get a light node using its ID
  13170. * @param {string} the light's id
  13171. * @return {BABYLON.Light|null} the light or null if none found.
  13172. */
  13173. Scene.prototype.getLightByID = function (id) {
  13174. for (var index = 0; index < this.lights.length; index++) {
  13175. if (this.lights[index].id === id) {
  13176. return this.lights[index];
  13177. }
  13178. }
  13179. return null;
  13180. };
  13181. /**
  13182. * get a light node using its scene-generated unique ID
  13183. * @param {number} the light's unique id
  13184. * @return {BABYLON.Light|null} the light or null if none found.
  13185. */
  13186. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13187. for (var index = 0; index < this.lights.length; index++) {
  13188. if (this.lights[index].uniqueId === uniqueId) {
  13189. return this.lights[index];
  13190. }
  13191. }
  13192. return null;
  13193. };
  13194. /**
  13195. * get a geometry using its ID
  13196. * @param {string} the geometry's id
  13197. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13198. */
  13199. Scene.prototype.getGeometryByID = function (id) {
  13200. for (var index = 0; index < this._geometries.length; index++) {
  13201. if (this._geometries[index].id === id) {
  13202. return this._geometries[index];
  13203. }
  13204. }
  13205. return null;
  13206. };
  13207. /**
  13208. * add a new geometry to this scene.
  13209. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13210. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13211. * @return {boolean} was the geometry added or not
  13212. */
  13213. Scene.prototype.pushGeometry = function (geometry, force) {
  13214. if (!force && this.getGeometryByID(geometry.id)) {
  13215. return false;
  13216. }
  13217. this._geometries.push(geometry);
  13218. //notify the collision coordinator
  13219. this.collisionCoordinator.onGeometryAdded(geometry);
  13220. if (this.onGeometryAdded) {
  13221. this.onGeometryAdded(geometry);
  13222. }
  13223. return true;
  13224. };
  13225. /**
  13226. * Removes an existing geometry
  13227. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13228. * @return {boolean} was the geometry removed or not
  13229. */
  13230. Scene.prototype.removeGeometry = function (geometry) {
  13231. var index = this._geometries.indexOf(geometry);
  13232. if (index > -1) {
  13233. this._geometries.splice(index, 1);
  13234. //notify the collision coordinator
  13235. this.collisionCoordinator.onGeometryDeleted(geometry);
  13236. if (this.onGeometryRemoved) {
  13237. this.onGeometryRemoved(geometry);
  13238. }
  13239. return true;
  13240. }
  13241. return false;
  13242. };
  13243. Scene.prototype.getGeometries = function () {
  13244. return this._geometries;
  13245. };
  13246. /**
  13247. * Get the first added mesh found of a given ID
  13248. * @param {string} id - the id to search for
  13249. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13250. */
  13251. Scene.prototype.getMeshByID = function (id) {
  13252. for (var index = 0; index < this.meshes.length; index++) {
  13253. if (this.meshes[index].id === id) {
  13254. return this.meshes[index];
  13255. }
  13256. }
  13257. return null;
  13258. };
  13259. /**
  13260. * Get a mesh with its auto-generated unique id
  13261. * @param {number} uniqueId - the unique id to search for
  13262. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13263. */
  13264. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13265. for (var index = 0; index < this.meshes.length; index++) {
  13266. if (this.meshes[index].uniqueId === uniqueId) {
  13267. return this.meshes[index];
  13268. }
  13269. }
  13270. return null;
  13271. };
  13272. /**
  13273. * Get a the last added mesh found of a given ID
  13274. * @param {string} id - the id to search for
  13275. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13276. */
  13277. Scene.prototype.getLastMeshByID = function (id) {
  13278. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13279. if (this.meshes[index].id === id) {
  13280. return this.meshes[index];
  13281. }
  13282. }
  13283. return null;
  13284. };
  13285. /**
  13286. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13287. * @param {string} id - the id to search for
  13288. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13289. */
  13290. Scene.prototype.getLastEntryByID = function (id) {
  13291. var index;
  13292. for (index = this.meshes.length - 1; index >= 0; index--) {
  13293. if (this.meshes[index].id === id) {
  13294. return this.meshes[index];
  13295. }
  13296. }
  13297. for (index = this.cameras.length - 1; index >= 0; index--) {
  13298. if (this.cameras[index].id === id) {
  13299. return this.cameras[index];
  13300. }
  13301. }
  13302. for (index = this.lights.length - 1; index >= 0; index--) {
  13303. if (this.lights[index].id === id) {
  13304. return this.lights[index];
  13305. }
  13306. }
  13307. return null;
  13308. };
  13309. Scene.prototype.getNodeByID = function (id) {
  13310. var mesh = this.getMeshByID(id);
  13311. if (mesh) {
  13312. return mesh;
  13313. }
  13314. var light = this.getLightByID(id);
  13315. if (light) {
  13316. return light;
  13317. }
  13318. return this.getCameraByID(id);
  13319. };
  13320. Scene.prototype.getNodeByName = function (name) {
  13321. var mesh = this.getMeshByName(name);
  13322. if (mesh) {
  13323. return mesh;
  13324. }
  13325. var light = this.getLightByName(name);
  13326. if (light) {
  13327. return light;
  13328. }
  13329. return this.getCameraByName(name);
  13330. };
  13331. Scene.prototype.getMeshByName = function (name) {
  13332. for (var index = 0; index < this.meshes.length; index++) {
  13333. if (this.meshes[index].name === name) {
  13334. return this.meshes[index];
  13335. }
  13336. }
  13337. return null;
  13338. };
  13339. Scene.prototype.getSoundByName = function (name) {
  13340. var index;
  13341. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13342. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13343. return this.mainSoundTrack.soundCollection[index];
  13344. }
  13345. }
  13346. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13347. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13348. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13349. return this.soundTracks[sdIndex].soundCollection[index];
  13350. }
  13351. }
  13352. }
  13353. return null;
  13354. };
  13355. Scene.prototype.getLastSkeletonByID = function (id) {
  13356. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13357. if (this.skeletons[index].id === id) {
  13358. return this.skeletons[index];
  13359. }
  13360. }
  13361. return null;
  13362. };
  13363. Scene.prototype.getSkeletonById = function (id) {
  13364. for (var index = 0; index < this.skeletons.length; index++) {
  13365. if (this.skeletons[index].id === id) {
  13366. return this.skeletons[index];
  13367. }
  13368. }
  13369. return null;
  13370. };
  13371. Scene.prototype.getSkeletonByName = function (name) {
  13372. for (var index = 0; index < this.skeletons.length; index++) {
  13373. if (this.skeletons[index].name === name) {
  13374. return this.skeletons[index];
  13375. }
  13376. }
  13377. return null;
  13378. };
  13379. Scene.prototype.isActiveMesh = function (mesh) {
  13380. return (this._activeMeshes.indexOf(mesh) !== -1);
  13381. };
  13382. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13383. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13384. var material = subMesh.getMaterial();
  13385. if (mesh.showSubMeshesBoundingBox) {
  13386. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13387. }
  13388. if (material) {
  13389. // Render targets
  13390. if (material.getRenderTargetTextures) {
  13391. if (this._processedMaterials.indexOf(material) === -1) {
  13392. this._processedMaterials.push(material);
  13393. this._renderTargets.concat(material.getRenderTargetTextures());
  13394. }
  13395. }
  13396. // Dispatch
  13397. this._activeIndices += subMesh.indexCount;
  13398. this._renderingManager.dispatch(subMesh);
  13399. }
  13400. }
  13401. };
  13402. Scene.prototype._evaluateActiveMeshes = function () {
  13403. this.activeCamera._activeMeshes.reset();
  13404. this._activeMeshes.reset();
  13405. this._renderingManager.reset();
  13406. this._processedMaterials.reset();
  13407. this._activeParticleSystems.reset();
  13408. this._activeSkeletons.reset();
  13409. this._softwareSkinnedMeshes.reset();
  13410. this._boundingBoxRenderer.reset();
  13411. this._edgesRenderers.reset();
  13412. if (!this._frustumPlanes) {
  13413. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13414. }
  13415. else {
  13416. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13417. }
  13418. // Meshes
  13419. var meshes;
  13420. var len;
  13421. if (this._selectionOctree) {
  13422. var selection = this._selectionOctree.select(this._frustumPlanes);
  13423. meshes = selection.data;
  13424. len = selection.length;
  13425. }
  13426. else {
  13427. len = this.meshes.length;
  13428. meshes = this.meshes;
  13429. }
  13430. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13431. var mesh = meshes[meshIndex];
  13432. if (mesh.isBlocked) {
  13433. continue;
  13434. }
  13435. this._totalVertices += mesh.getTotalVertices();
  13436. if (!mesh.isReady() || !mesh.isEnabled()) {
  13437. continue;
  13438. }
  13439. mesh.computeWorldMatrix();
  13440. // Intersections
  13441. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13442. this._meshesForIntersections.pushNoDuplicate(mesh);
  13443. }
  13444. // Switch to current LOD
  13445. var meshLOD = mesh.getLOD(this.activeCamera);
  13446. if (!meshLOD) {
  13447. continue;
  13448. }
  13449. mesh._preActivate();
  13450. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13451. this._activeMeshes.push(mesh);
  13452. this.activeCamera._activeMeshes.push(mesh);
  13453. mesh._activate(this._renderId);
  13454. this._activeMesh(meshLOD);
  13455. }
  13456. }
  13457. // Particle systems
  13458. var beforeParticlesDate = BABYLON.Tools.Now;
  13459. if (this.particlesEnabled) {
  13460. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13461. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13462. var particleSystem = this.particleSystems[particleIndex];
  13463. if (!particleSystem.isStarted()) {
  13464. continue;
  13465. }
  13466. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13467. this._activeParticleSystems.push(particleSystem);
  13468. particleSystem.animate();
  13469. }
  13470. }
  13471. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13472. }
  13473. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13474. };
  13475. Scene.prototype._activeMesh = function (mesh) {
  13476. if (mesh.skeleton && this.skeletonsEnabled) {
  13477. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13478. if (!mesh.computeBonesUsingShaders) {
  13479. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13480. }
  13481. }
  13482. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13483. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13484. }
  13485. if (mesh._edgesRenderer) {
  13486. this._edgesRenderers.push(mesh._edgesRenderer);
  13487. }
  13488. if (mesh && mesh.subMeshes) {
  13489. // Submeshes Octrees
  13490. var len;
  13491. var subMeshes;
  13492. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13493. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13494. len = intersections.length;
  13495. subMeshes = intersections.data;
  13496. }
  13497. else {
  13498. subMeshes = mesh.subMeshes;
  13499. len = subMeshes.length;
  13500. }
  13501. for (var subIndex = 0; subIndex < len; subIndex++) {
  13502. var subMesh = subMeshes[subIndex];
  13503. this._evaluateSubMesh(subMesh, mesh);
  13504. }
  13505. }
  13506. };
  13507. Scene.prototype.updateTransformMatrix = function (force) {
  13508. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13509. };
  13510. Scene.prototype._renderForCamera = function (camera) {
  13511. var engine = this._engine;
  13512. this.activeCamera = camera;
  13513. if (!this.activeCamera)
  13514. throw new Error("Active camera not set");
  13515. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13516. // Viewport
  13517. engine.setViewport(this.activeCamera.viewport);
  13518. // Camera
  13519. this.resetCachedMaterial();
  13520. this._renderId++;
  13521. this.updateTransformMatrix();
  13522. if (this.beforeCameraRender) {
  13523. this.beforeCameraRender(this.activeCamera);
  13524. }
  13525. // Meshes
  13526. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13527. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13528. this._evaluateActiveMeshes();
  13529. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13530. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13531. // Skeletons
  13532. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13533. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13534. skeleton.prepare();
  13535. }
  13536. // Software skinning
  13537. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13538. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13539. mesh.applySkeleton(mesh.skeleton);
  13540. }
  13541. // Render targets
  13542. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13543. if (this.renderTargetsEnabled) {
  13544. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13545. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13546. var renderTarget = this._renderTargets.data[renderIndex];
  13547. if (renderTarget._shouldRender()) {
  13548. this._renderId++;
  13549. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13550. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13551. }
  13552. }
  13553. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13554. this._renderId++;
  13555. }
  13556. if (this._renderTargets.length > 0) {
  13557. engine.restoreDefaultFramebuffer();
  13558. }
  13559. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13560. // Prepare Frame
  13561. this.postProcessManager._prepareFrame();
  13562. var beforeRenderDate = BABYLON.Tools.Now;
  13563. // Backgrounds
  13564. var layerIndex;
  13565. var layer;
  13566. if (this.layers.length) {
  13567. engine.setDepthBuffer(false);
  13568. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13569. layer = this.layers[layerIndex];
  13570. if (layer.isBackground) {
  13571. layer.render();
  13572. }
  13573. }
  13574. engine.setDepthBuffer(true);
  13575. }
  13576. // Render
  13577. BABYLON.Tools.StartPerformanceCounter("Main render");
  13578. this._renderingManager.render(null, null, true, true);
  13579. BABYLON.Tools.EndPerformanceCounter("Main render");
  13580. // Bounding boxes
  13581. this._boundingBoxRenderer.render();
  13582. // Edges
  13583. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13584. this._edgesRenderers.data[edgesRendererIndex].render();
  13585. }
  13586. // Lens flares
  13587. if (this.lensFlaresEnabled) {
  13588. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13589. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13590. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13591. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13592. lensFlareSystem.render();
  13593. }
  13594. }
  13595. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13596. }
  13597. // Foregrounds
  13598. if (this.layers.length) {
  13599. engine.setDepthBuffer(false);
  13600. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13601. layer = this.layers[layerIndex];
  13602. if (!layer.isBackground) {
  13603. layer.render();
  13604. }
  13605. }
  13606. engine.setDepthBuffer(true);
  13607. }
  13608. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13609. // Finalize frame
  13610. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13611. // Update camera
  13612. this.activeCamera._updateFromScene();
  13613. // Reset some special arrays
  13614. this._renderTargets.reset();
  13615. if (this.afterCameraRender) {
  13616. this.afterCameraRender(this.activeCamera);
  13617. }
  13618. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13619. };
  13620. Scene.prototype._processSubCameras = function (camera) {
  13621. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13622. this._renderForCamera(camera);
  13623. return;
  13624. }
  13625. // rig cameras
  13626. for (var index = 0; index < camera._rigCameras.length; index++) {
  13627. this._renderForCamera(camera._rigCameras[index]);
  13628. }
  13629. this.activeCamera = camera;
  13630. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13631. // Update camera
  13632. this.activeCamera._updateFromScene();
  13633. };
  13634. Scene.prototype._checkIntersections = function () {
  13635. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13636. var sourceMesh = this._meshesForIntersections.data[index];
  13637. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13638. var action = sourceMesh.actionManager.actions[actionIndex];
  13639. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13640. var parameters = action.getTriggerParameter();
  13641. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13642. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13643. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13644. if (areIntersecting && currentIntersectionInProgress === -1) {
  13645. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13646. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13647. sourceMesh._intersectionsInProgress.push(otherMesh);
  13648. }
  13649. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13650. sourceMesh._intersectionsInProgress.push(otherMesh);
  13651. }
  13652. }
  13653. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13654. //They intersected, and now they don't.
  13655. //is this trigger an exit trigger? execute an event.
  13656. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13657. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13658. }
  13659. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13660. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13661. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13662. }
  13663. }
  13664. }
  13665. }
  13666. }
  13667. };
  13668. Scene.prototype.render = function () {
  13669. var startDate = BABYLON.Tools.Now;
  13670. this._particlesDuration = 0;
  13671. this._spritesDuration = 0;
  13672. this._activeParticles = 0;
  13673. this._renderDuration = 0;
  13674. this._renderTargetsDuration = 0;
  13675. this._evaluateActiveMeshesDuration = 0;
  13676. this._totalVertices = 0;
  13677. this._activeIndices = 0;
  13678. this._activeBones = 0;
  13679. this.getEngine().resetDrawCalls();
  13680. this._meshesForIntersections.reset();
  13681. this.resetCachedMaterial();
  13682. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13683. // Actions
  13684. if (this.actionManager) {
  13685. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13686. }
  13687. //Simplification Queue
  13688. if (!this.simplificationQueue.running) {
  13689. this.simplificationQueue.executeNext();
  13690. }
  13691. // Before render
  13692. if (this.beforeRender) {
  13693. this.beforeRender();
  13694. }
  13695. var callbackIndex;
  13696. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13697. this._onBeforeRenderCallbacks[callbackIndex]();
  13698. }
  13699. // Animations
  13700. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13701. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13702. this._animate();
  13703. // Physics
  13704. if (this._physicsEngine) {
  13705. BABYLON.Tools.StartPerformanceCounter("Physics");
  13706. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13707. BABYLON.Tools.EndPerformanceCounter("Physics");
  13708. }
  13709. // Customs render targets
  13710. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13711. var engine = this.getEngine();
  13712. var currentActiveCamera = this.activeCamera;
  13713. if (this.renderTargetsEnabled) {
  13714. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13715. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13716. var renderTarget = this.customRenderTargets[customIndex];
  13717. if (renderTarget._shouldRender()) {
  13718. this._renderId++;
  13719. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13720. if (!this.activeCamera)
  13721. throw new Error("Active camera not set");
  13722. // Viewport
  13723. engine.setViewport(this.activeCamera.viewport);
  13724. // Camera
  13725. this.updateTransformMatrix();
  13726. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13727. }
  13728. }
  13729. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13730. this._renderId++;
  13731. }
  13732. if (this.customRenderTargets.length > 0) {
  13733. engine.restoreDefaultFramebuffer();
  13734. }
  13735. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13736. this.activeCamera = currentActiveCamera;
  13737. // Procedural textures
  13738. if (this.proceduralTexturesEnabled) {
  13739. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13740. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13741. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13742. if (proceduralTexture._shouldRender()) {
  13743. proceduralTexture.render();
  13744. }
  13745. }
  13746. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13747. }
  13748. // Clear
  13749. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13750. // Shadows
  13751. if (this.shadowsEnabled) {
  13752. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13753. var light = this.lights[lightIndex];
  13754. var shadowGenerator = light.getShadowGenerator();
  13755. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13756. this._renderTargets.push(shadowGenerator.getShadowMap());
  13757. }
  13758. }
  13759. }
  13760. // Depth renderer
  13761. if (this._depthRenderer) {
  13762. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13763. }
  13764. // RenderPipeline
  13765. this.postProcessRenderPipelineManager.update();
  13766. // Multi-cameras?
  13767. if (this.activeCameras.length > 0) {
  13768. var currentRenderId = this._renderId;
  13769. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13770. this._renderId = currentRenderId;
  13771. this._processSubCameras(this.activeCameras[cameraIndex]);
  13772. }
  13773. }
  13774. else {
  13775. if (!this.activeCamera) {
  13776. throw new Error("No camera defined");
  13777. }
  13778. this._processSubCameras(this.activeCamera);
  13779. }
  13780. // Intersection checks
  13781. this._checkIntersections();
  13782. // Update the audio listener attached to the camera
  13783. this._updateAudioParameters();
  13784. // After render
  13785. if (this.afterRender) {
  13786. this.afterRender();
  13787. }
  13788. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13789. this._onAfterRenderCallbacks[callbackIndex]();
  13790. }
  13791. // Cleaning
  13792. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13793. this._toBeDisposed.data[index].dispose();
  13794. this._toBeDisposed[index] = null;
  13795. }
  13796. this._toBeDisposed.reset();
  13797. if (this.dumpNextRenderTargets) {
  13798. this.dumpNextRenderTargets = false;
  13799. }
  13800. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13801. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13802. };
  13803. Scene.prototype._updateAudioParameters = function () {
  13804. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13805. return;
  13806. }
  13807. var listeningCamera;
  13808. var audioEngine = BABYLON.Engine.audioEngine;
  13809. if (this.activeCameras.length > 0) {
  13810. listeningCamera = this.activeCameras[0];
  13811. }
  13812. else {
  13813. listeningCamera = this.activeCamera;
  13814. }
  13815. if (listeningCamera && audioEngine.canUseWebAudio) {
  13816. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13817. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13818. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13819. cameraDirection.normalize();
  13820. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13821. var i;
  13822. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13823. var sound = this.mainSoundTrack.soundCollection[i];
  13824. if (sound.useCustomAttenuation) {
  13825. sound.updateDistanceFromListener();
  13826. }
  13827. }
  13828. for (i = 0; i < this.soundTracks.length; i++) {
  13829. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13830. sound = this.soundTracks[i].soundCollection[j];
  13831. if (sound.useCustomAttenuation) {
  13832. sound.updateDistanceFromListener();
  13833. }
  13834. }
  13835. }
  13836. }
  13837. };
  13838. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13839. // Audio
  13840. get: function () {
  13841. return this._audioEnabled;
  13842. },
  13843. set: function (value) {
  13844. this._audioEnabled = value;
  13845. if (this._audioEnabled) {
  13846. this._enableAudio();
  13847. }
  13848. else {
  13849. this._disableAudio();
  13850. }
  13851. },
  13852. enumerable: true,
  13853. configurable: true
  13854. });
  13855. Scene.prototype._disableAudio = function () {
  13856. var i;
  13857. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13858. this.mainSoundTrack.soundCollection[i].pause();
  13859. }
  13860. for (i = 0; i < this.soundTracks.length; i++) {
  13861. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13862. this.soundTracks[i].soundCollection[j].pause();
  13863. }
  13864. }
  13865. };
  13866. Scene.prototype._enableAudio = function () {
  13867. var i;
  13868. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13869. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13870. this.mainSoundTrack.soundCollection[i].play();
  13871. }
  13872. }
  13873. for (i = 0; i < this.soundTracks.length; i++) {
  13874. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13875. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13876. this.soundTracks[i].soundCollection[j].play();
  13877. }
  13878. }
  13879. }
  13880. };
  13881. Object.defineProperty(Scene.prototype, "headphone", {
  13882. get: function () {
  13883. return this._headphone;
  13884. },
  13885. set: function (value) {
  13886. this._headphone = value;
  13887. if (this._headphone) {
  13888. this._switchAudioModeForHeadphones();
  13889. }
  13890. else {
  13891. this._switchAudioModeForNormalSpeakers();
  13892. }
  13893. },
  13894. enumerable: true,
  13895. configurable: true
  13896. });
  13897. Scene.prototype._switchAudioModeForHeadphones = function () {
  13898. this.mainSoundTrack.switchPanningModelToHRTF();
  13899. for (var i = 0; i < this.soundTracks.length; i++) {
  13900. this.soundTracks[i].switchPanningModelToHRTF();
  13901. }
  13902. };
  13903. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13904. this.mainSoundTrack.switchPanningModelToEqualPower();
  13905. for (var i = 0; i < this.soundTracks.length; i++) {
  13906. this.soundTracks[i].switchPanningModelToEqualPower();
  13907. }
  13908. };
  13909. Scene.prototype.enableDepthRenderer = function () {
  13910. if (this._depthRenderer) {
  13911. return this._depthRenderer;
  13912. }
  13913. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13914. return this._depthRenderer;
  13915. };
  13916. Scene.prototype.disableDepthRenderer = function () {
  13917. if (!this._depthRenderer) {
  13918. return;
  13919. }
  13920. this._depthRenderer.dispose();
  13921. this._depthRenderer = null;
  13922. };
  13923. Scene.prototype.dispose = function () {
  13924. this.beforeRender = null;
  13925. this.afterRender = null;
  13926. this.skeletons = [];
  13927. this._boundingBoxRenderer.dispose();
  13928. if (this._depthRenderer) {
  13929. this._depthRenderer.dispose();
  13930. }
  13931. // Debug layer
  13932. this.debugLayer.hide();
  13933. // Events
  13934. if (this.onDispose) {
  13935. this.onDispose();
  13936. }
  13937. this._onBeforeRenderCallbacks = [];
  13938. this._onAfterRenderCallbacks = [];
  13939. this.detachControl();
  13940. // Release sounds & sounds tracks
  13941. this.disposeSounds();
  13942. // Detach cameras
  13943. var canvas = this._engine.getRenderingCanvas();
  13944. var index;
  13945. for (index = 0; index < this.cameras.length; index++) {
  13946. this.cameras[index].detachControl(canvas);
  13947. }
  13948. // Release lights
  13949. while (this.lights.length) {
  13950. this.lights[0].dispose();
  13951. }
  13952. // Release meshes
  13953. while (this.meshes.length) {
  13954. this.meshes[0].dispose(true);
  13955. }
  13956. // Release cameras
  13957. while (this.cameras.length) {
  13958. this.cameras[0].dispose();
  13959. }
  13960. // Release materials
  13961. while (this.materials.length) {
  13962. this.materials[0].dispose();
  13963. }
  13964. // Release particles
  13965. while (this.particleSystems.length) {
  13966. this.particleSystems[0].dispose();
  13967. }
  13968. // Release sprites
  13969. while (this.spriteManagers.length) {
  13970. this.spriteManagers[0].dispose();
  13971. }
  13972. // Release layers
  13973. while (this.layers.length) {
  13974. this.layers[0].dispose();
  13975. }
  13976. // Release textures
  13977. while (this.textures.length) {
  13978. this.textures[0].dispose();
  13979. }
  13980. // Post-processes
  13981. this.postProcessManager.dispose();
  13982. // Physics
  13983. if (this._physicsEngine) {
  13984. this.disablePhysicsEngine();
  13985. }
  13986. // Remove from engine
  13987. index = this._engine.scenes.indexOf(this);
  13988. if (index > -1) {
  13989. this._engine.scenes.splice(index, 1);
  13990. }
  13991. this._engine.wipeCaches();
  13992. };
  13993. // Release sounds & sounds tracks
  13994. Scene.prototype.disposeSounds = function () {
  13995. this.mainSoundTrack.dispose();
  13996. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13997. this.soundTracks[scIndex].dispose();
  13998. }
  13999. };
  14000. // Octrees
  14001. Scene.prototype.getWorldExtends = function () {
  14002. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14003. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14004. for (var index = 0; index < this.meshes.length; index++) {
  14005. var mesh = this.meshes[index];
  14006. mesh.computeWorldMatrix(true);
  14007. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14008. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14009. BABYLON.Tools.CheckExtends(minBox, min, max);
  14010. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14011. }
  14012. return {
  14013. min: min,
  14014. max: max
  14015. };
  14016. };
  14017. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14018. if (maxCapacity === void 0) { maxCapacity = 64; }
  14019. if (maxDepth === void 0) { maxDepth = 2; }
  14020. if (!this._selectionOctree) {
  14021. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14022. }
  14023. var worldExtends = this.getWorldExtends();
  14024. // Update octree
  14025. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14026. return this._selectionOctree;
  14027. };
  14028. // Picking
  14029. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  14030. var engine = this._engine;
  14031. if (!camera) {
  14032. if (!this.activeCamera)
  14033. throw new Error("Active camera not set");
  14034. camera = this.activeCamera;
  14035. }
  14036. var cameraViewport = camera.viewport;
  14037. var viewport = cameraViewport.toGlobal(engine);
  14038. // Moving coordinates to local viewport world
  14039. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14040. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14041. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14042. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14043. };
  14044. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14045. var pickingInfo = null;
  14046. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14047. var mesh = this.meshes[meshIndex];
  14048. if (predicate) {
  14049. if (!predicate(mesh)) {
  14050. continue;
  14051. }
  14052. }
  14053. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14054. continue;
  14055. }
  14056. var world = mesh.getWorldMatrix();
  14057. var ray = rayFunction(world);
  14058. var result = mesh.intersects(ray, fastCheck);
  14059. if (!result || !result.hit)
  14060. continue;
  14061. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14062. continue;
  14063. pickingInfo = result;
  14064. if (fastCheck) {
  14065. break;
  14066. }
  14067. }
  14068. return pickingInfo || new BABYLON.PickingInfo();
  14069. };
  14070. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14071. var _this = this;
  14072. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14073. /// <param name="x">X position on screen</param>
  14074. /// <param name="y">Y position on screen</param>
  14075. /// <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>
  14076. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14077. /// <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>
  14078. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14079. };
  14080. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14081. var _this = this;
  14082. return this._internalPick(function (world) {
  14083. if (!_this._pickWithRayInverseMatrix) {
  14084. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14085. }
  14086. world.invertToRef(_this._pickWithRayInverseMatrix);
  14087. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14088. }, predicate, fastCheck);
  14089. };
  14090. Scene.prototype.setPointerOverMesh = function (mesh) {
  14091. if (this._pointerOverMesh === mesh) {
  14092. return;
  14093. }
  14094. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14095. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14096. }
  14097. this._pointerOverMesh = mesh;
  14098. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14099. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14100. }
  14101. };
  14102. Scene.prototype.getPointerOverMesh = function () {
  14103. return this._pointerOverMesh;
  14104. };
  14105. // Physics
  14106. Scene.prototype.getPhysicsEngine = function () {
  14107. return this._physicsEngine;
  14108. };
  14109. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14110. if (this._physicsEngine) {
  14111. return true;
  14112. }
  14113. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14114. if (!this._physicsEngine.isSupported()) {
  14115. this._physicsEngine = null;
  14116. return false;
  14117. }
  14118. this._physicsEngine._initialize(gravity);
  14119. return true;
  14120. };
  14121. Scene.prototype.disablePhysicsEngine = function () {
  14122. if (!this._physicsEngine) {
  14123. return;
  14124. }
  14125. this._physicsEngine.dispose();
  14126. this._physicsEngine = undefined;
  14127. };
  14128. Scene.prototype.isPhysicsEnabled = function () {
  14129. return this._physicsEngine !== undefined;
  14130. };
  14131. Scene.prototype.setGravity = function (gravity) {
  14132. if (!this._physicsEngine) {
  14133. return;
  14134. }
  14135. this._physicsEngine._setGravity(gravity);
  14136. };
  14137. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14138. if (parts.parts) {
  14139. options = parts;
  14140. parts = parts.parts;
  14141. }
  14142. if (!this._physicsEngine) {
  14143. return null;
  14144. }
  14145. for (var index = 0; index < parts.length; index++) {
  14146. var mesh = parts[index].mesh;
  14147. mesh._physicImpostor = parts[index].impostor;
  14148. mesh._physicsMass = options.mass / parts.length;
  14149. mesh._physicsFriction = options.friction;
  14150. mesh._physicRestitution = options.restitution;
  14151. }
  14152. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14153. };
  14154. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14155. for (var index = 0; index < compound.parts.length; index++) {
  14156. var mesh = compound.parts[index].mesh;
  14157. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14158. this._physicsEngine._unregisterMesh(mesh);
  14159. }
  14160. };
  14161. // Misc.
  14162. Scene.prototype.createDefaultCameraOrLight = function () {
  14163. // Light
  14164. if (this.lights.length === 0) {
  14165. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14166. }
  14167. // Camera
  14168. if (!this.activeCamera) {
  14169. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14170. // Compute position
  14171. var worldExtends = this.getWorldExtends();
  14172. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14173. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14174. camera.setTarget(worldCenter);
  14175. this.activeCamera = camera;
  14176. }
  14177. };
  14178. // Tags
  14179. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14180. if (tagsQuery === undefined) {
  14181. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14182. return list;
  14183. }
  14184. var listByTags = [];
  14185. forEach = forEach || (function (item) { return; });
  14186. for (var i in list) {
  14187. var item = list[i];
  14188. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14189. listByTags.push(item);
  14190. forEach(item);
  14191. }
  14192. }
  14193. return listByTags;
  14194. };
  14195. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14196. return this._getByTags(this.meshes, tagsQuery, forEach);
  14197. };
  14198. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14199. return this._getByTags(this.cameras, tagsQuery, forEach);
  14200. };
  14201. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14202. return this._getByTags(this.lights, tagsQuery, forEach);
  14203. };
  14204. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14205. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14206. };
  14207. // Statics
  14208. Scene._FOGMODE_NONE = 0;
  14209. Scene._FOGMODE_EXP = 1;
  14210. Scene._FOGMODE_EXP2 = 2;
  14211. Scene._FOGMODE_LINEAR = 3;
  14212. Scene.MinDeltaTime = 1.0;
  14213. Scene.MaxDeltaTime = 1000.0;
  14214. return Scene;
  14215. })();
  14216. BABYLON.Scene = Scene;
  14217. })(BABYLON || (BABYLON = {}));
  14218. var BABYLON;
  14219. (function (BABYLON) {
  14220. var VertexBuffer = (function () {
  14221. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14222. if (engine instanceof BABYLON.Mesh) {
  14223. this._engine = engine.getScene().getEngine();
  14224. }
  14225. else {
  14226. this._engine = engine;
  14227. }
  14228. this._updatable = updatable;
  14229. this._data = data;
  14230. if (!postponeInternalCreation) {
  14231. this.create();
  14232. }
  14233. this._kind = kind;
  14234. if (stride) {
  14235. this._strideSize = stride;
  14236. return;
  14237. }
  14238. // Deduce stride from kind
  14239. switch (kind) {
  14240. case VertexBuffer.PositionKind:
  14241. this._strideSize = 3;
  14242. break;
  14243. case VertexBuffer.NormalKind:
  14244. this._strideSize = 3;
  14245. break;
  14246. case VertexBuffer.UVKind:
  14247. case VertexBuffer.UV2Kind:
  14248. case VertexBuffer.UV3Kind:
  14249. case VertexBuffer.UV4Kind:
  14250. case VertexBuffer.UV5Kind:
  14251. case VertexBuffer.UV6Kind:
  14252. this._strideSize = 2;
  14253. break;
  14254. case VertexBuffer.ColorKind:
  14255. this._strideSize = 4;
  14256. break;
  14257. case VertexBuffer.MatricesIndicesKind:
  14258. this._strideSize = 4;
  14259. break;
  14260. case VertexBuffer.MatricesWeightsKind:
  14261. this._strideSize = 4;
  14262. break;
  14263. }
  14264. }
  14265. // Properties
  14266. VertexBuffer.prototype.isUpdatable = function () {
  14267. return this._updatable;
  14268. };
  14269. VertexBuffer.prototype.getData = function () {
  14270. return this._data;
  14271. };
  14272. VertexBuffer.prototype.getBuffer = function () {
  14273. return this._buffer;
  14274. };
  14275. VertexBuffer.prototype.getStrideSize = function () {
  14276. return this._strideSize;
  14277. };
  14278. // Methods
  14279. VertexBuffer.prototype.create = function (data) {
  14280. if (!data && this._buffer) {
  14281. return; // nothing to do
  14282. }
  14283. data = data || this._data;
  14284. if (!this._buffer) {
  14285. if (this._updatable) {
  14286. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14287. }
  14288. else {
  14289. this._buffer = this._engine.createVertexBuffer(data);
  14290. }
  14291. }
  14292. if (this._updatable) {
  14293. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14294. this._data = data;
  14295. }
  14296. };
  14297. VertexBuffer.prototype.update = function (data) {
  14298. this.create(data);
  14299. };
  14300. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14301. if (!this._buffer) {
  14302. return;
  14303. }
  14304. if (this._updatable) {
  14305. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14306. this._data = null;
  14307. }
  14308. };
  14309. VertexBuffer.prototype.dispose = function () {
  14310. if (!this._buffer) {
  14311. return;
  14312. }
  14313. if (this._engine._releaseBuffer(this._buffer)) {
  14314. this._buffer = null;
  14315. }
  14316. };
  14317. Object.defineProperty(VertexBuffer, "PositionKind", {
  14318. get: function () {
  14319. return VertexBuffer._PositionKind;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. Object.defineProperty(VertexBuffer, "NormalKind", {
  14325. get: function () {
  14326. return VertexBuffer._NormalKind;
  14327. },
  14328. enumerable: true,
  14329. configurable: true
  14330. });
  14331. Object.defineProperty(VertexBuffer, "UVKind", {
  14332. get: function () {
  14333. return VertexBuffer._UVKind;
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14339. get: function () {
  14340. return VertexBuffer._UV2Kind;
  14341. },
  14342. enumerable: true,
  14343. configurable: true
  14344. });
  14345. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14346. get: function () {
  14347. return VertexBuffer._UV3Kind;
  14348. },
  14349. enumerable: true,
  14350. configurable: true
  14351. });
  14352. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14353. get: function () {
  14354. return VertexBuffer._UV4Kind;
  14355. },
  14356. enumerable: true,
  14357. configurable: true
  14358. });
  14359. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14360. get: function () {
  14361. return VertexBuffer._UV5Kind;
  14362. },
  14363. enumerable: true,
  14364. configurable: true
  14365. });
  14366. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14367. get: function () {
  14368. return VertexBuffer._UV6Kind;
  14369. },
  14370. enumerable: true,
  14371. configurable: true
  14372. });
  14373. Object.defineProperty(VertexBuffer, "ColorKind", {
  14374. get: function () {
  14375. return VertexBuffer._ColorKind;
  14376. },
  14377. enumerable: true,
  14378. configurable: true
  14379. });
  14380. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14381. get: function () {
  14382. return VertexBuffer._MatricesIndicesKind;
  14383. },
  14384. enumerable: true,
  14385. configurable: true
  14386. });
  14387. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14388. get: function () {
  14389. return VertexBuffer._MatricesWeightsKind;
  14390. },
  14391. enumerable: true,
  14392. configurable: true
  14393. });
  14394. // Enums
  14395. VertexBuffer._PositionKind = "position";
  14396. VertexBuffer._NormalKind = "normal";
  14397. VertexBuffer._UVKind = "uv";
  14398. VertexBuffer._UV2Kind = "uv2";
  14399. VertexBuffer._UV3Kind = "uv3";
  14400. VertexBuffer._UV4Kind = "uv4";
  14401. VertexBuffer._UV5Kind = "uv5";
  14402. VertexBuffer._UV6Kind = "uv6";
  14403. VertexBuffer._ColorKind = "color";
  14404. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14405. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14406. return VertexBuffer;
  14407. })();
  14408. BABYLON.VertexBuffer = VertexBuffer;
  14409. })(BABYLON || (BABYLON = {}));
  14410. var BABYLON;
  14411. (function (BABYLON) {
  14412. /**
  14413. * Creates an instance based on a source mesh.
  14414. */
  14415. var InstancedMesh = (function (_super) {
  14416. __extends(InstancedMesh, _super);
  14417. function InstancedMesh(name, source) {
  14418. _super.call(this, name, source.getScene());
  14419. source.instances.push(this);
  14420. this._sourceMesh = source;
  14421. this.position.copyFrom(source.position);
  14422. this.rotation.copyFrom(source.rotation);
  14423. this.scaling.copyFrom(source.scaling);
  14424. if (source.rotationQuaternion) {
  14425. this.rotationQuaternion = source.rotationQuaternion.clone();
  14426. }
  14427. this.infiniteDistance = source.infiniteDistance;
  14428. this.setPivotMatrix(source.getPivotMatrix());
  14429. this.refreshBoundingInfo();
  14430. this._syncSubMeshes();
  14431. }
  14432. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14433. // Methods
  14434. get: function () {
  14435. return this._sourceMesh.receiveShadows;
  14436. },
  14437. enumerable: true,
  14438. configurable: true
  14439. });
  14440. Object.defineProperty(InstancedMesh.prototype, "material", {
  14441. get: function () {
  14442. return this._sourceMesh.material;
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14448. get: function () {
  14449. return this._sourceMesh.visibility;
  14450. },
  14451. enumerable: true,
  14452. configurable: true
  14453. });
  14454. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14455. get: function () {
  14456. return this._sourceMesh.skeleton;
  14457. },
  14458. enumerable: true,
  14459. configurable: true
  14460. });
  14461. InstancedMesh.prototype.getTotalVertices = function () {
  14462. return this._sourceMesh.getTotalVertices();
  14463. };
  14464. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14465. get: function () {
  14466. return this._sourceMesh;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. InstancedMesh.prototype.getVerticesData = function (kind) {
  14472. return this._sourceMesh.getVerticesData(kind);
  14473. };
  14474. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14475. return this._sourceMesh.isVerticesDataPresent(kind);
  14476. };
  14477. InstancedMesh.prototype.getIndices = function () {
  14478. return this._sourceMesh.getIndices();
  14479. };
  14480. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14481. get: function () {
  14482. return this._sourceMesh._positions;
  14483. },
  14484. enumerable: true,
  14485. configurable: true
  14486. });
  14487. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14488. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14489. if (data) {
  14490. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14491. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14492. }
  14493. this._updateBoundingInfo();
  14494. };
  14495. InstancedMesh.prototype._preActivate = function () {
  14496. if (this._currentLOD) {
  14497. this._currentLOD._preActivate();
  14498. }
  14499. };
  14500. InstancedMesh.prototype._activate = function (renderId) {
  14501. if (this._currentLOD) {
  14502. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14503. }
  14504. };
  14505. InstancedMesh.prototype.getLOD = function (camera) {
  14506. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14507. if (this._currentLOD === this.sourceMesh) {
  14508. return this;
  14509. }
  14510. return this._currentLOD;
  14511. };
  14512. InstancedMesh.prototype._syncSubMeshes = function () {
  14513. this.releaseSubMeshes();
  14514. if (this._sourceMesh.subMeshes) {
  14515. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14516. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14517. }
  14518. }
  14519. };
  14520. InstancedMesh.prototype._generatePointsArray = function () {
  14521. return this._sourceMesh._generatePointsArray();
  14522. };
  14523. // Clone
  14524. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14525. var result = this._sourceMesh.createInstance(name);
  14526. // Deep copy
  14527. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14528. // Bounding info
  14529. this.refreshBoundingInfo();
  14530. // Parent
  14531. if (newParent) {
  14532. result.parent = newParent;
  14533. }
  14534. if (!doNotCloneChildren) {
  14535. // Children
  14536. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14537. var mesh = this.getScene().meshes[index];
  14538. if (mesh.parent === this) {
  14539. mesh.clone(mesh.name, result);
  14540. }
  14541. }
  14542. }
  14543. result.computeWorldMatrix(true);
  14544. return result;
  14545. };
  14546. // Dispoe
  14547. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14548. // Remove from mesh
  14549. var index = this._sourceMesh.instances.indexOf(this);
  14550. this._sourceMesh.instances.splice(index, 1);
  14551. _super.prototype.dispose.call(this, doNotRecurse);
  14552. };
  14553. return InstancedMesh;
  14554. })(BABYLON.AbstractMesh);
  14555. BABYLON.InstancedMesh = InstancedMesh;
  14556. })(BABYLON || (BABYLON = {}));
  14557. var BABYLON;
  14558. (function (BABYLON) {
  14559. var _InstancesBatch = (function () {
  14560. function _InstancesBatch() {
  14561. this.mustReturn = false;
  14562. this.visibleInstances = new Array();
  14563. this.renderSelf = new Array();
  14564. }
  14565. return _InstancesBatch;
  14566. })();
  14567. BABYLON._InstancesBatch = _InstancesBatch;
  14568. var Mesh = (function (_super) {
  14569. __extends(Mesh, _super);
  14570. /**
  14571. * @constructor
  14572. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14573. * @param {Scene} scene - The scene to add this mesh to.
  14574. * @param {Node} parent - The parent of this mesh, if it has one
  14575. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14576. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14577. * When false, achieved by calling a clone(), also passing False.
  14578. * This will make creation of children, recursive.
  14579. */
  14580. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14581. if (parent === void 0) { parent = null; }
  14582. _super.call(this, name, scene);
  14583. // Members
  14584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14585. this.instances = new Array();
  14586. this._LODLevels = new Array();
  14587. this._onBeforeRenderCallbacks = new Array();
  14588. this._onAfterRenderCallbacks = new Array();
  14589. this._visibleInstances = {};
  14590. this._renderIdForInstances = new Array();
  14591. this._batchCache = new _InstancesBatch();
  14592. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14593. this._sideOrientation = Mesh._DEFAULTSIDE;
  14594. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14595. if (source) {
  14596. // Geometry
  14597. if (source._geometry) {
  14598. source._geometry.applyToMesh(this);
  14599. }
  14600. // Deep copy
  14601. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14602. this.id = name + "." + source.id;
  14603. // Material
  14604. this.material = source.material;
  14605. if (!doNotCloneChildren) {
  14606. // Children
  14607. for (var index = 0; index < scene.meshes.length; index++) {
  14608. var mesh = scene.meshes[index];
  14609. if (mesh.parent === source) {
  14610. // doNotCloneChildren is always going to be False
  14611. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14612. }
  14613. }
  14614. }
  14615. // Particles
  14616. for (index = 0; index < scene.particleSystems.length; index++) {
  14617. var system = scene.particleSystems[index];
  14618. if (system.emitter === source) {
  14619. system.clone(system.name, this);
  14620. }
  14621. }
  14622. this.computeWorldMatrix(true);
  14623. }
  14624. // Parent
  14625. if (parent !== null) {
  14626. this.parent = parent;
  14627. }
  14628. }
  14629. Object.defineProperty(Mesh, "FRONTSIDE", {
  14630. get: function () {
  14631. return Mesh._FRONTSIDE;
  14632. },
  14633. enumerable: true,
  14634. configurable: true
  14635. });
  14636. Object.defineProperty(Mesh, "BACKSIDE", {
  14637. get: function () {
  14638. return Mesh._BACKSIDE;
  14639. },
  14640. enumerable: true,
  14641. configurable: true
  14642. });
  14643. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14644. get: function () {
  14645. return Mesh._DOUBLESIDE;
  14646. },
  14647. enumerable: true,
  14648. configurable: true
  14649. });
  14650. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14651. get: function () {
  14652. return Mesh._DEFAULTSIDE;
  14653. },
  14654. enumerable: true,
  14655. configurable: true
  14656. });
  14657. Object.defineProperty(Mesh, "NO_CAP", {
  14658. get: function () {
  14659. return Mesh._NO_CAP;
  14660. },
  14661. enumerable: true,
  14662. configurable: true
  14663. });
  14664. Object.defineProperty(Mesh, "CAP_START", {
  14665. get: function () {
  14666. return Mesh._CAP_START;
  14667. },
  14668. enumerable: true,
  14669. configurable: true
  14670. });
  14671. Object.defineProperty(Mesh, "CAP_END", {
  14672. get: function () {
  14673. return Mesh._CAP_END;
  14674. },
  14675. enumerable: true,
  14676. configurable: true
  14677. });
  14678. Object.defineProperty(Mesh, "CAP_ALL", {
  14679. get: function () {
  14680. return Mesh._CAP_ALL;
  14681. },
  14682. enumerable: true,
  14683. configurable: true
  14684. });
  14685. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14686. // Methods
  14687. get: function () {
  14688. return this._LODLevels.length > 0;
  14689. },
  14690. enumerable: true,
  14691. configurable: true
  14692. });
  14693. Mesh.prototype._sortLODLevels = function () {
  14694. this._LODLevels.sort(function (a, b) {
  14695. if (a.distance < b.distance) {
  14696. return 1;
  14697. }
  14698. if (a.distance > b.distance) {
  14699. return -1;
  14700. }
  14701. return 0;
  14702. });
  14703. };
  14704. /**
  14705. * Add a mesh as LOD level triggered at the given distance.
  14706. * @param {number} distance - the distance from the center of the object to show this level
  14707. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14708. * @return {BABYLON.Mesh} this mesh (for chaining)
  14709. */
  14710. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14711. if (mesh && mesh._masterMesh) {
  14712. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14713. return this;
  14714. }
  14715. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14716. this._LODLevels.push(level);
  14717. if (mesh) {
  14718. mesh._masterMesh = this;
  14719. }
  14720. this._sortLODLevels();
  14721. return this;
  14722. };
  14723. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14724. for (var index = 0; index < this._LODLevels.length; index++) {
  14725. var level = this._LODLevels[index];
  14726. if (level.distance === distance) {
  14727. return level.mesh;
  14728. }
  14729. }
  14730. return null;
  14731. };
  14732. /**
  14733. * Remove a mesh from the LOD array
  14734. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14735. * @return {BABYLON.Mesh} this mesh (for chaining)
  14736. */
  14737. Mesh.prototype.removeLODLevel = function (mesh) {
  14738. for (var index = 0; index < this._LODLevels.length; index++) {
  14739. if (this._LODLevels[index].mesh === mesh) {
  14740. this._LODLevels.splice(index, 1);
  14741. if (mesh) {
  14742. mesh._masterMesh = null;
  14743. }
  14744. }
  14745. }
  14746. this._sortLODLevels();
  14747. return this;
  14748. };
  14749. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14750. if (!this._LODLevels || this._LODLevels.length === 0) {
  14751. return this;
  14752. }
  14753. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14754. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14755. if (this.onLODLevelSelection) {
  14756. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14757. }
  14758. return this;
  14759. }
  14760. for (var index = 0; index < this._LODLevels.length; index++) {
  14761. var level = this._LODLevels[index];
  14762. if (level.distance < distanceToCamera) {
  14763. if (level.mesh) {
  14764. level.mesh._preActivate();
  14765. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14766. }
  14767. if (this.onLODLevelSelection) {
  14768. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14769. }
  14770. return level.mesh;
  14771. }
  14772. }
  14773. if (this.onLODLevelSelection) {
  14774. this.onLODLevelSelection(distanceToCamera, this, this);
  14775. }
  14776. return this;
  14777. };
  14778. Object.defineProperty(Mesh.prototype, "geometry", {
  14779. get: function () {
  14780. return this._geometry;
  14781. },
  14782. enumerable: true,
  14783. configurable: true
  14784. });
  14785. Mesh.prototype.getTotalVertices = function () {
  14786. if (!this._geometry) {
  14787. return 0;
  14788. }
  14789. return this._geometry.getTotalVertices();
  14790. };
  14791. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14792. if (!this._geometry) {
  14793. return null;
  14794. }
  14795. return this._geometry.getVerticesData(kind, copyWhenShared);
  14796. };
  14797. Mesh.prototype.getVertexBuffer = function (kind) {
  14798. if (!this._geometry) {
  14799. return undefined;
  14800. }
  14801. return this._geometry.getVertexBuffer(kind);
  14802. };
  14803. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14804. if (!this._geometry) {
  14805. if (this._delayInfo) {
  14806. return this._delayInfo.indexOf(kind) !== -1;
  14807. }
  14808. return false;
  14809. }
  14810. return this._geometry.isVerticesDataPresent(kind);
  14811. };
  14812. Mesh.prototype.getVerticesDataKinds = function () {
  14813. if (!this._geometry) {
  14814. var result = [];
  14815. if (this._delayInfo) {
  14816. for (var kind in this._delayInfo) {
  14817. result.push(kind);
  14818. }
  14819. }
  14820. return result;
  14821. }
  14822. return this._geometry.getVerticesDataKinds();
  14823. };
  14824. Mesh.prototype.getTotalIndices = function () {
  14825. if (!this._geometry) {
  14826. return 0;
  14827. }
  14828. return this._geometry.getTotalIndices();
  14829. };
  14830. Mesh.prototype.getIndices = function (copyWhenShared) {
  14831. if (!this._geometry) {
  14832. return [];
  14833. }
  14834. return this._geometry.getIndices(copyWhenShared);
  14835. };
  14836. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14837. get: function () {
  14838. return this._masterMesh !== null && this._masterMesh !== undefined;
  14839. },
  14840. enumerable: true,
  14841. configurable: true
  14842. });
  14843. Mesh.prototype.isReady = function () {
  14844. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14845. return false;
  14846. }
  14847. return _super.prototype.isReady.call(this);
  14848. };
  14849. Mesh.prototype.isDisposed = function () {
  14850. return this._isDisposed;
  14851. };
  14852. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14853. get: function () {
  14854. return this._sideOrientation;
  14855. },
  14856. set: function (sideO) {
  14857. this._sideOrientation = sideO;
  14858. },
  14859. enumerable: true,
  14860. configurable: true
  14861. });
  14862. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14863. get: function () {
  14864. return this._areNormalsFrozen;
  14865. },
  14866. enumerable: true,
  14867. configurable: true
  14868. });
  14869. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14870. Mesh.prototype.freezeNormals = function () {
  14871. this._areNormalsFrozen = true;
  14872. };
  14873. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14874. Mesh.prototype.unfreezeNormals = function () {
  14875. this._areNormalsFrozen = false;
  14876. };
  14877. // Methods
  14878. Mesh.prototype._preActivate = function () {
  14879. var sceneRenderId = this.getScene().getRenderId();
  14880. if (this._preActivateId === sceneRenderId) {
  14881. return;
  14882. }
  14883. this._preActivateId = sceneRenderId;
  14884. this._visibleInstances = null;
  14885. };
  14886. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14887. if (!this._visibleInstances) {
  14888. this._visibleInstances = {};
  14889. this._visibleInstances.defaultRenderId = renderId;
  14890. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14891. }
  14892. if (!this._visibleInstances[renderId]) {
  14893. this._visibleInstances[renderId] = new Array();
  14894. }
  14895. this._visibleInstances[renderId].push(instance);
  14896. };
  14897. Mesh.prototype.refreshBoundingInfo = function () {
  14898. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14899. if (data) {
  14900. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14901. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14902. }
  14903. if (this.subMeshes) {
  14904. for (var index = 0; index < this.subMeshes.length; index++) {
  14905. this.subMeshes[index].refreshBoundingInfo();
  14906. }
  14907. }
  14908. this._updateBoundingInfo();
  14909. };
  14910. Mesh.prototype._createGlobalSubMesh = function () {
  14911. var totalVertices = this.getTotalVertices();
  14912. if (!totalVertices || !this.getIndices()) {
  14913. return null;
  14914. }
  14915. this.releaseSubMeshes();
  14916. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14917. };
  14918. Mesh.prototype.subdivide = function (count) {
  14919. if (count < 1) {
  14920. return;
  14921. }
  14922. var totalIndices = this.getTotalIndices();
  14923. var subdivisionSize = (totalIndices / count) | 0;
  14924. var offset = 0;
  14925. // Ensure that subdivisionSize is a multiple of 3
  14926. while (subdivisionSize % 3 !== 0) {
  14927. subdivisionSize++;
  14928. }
  14929. this.releaseSubMeshes();
  14930. for (var index = 0; index < count; index++) {
  14931. if (offset >= totalIndices) {
  14932. break;
  14933. }
  14934. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14935. offset += subdivisionSize;
  14936. }
  14937. this.synchronizeInstances();
  14938. };
  14939. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14940. if (kind instanceof Array) {
  14941. var temp = data;
  14942. data = kind;
  14943. kind = temp;
  14944. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14945. }
  14946. if (!this._geometry) {
  14947. var vertexData = new BABYLON.VertexData();
  14948. vertexData.set(data, kind);
  14949. var scene = this.getScene();
  14950. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14951. }
  14952. else {
  14953. this._geometry.setVerticesData(kind, data, updatable, stride);
  14954. }
  14955. };
  14956. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14957. if (!this._geometry) {
  14958. return;
  14959. }
  14960. if (!makeItUnique) {
  14961. this._geometry.updateVerticesData(kind, data, updateExtends);
  14962. }
  14963. else {
  14964. this.makeGeometryUnique();
  14965. this.updateVerticesData(kind, data, updateExtends, false);
  14966. }
  14967. };
  14968. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14969. if (!this._geometry) {
  14970. return;
  14971. }
  14972. if (!makeItUnique) {
  14973. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14974. }
  14975. else {
  14976. this.makeGeometryUnique();
  14977. this.updateVerticesDataDirectly(kind, data, offset, false);
  14978. }
  14979. };
  14980. // Mesh positions update function :
  14981. // updates the mesh positions according to the positionFunction returned values.
  14982. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14983. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14984. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14985. if (computeNormals === void 0) { computeNormals = true; }
  14986. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14987. positionFunction(positions);
  14988. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14989. if (computeNormals) {
  14990. var indices = this.getIndices();
  14991. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14992. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14993. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14994. }
  14995. };
  14996. Mesh.prototype.makeGeometryUnique = function () {
  14997. if (!this._geometry) {
  14998. return;
  14999. }
  15000. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15001. geometry.applyToMesh(this);
  15002. };
  15003. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15004. if (!this._geometry) {
  15005. var vertexData = new BABYLON.VertexData();
  15006. vertexData.indices = indices;
  15007. var scene = this.getScene();
  15008. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15009. }
  15010. else {
  15011. this._geometry.setIndices(indices, totalVertices);
  15012. }
  15013. };
  15014. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15015. var engine = this.getScene().getEngine();
  15016. // Wireframe
  15017. var indexToBind;
  15018. switch (fillMode) {
  15019. case BABYLON.Material.PointFillMode:
  15020. indexToBind = null;
  15021. break;
  15022. case BABYLON.Material.WireFrameFillMode:
  15023. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15024. break;
  15025. default:
  15026. case BABYLON.Material.TriangleFillMode:
  15027. indexToBind = this._geometry.getIndexBuffer();
  15028. break;
  15029. }
  15030. // VBOs
  15031. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15032. };
  15033. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15034. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15035. return;
  15036. }
  15037. var engine = this.getScene().getEngine();
  15038. // Draw order
  15039. switch (fillMode) {
  15040. case BABYLON.Material.PointFillMode:
  15041. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15042. break;
  15043. case BABYLON.Material.WireFrameFillMode:
  15044. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15045. break;
  15046. default:
  15047. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15048. }
  15049. };
  15050. Mesh.prototype.registerBeforeRender = function (func) {
  15051. this._onBeforeRenderCallbacks.push(func);
  15052. };
  15053. Mesh.prototype.unregisterBeforeRender = function (func) {
  15054. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15055. if (index > -1) {
  15056. this._onBeforeRenderCallbacks.splice(index, 1);
  15057. }
  15058. };
  15059. Mesh.prototype.registerAfterRender = function (func) {
  15060. this._onAfterRenderCallbacks.push(func);
  15061. };
  15062. Mesh.prototype.unregisterAfterRender = function (func) {
  15063. var index = this._onAfterRenderCallbacks.indexOf(func);
  15064. if (index > -1) {
  15065. this._onAfterRenderCallbacks.splice(index, 1);
  15066. }
  15067. };
  15068. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15069. var scene = this.getScene();
  15070. this._batchCache.mustReturn = false;
  15071. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15072. this._batchCache.visibleInstances[subMeshId] = null;
  15073. if (this._visibleInstances) {
  15074. var currentRenderId = scene.getRenderId();
  15075. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15076. var selfRenderId = this._renderId;
  15077. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15078. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15079. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15080. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15081. }
  15082. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15083. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15084. this._batchCache.mustReturn = true;
  15085. return this._batchCache;
  15086. }
  15087. if (currentRenderId !== selfRenderId) {
  15088. this._batchCache.renderSelf[subMeshId] = false;
  15089. }
  15090. }
  15091. this._renderIdForInstances[subMeshId] = currentRenderId;
  15092. }
  15093. return this._batchCache;
  15094. };
  15095. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15096. var visibleInstances = batch.visibleInstances[subMesh._id];
  15097. var matricesCount = visibleInstances.length + 1;
  15098. var bufferSize = matricesCount * 16 * 4;
  15099. while (this._instancesBufferSize < bufferSize) {
  15100. this._instancesBufferSize *= 2;
  15101. }
  15102. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15103. if (this._worldMatricesInstancesBuffer) {
  15104. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15105. }
  15106. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15107. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15108. }
  15109. var offset = 0;
  15110. var instancesCount = 0;
  15111. var world = this.getWorldMatrix();
  15112. if (batch.renderSelf[subMesh._id]) {
  15113. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15114. offset += 16;
  15115. instancesCount++;
  15116. }
  15117. if (visibleInstances) {
  15118. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15119. var instance = visibleInstances[instanceIndex];
  15120. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15121. offset += 16;
  15122. instancesCount++;
  15123. }
  15124. }
  15125. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15126. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15127. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15128. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15129. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15130. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15131. this._draw(subMesh, fillMode, instancesCount);
  15132. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15133. };
  15134. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15135. var scene = this.getScene();
  15136. var engine = scene.getEngine();
  15137. if (hardwareInstancedRendering) {
  15138. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15139. }
  15140. else {
  15141. if (batch.renderSelf[subMesh._id]) {
  15142. // Draw
  15143. if (onBeforeDraw) {
  15144. onBeforeDraw(false, this.getWorldMatrix());
  15145. }
  15146. this._draw(subMesh, fillMode);
  15147. }
  15148. if (batch.visibleInstances[subMesh._id]) {
  15149. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15150. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15151. // World
  15152. var world = instance.getWorldMatrix();
  15153. if (onBeforeDraw) {
  15154. onBeforeDraw(true, world);
  15155. }
  15156. // Draw
  15157. this._draw(subMesh, fillMode);
  15158. }
  15159. }
  15160. }
  15161. };
  15162. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15163. var scene = this.getScene();
  15164. // Managing instances
  15165. var batch = this._getInstancesRenderList(subMesh._id);
  15166. if (batch.mustReturn) {
  15167. return;
  15168. }
  15169. // Checking geometry state
  15170. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15171. return;
  15172. }
  15173. var callbackIndex;
  15174. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15175. this._onBeforeRenderCallbacks[callbackIndex](this);
  15176. }
  15177. var engine = scene.getEngine();
  15178. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15179. // Material
  15180. var effectiveMaterial = subMesh.getMaterial();
  15181. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15182. return;
  15183. }
  15184. // Outline - step 1
  15185. var savedDepthWrite = engine.getDepthWrite();
  15186. if (this.renderOutline) {
  15187. engine.setDepthWrite(false);
  15188. scene.getOutlineRenderer().render(subMesh, batch);
  15189. engine.setDepthWrite(savedDepthWrite);
  15190. }
  15191. effectiveMaterial._preBind();
  15192. var effect = effectiveMaterial.getEffect();
  15193. // Bind
  15194. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15195. this._bind(subMesh, effect, fillMode);
  15196. var world = this.getWorldMatrix();
  15197. effectiveMaterial.bind(world, this);
  15198. // Alpha mode
  15199. if (enableAlphaMode) {
  15200. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15201. }
  15202. // Draw
  15203. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15204. if (isInstance) {
  15205. effectiveMaterial.bindOnlyWorldMatrix(world);
  15206. }
  15207. });
  15208. // Unbind
  15209. effectiveMaterial.unbind();
  15210. // Outline - step 2
  15211. if (this.renderOutline && savedDepthWrite) {
  15212. engine.setDepthWrite(true);
  15213. engine.setColorWrite(false);
  15214. scene.getOutlineRenderer().render(subMesh, batch);
  15215. engine.setColorWrite(true);
  15216. }
  15217. // Overlay
  15218. if (this.renderOverlay) {
  15219. var currentMode = engine.getAlphaMode();
  15220. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15221. scene.getOutlineRenderer().render(subMesh, batch, true);
  15222. engine.setAlphaMode(currentMode);
  15223. }
  15224. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15225. this._onAfterRenderCallbacks[callbackIndex](this);
  15226. }
  15227. };
  15228. Mesh.prototype.getEmittedParticleSystems = function () {
  15229. var results = new Array();
  15230. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15231. var particleSystem = this.getScene().particleSystems[index];
  15232. if (particleSystem.emitter === this) {
  15233. results.push(particleSystem);
  15234. }
  15235. }
  15236. return results;
  15237. };
  15238. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15239. var results = new Array();
  15240. var descendants = this.getDescendants();
  15241. descendants.push(this);
  15242. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15243. var particleSystem = this.getScene().particleSystems[index];
  15244. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15245. results.push(particleSystem);
  15246. }
  15247. }
  15248. return results;
  15249. };
  15250. Mesh.prototype.getChildren = function () {
  15251. var results = [];
  15252. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15253. var mesh = this.getScene().meshes[index];
  15254. if (mesh.parent === this) {
  15255. results.push(mesh);
  15256. }
  15257. }
  15258. return results;
  15259. };
  15260. Mesh.prototype._checkDelayState = function () {
  15261. var _this = this;
  15262. var that = this;
  15263. var scene = this.getScene();
  15264. if (this._geometry) {
  15265. this._geometry.load(scene);
  15266. }
  15267. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15268. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15269. scene._addPendingData(that);
  15270. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15271. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15272. if (data instanceof ArrayBuffer) {
  15273. _this._delayLoadingFunction(data, _this);
  15274. }
  15275. else {
  15276. _this._delayLoadingFunction(JSON.parse(data), _this);
  15277. }
  15278. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15279. scene._removePendingData(_this);
  15280. }, function () { }, scene.database, getBinaryData);
  15281. }
  15282. };
  15283. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15284. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15285. return false;
  15286. }
  15287. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15288. return false;
  15289. }
  15290. this._checkDelayState();
  15291. return true;
  15292. };
  15293. Mesh.prototype.setMaterialByID = function (id) {
  15294. var materials = this.getScene().materials;
  15295. var index;
  15296. for (index = 0; index < materials.length; index++) {
  15297. if (materials[index].id === id) {
  15298. this.material = materials[index];
  15299. return;
  15300. }
  15301. }
  15302. // Multi
  15303. var multiMaterials = this.getScene().multiMaterials;
  15304. for (index = 0; index < multiMaterials.length; index++) {
  15305. if (multiMaterials[index].id === id) {
  15306. this.material = multiMaterials[index];
  15307. return;
  15308. }
  15309. }
  15310. };
  15311. Mesh.prototype.getAnimatables = function () {
  15312. var results = [];
  15313. if (this.material) {
  15314. results.push(this.material);
  15315. }
  15316. if (this.skeleton) {
  15317. results.push(this.skeleton);
  15318. }
  15319. return results;
  15320. };
  15321. // Geometry
  15322. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15323. // Position
  15324. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15325. return;
  15326. }
  15327. this._resetPointsArrayCache();
  15328. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15329. var temp = [];
  15330. var index;
  15331. for (index = 0; index < data.length; index += 3) {
  15332. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15333. }
  15334. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15335. // Normals
  15336. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15337. return;
  15338. }
  15339. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15340. temp = [];
  15341. for (index = 0; index < data.length; index += 3) {
  15342. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15343. }
  15344. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15345. // flip faces?
  15346. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15347. this.flipFaces();
  15348. }
  15349. };
  15350. // Will apply current transform to mesh and reset world matrix
  15351. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15352. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15353. this.scaling.copyFromFloats(1, 1, 1);
  15354. this.position.copyFromFloats(0, 0, 0);
  15355. this.rotation.copyFromFloats(0, 0, 0);
  15356. //only if quaternion is already set
  15357. if (this.rotationQuaternion) {
  15358. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15359. }
  15360. this._worldMatrix = BABYLON.Matrix.Identity();
  15361. };
  15362. // Cache
  15363. Mesh.prototype._resetPointsArrayCache = function () {
  15364. this._positions = null;
  15365. };
  15366. Mesh.prototype._generatePointsArray = function () {
  15367. if (this._positions)
  15368. return true;
  15369. this._positions = [];
  15370. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15371. if (!data) {
  15372. return false;
  15373. }
  15374. for (var index = 0; index < data.length; index += 3) {
  15375. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15376. }
  15377. return true;
  15378. };
  15379. // Clone
  15380. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15381. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15382. };
  15383. // Dispose
  15384. Mesh.prototype.dispose = function (doNotRecurse) {
  15385. if (this._geometry) {
  15386. this._geometry.releaseForMesh(this, true);
  15387. }
  15388. // Instances
  15389. if (this._worldMatricesInstancesBuffer) {
  15390. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15391. this._worldMatricesInstancesBuffer = null;
  15392. }
  15393. while (this.instances.length) {
  15394. this.instances[0].dispose();
  15395. }
  15396. _super.prototype.dispose.call(this, doNotRecurse);
  15397. };
  15398. // Geometric tools
  15399. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15400. var _this = this;
  15401. var scene = this.getScene();
  15402. var onload = function (img) {
  15403. // Getting height map data
  15404. var canvas = document.createElement("canvas");
  15405. var context = canvas.getContext("2d");
  15406. var heightMapWidth = img.width;
  15407. var heightMapHeight = img.height;
  15408. canvas.width = heightMapWidth;
  15409. canvas.height = heightMapHeight;
  15410. context.drawImage(img, 0, 0);
  15411. // Create VertexData from map data
  15412. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15413. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15414. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15415. //execute success callback, if set
  15416. if (onSuccess) {
  15417. onSuccess(_this);
  15418. }
  15419. };
  15420. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15421. };
  15422. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15423. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15424. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15425. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15426. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15427. return;
  15428. }
  15429. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15430. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15431. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15432. var position = BABYLON.Vector3.Zero();
  15433. var normal = BABYLON.Vector3.Zero();
  15434. var uv = BABYLON.Vector2.Zero();
  15435. for (var index = 0; index < positions.length; index += 3) {
  15436. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15437. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15438. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15439. // Compute height
  15440. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15441. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15442. var pos = (u + v * heightMapWidth) * 4;
  15443. var r = buffer[pos] / 255.0;
  15444. var g = buffer[pos + 1] / 255.0;
  15445. var b = buffer[pos + 2] / 255.0;
  15446. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15447. normal.normalize();
  15448. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15449. position = position.add(normal);
  15450. position.toArray(positions, index);
  15451. }
  15452. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15453. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15454. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15455. };
  15456. Mesh.prototype.convertToFlatShadedMesh = function () {
  15457. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15458. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15459. var kinds = this.getVerticesDataKinds();
  15460. var vbs = [];
  15461. var data = [];
  15462. var newdata = [];
  15463. var updatableNormals = false;
  15464. var kindIndex;
  15465. var kind;
  15466. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15467. kind = kinds[kindIndex];
  15468. var vertexBuffer = this.getVertexBuffer(kind);
  15469. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15470. updatableNormals = vertexBuffer.isUpdatable();
  15471. kinds.splice(kindIndex, 1);
  15472. kindIndex--;
  15473. continue;
  15474. }
  15475. vbs[kind] = vertexBuffer;
  15476. data[kind] = vbs[kind].getData();
  15477. newdata[kind] = [];
  15478. }
  15479. // Save previous submeshes
  15480. var previousSubmeshes = this.subMeshes.slice(0);
  15481. var indices = this.getIndices();
  15482. var totalIndices = this.getTotalIndices();
  15483. // Generating unique vertices per face
  15484. var index;
  15485. for (index = 0; index < totalIndices; index++) {
  15486. var vertexIndex = indices[index];
  15487. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15488. kind = kinds[kindIndex];
  15489. var stride = vbs[kind].getStrideSize();
  15490. for (var offset = 0; offset < stride; offset++) {
  15491. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15492. }
  15493. }
  15494. }
  15495. // Updating faces & normal
  15496. var normals = [];
  15497. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15498. for (index = 0; index < totalIndices; index += 3) {
  15499. indices[index] = index;
  15500. indices[index + 1] = index + 1;
  15501. indices[index + 2] = index + 2;
  15502. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15503. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15504. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15505. var p1p2 = p1.subtract(p2);
  15506. var p3p2 = p3.subtract(p2);
  15507. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15508. // Store same normals for every vertex
  15509. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15510. normals.push(normal.x);
  15511. normals.push(normal.y);
  15512. normals.push(normal.z);
  15513. }
  15514. }
  15515. this.setIndices(indices);
  15516. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15517. // Updating vertex buffers
  15518. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15519. kind = kinds[kindIndex];
  15520. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15521. }
  15522. // Updating submeshes
  15523. this.releaseSubMeshes();
  15524. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15525. var previousOne = previousSubmeshes[submeshIndex];
  15526. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15527. }
  15528. this.synchronizeInstances();
  15529. };
  15530. // will inverse faces orientations, and invert normals too if specified
  15531. Mesh.prototype.flipFaces = function (flipNormals) {
  15532. if (flipNormals === void 0) { flipNormals = false; }
  15533. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15534. var i;
  15535. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15536. for (i = 0; i < vertex_data.normals.length; i++) {
  15537. vertex_data.normals[i] *= -1;
  15538. }
  15539. }
  15540. var temp;
  15541. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15542. // reassign indices
  15543. temp = vertex_data.indices[i + 1];
  15544. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15545. vertex_data.indices[i + 2] = temp;
  15546. }
  15547. vertex_data.applyToMesh(this);
  15548. };
  15549. // Instances
  15550. Mesh.prototype.createInstance = function (name) {
  15551. return new BABYLON.InstancedMesh(name, this);
  15552. };
  15553. Mesh.prototype.synchronizeInstances = function () {
  15554. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15555. var instance = this.instances[instanceIndex];
  15556. instance._syncSubMeshes();
  15557. }
  15558. };
  15559. /**
  15560. * Simplify the mesh according to the given array of settings.
  15561. * Function will return immediately and will simplify async.
  15562. * @param settings a collection of simplification settings.
  15563. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15564. * @param type the type of simplification to run.
  15565. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15566. */
  15567. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15568. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15569. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15570. this.getScene().simplificationQueue.addTask({
  15571. settings: settings,
  15572. parallelProcessing: parallelProcessing,
  15573. mesh: this,
  15574. simplificationType: simplificationType,
  15575. successCallback: successCallback
  15576. });
  15577. };
  15578. /**
  15579. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15580. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15581. * This should be used together with the simplification to avoid disappearing triangles.
  15582. * @param successCallback an optional success callback to be called after the optimization finished.
  15583. */
  15584. Mesh.prototype.optimizeIndices = function (successCallback) {
  15585. var _this = this;
  15586. var indices = this.getIndices();
  15587. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15588. var vectorPositions = [];
  15589. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15590. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15591. }
  15592. var dupes = [];
  15593. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15594. var realPos = vectorPositions.length - 1 - iteration;
  15595. var testedPosition = vectorPositions[realPos];
  15596. for (var j = 0; j < realPos; ++j) {
  15597. var againstPosition = vectorPositions[j];
  15598. if (testedPosition.equals(againstPosition)) {
  15599. dupes[realPos] = j;
  15600. break;
  15601. }
  15602. }
  15603. }, function () {
  15604. for (var i = 0; i < indices.length; ++i) {
  15605. indices[i] = dupes[indices[i]] || indices[i];
  15606. }
  15607. //indices are now reordered
  15608. var originalSubMeshes = _this.subMeshes.slice(0);
  15609. _this.setIndices(indices);
  15610. _this.subMeshes = originalSubMeshes;
  15611. if (successCallback) {
  15612. successCallback(_this);
  15613. }
  15614. });
  15615. };
  15616. // Statics
  15617. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15618. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15619. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15620. if (ribbonInstance) {
  15621. // positionFunction : ribbon case
  15622. // only pathArray and sideOrientation parameters are taken into account for positions update
  15623. var positionFunction = function (positions) {
  15624. var minlg = pathArray[0].length;
  15625. var i = 0;
  15626. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15627. for (var si = 1; si <= ns; si++) {
  15628. for (var p = 0; p < pathArray.length; p++) {
  15629. var path = pathArray[p];
  15630. var l = path.length;
  15631. minlg = (minlg < l) ? minlg : l;
  15632. var j = 0;
  15633. while (j < minlg) {
  15634. positions[i] = path[j].x;
  15635. positions[i + 1] = path[j].y;
  15636. positions[i + 2] = path[j].z;
  15637. j++;
  15638. i += 3;
  15639. }
  15640. if (ribbonInstance._closePath) {
  15641. positions[i] = path[0].x;
  15642. positions[i + 1] = path[0].y;
  15643. positions[i + 2] = path[0].z;
  15644. i += 3;
  15645. }
  15646. }
  15647. }
  15648. };
  15649. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15650. positionFunction(positions);
  15651. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15652. if (!(ribbonInstance.areNormalsFrozen)) {
  15653. var indices = ribbonInstance.getIndices();
  15654. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15655. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15656. if (ribbonInstance._closePath) {
  15657. var indexFirst = 0;
  15658. var indexLast = 0;
  15659. for (var p = 0; p < pathArray.length; p++) {
  15660. indexFirst = ribbonInstance._idx[p] * 3;
  15661. if (p + 1 < pathArray.length) {
  15662. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15663. }
  15664. else {
  15665. indexLast = normals.length - 3;
  15666. }
  15667. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15668. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15669. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15670. normals[indexLast] = normals[indexFirst];
  15671. normals[indexLast + 1] = normals[indexFirst + 1];
  15672. normals[indexLast + 2] = normals[indexFirst + 2];
  15673. }
  15674. }
  15675. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15676. }
  15677. return ribbonInstance;
  15678. }
  15679. else {
  15680. var ribbon = new Mesh(name, scene);
  15681. ribbon.sideOrientation = sideOrientation;
  15682. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15683. if (closePath) {
  15684. ribbon._idx = vertexData._idx;
  15685. }
  15686. ribbon._closePath = closePath;
  15687. vertexData.applyToMesh(ribbon, updatable);
  15688. return ribbon;
  15689. }
  15690. };
  15691. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15692. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15693. var disc = new Mesh(name, scene);
  15694. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15695. vertexData.applyToMesh(disc, updatable);
  15696. return disc;
  15697. };
  15698. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15699. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15700. // Check parameters
  15701. updatable = updatable || options.updatable;
  15702. var box = new Mesh(name, scene);
  15703. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15704. vertexData.applyToMesh(box, updatable);
  15705. return box;
  15706. };
  15707. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15708. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15709. if (diameterOrScene instanceof BABYLON.Scene) {
  15710. scene = diameterOrScene;
  15711. updatable = options.updatable;
  15712. }
  15713. else {
  15714. var segments = options;
  15715. options = {
  15716. segments: segments,
  15717. diameterX: diameterOrScene,
  15718. diameterY: diameterOrScene,
  15719. diameterZ: diameterOrScene,
  15720. sideOrientation: sideOrientation
  15721. };
  15722. }
  15723. var sphere = new Mesh(name, scene);
  15724. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15725. vertexData.applyToMesh(sphere, updatable);
  15726. return sphere;
  15727. };
  15728. // Cylinder and cone
  15729. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15730. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15731. // subdivisions is a new parameter, we need to support old signature
  15732. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15733. if (scene !== undefined) {
  15734. updatable = scene;
  15735. }
  15736. scene = subdivisions;
  15737. subdivisions = 1;
  15738. }
  15739. var cylinder = new Mesh(name, scene);
  15740. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15741. vertexData.applyToMesh(cylinder, updatable);
  15742. return cylinder;
  15743. };
  15744. // Torus (Code from SharpDX.org)
  15745. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15746. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15747. var torus = new Mesh(name, scene);
  15748. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15749. vertexData.applyToMesh(torus, updatable);
  15750. return torus;
  15751. };
  15752. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15753. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15754. var torusKnot = new Mesh(name, scene);
  15755. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15756. vertexData.applyToMesh(torusKnot, updatable);
  15757. return torusKnot;
  15758. };
  15759. // Lines
  15760. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15761. if (linesInstance === void 0) { linesInstance = null; }
  15762. if (linesInstance) {
  15763. var positionFunction = function (positions) {
  15764. var i = 0;
  15765. for (var p = 0; p < points.length; p++) {
  15766. positions[i] = points[p].x;
  15767. positions[i + 1] = points[p].y;
  15768. positions[i + 2] = points[p].z;
  15769. i += 3;
  15770. }
  15771. };
  15772. linesInstance.updateMeshPositions(positionFunction, false);
  15773. return linesInstance;
  15774. }
  15775. // lines creation
  15776. var lines = new BABYLON.LinesMesh(name, scene);
  15777. var vertexData = BABYLON.VertexData.CreateLines(points);
  15778. vertexData.applyToMesh(lines, updatable);
  15779. return lines;
  15780. };
  15781. // Dashed Lines
  15782. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15783. if (linesInstance === void 0) { linesInstance = null; }
  15784. if (linesInstance) {
  15785. var positionFunction = function (positions) {
  15786. var curvect = BABYLON.Vector3.Zero();
  15787. var nbSeg = positions.length / 6;
  15788. var lg = 0;
  15789. var nb = 0;
  15790. var shft = 0;
  15791. var dashshft = 0;
  15792. var curshft = 0;
  15793. var p = 0;
  15794. var i = 0;
  15795. var j = 0;
  15796. for (i = 0; i < points.length - 1; i++) {
  15797. points[i + 1].subtractToRef(points[i], curvect);
  15798. lg += curvect.length();
  15799. }
  15800. shft = lg / nbSeg;
  15801. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15802. for (i = 0; i < points.length - 1; i++) {
  15803. points[i + 1].subtractToRef(points[i], curvect);
  15804. nb = Math.floor(curvect.length() / shft);
  15805. curvect.normalize();
  15806. j = 0;
  15807. while (j < nb && p < positions.length) {
  15808. curshft = shft * j;
  15809. positions[p] = points[i].x + curshft * curvect.x;
  15810. positions[p + 1] = points[i].y + curshft * curvect.y;
  15811. positions[p + 2] = points[i].z + curshft * curvect.z;
  15812. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15813. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15814. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15815. p += 6;
  15816. j++;
  15817. }
  15818. }
  15819. while (p < positions.length) {
  15820. positions[p] = points[i].x;
  15821. positions[p + 1] = points[i].y;
  15822. positions[p + 2] = points[i].z;
  15823. p += 3;
  15824. }
  15825. };
  15826. linesInstance.updateMeshPositions(positionFunction, false);
  15827. return linesInstance;
  15828. }
  15829. // dashed lines creation
  15830. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15831. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15832. vertexData.applyToMesh(dashedLines, updatable);
  15833. dashedLines.dashSize = dashSize;
  15834. dashedLines.gapSize = gapSize;
  15835. return dashedLines;
  15836. };
  15837. // Extrusion
  15838. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15839. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15840. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15841. scale = scale || 1;
  15842. rotation = rotation || 0;
  15843. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15844. return extruded;
  15845. };
  15846. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15847. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15848. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15849. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15850. return extrudedCustom;
  15851. };
  15852. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15853. // extrusion geometry
  15854. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15855. var tangents = path3D.getTangents();
  15856. var normals = path3D.getNormals();
  15857. var binormals = path3D.getBinormals();
  15858. var distances = path3D.getDistances();
  15859. var angle = 0;
  15860. var returnScale = function (i, distance) { return scale; };
  15861. var returnRotation = function (i, distance) { return rotation; };
  15862. var rotate = custom ? rotateFunction : returnRotation;
  15863. var scl = custom ? scaleFunction : returnScale;
  15864. var index = 0;
  15865. for (var i = 0; i < curve.length; i++) {
  15866. var shapePath = new Array();
  15867. var angleStep = rotate(i, distances[i]);
  15868. var scaleRatio = scl(i, distances[i]);
  15869. for (var p = 0; p < shape.length; p++) {
  15870. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15871. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15872. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15873. shapePath.push(rotated);
  15874. }
  15875. shapePaths[index] = shapePath;
  15876. angle += angleStep;
  15877. index++;
  15878. }
  15879. // cap
  15880. var capPath = function (shapePath) {
  15881. var pointCap = Array();
  15882. var barycenter = BABYLON.Vector3.Zero();
  15883. var i;
  15884. for (i = 0; i < shapePath.length; i++) {
  15885. barycenter.addInPlace(shapePath[i]);
  15886. }
  15887. barycenter.scaleInPlace(1 / shapePath.length);
  15888. for (i = 0; i < shapePath.length; i++) {
  15889. pointCap.push(barycenter);
  15890. }
  15891. return pointCap;
  15892. };
  15893. switch (cap) {
  15894. case Mesh.NO_CAP:
  15895. break;
  15896. case Mesh.CAP_START:
  15897. shapePaths.unshift(capPath(shapePaths[0]));
  15898. break;
  15899. case Mesh.CAP_END:
  15900. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15901. break;
  15902. case Mesh.CAP_ALL:
  15903. shapePaths.unshift(capPath(shapePaths[0]));
  15904. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15905. break;
  15906. default:
  15907. break;
  15908. }
  15909. return shapePaths;
  15910. };
  15911. var path3D;
  15912. var pathArray;
  15913. if (instance) {
  15914. path3D = (instance.path3D).update(curve);
  15915. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15916. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15917. return instance;
  15918. }
  15919. // extruded shape creation
  15920. path3D = new BABYLON.Path3D(curve);
  15921. var newShapePaths = new Array();
  15922. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15923. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15924. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15925. extrudedGeneric.pathArray = pathArray;
  15926. extrudedGeneric.path3D = path3D;
  15927. extrudedGeneric.cap = cap;
  15928. return extrudedGeneric;
  15929. };
  15930. // Lathe
  15931. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15932. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15933. radius = radius || 1;
  15934. tessellation = tessellation || radius * 60;
  15935. var pi2 = Math.PI * 2;
  15936. var shapeLathe = new Array();
  15937. // first rotatable point
  15938. var i = 0;
  15939. while (shape[i].x === 0) {
  15940. i++;
  15941. }
  15942. var pt = shape[i];
  15943. for (i = 0; i < shape.length; i++) {
  15944. shapeLathe.push(shape[i].subtract(pt));
  15945. }
  15946. // circle path
  15947. var step = pi2 / tessellation;
  15948. var rotated;
  15949. var path = new Array();
  15950. ;
  15951. for (i = 0; i < tessellation; i++) {
  15952. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15953. path.push(rotated);
  15954. }
  15955. path.push(path[0]);
  15956. // extrusion
  15957. var scaleFunction = function () { return 1; };
  15958. var rotateFunction = function () { return 0; };
  15959. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15960. return lathe;
  15961. };
  15962. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  15963. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15964. var plane = new Mesh(name, scene);
  15965. var vertexData = BABYLON.VertexData.CreatePlane(options, sideOrientation);
  15966. vertexData.applyToMesh(plane, updatable || options.updatable);
  15967. return plane;
  15968. };
  15969. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  15970. if (heightOrScene instanceof BABYLON.Scene) {
  15971. scene = heightOrScene;
  15972. updatable = options.updatable;
  15973. }
  15974. else {
  15975. var width = options;
  15976. options = {
  15977. width: width,
  15978. height: heightOrScene,
  15979. subdivisions: subdivisions
  15980. };
  15981. }
  15982. var ground = new BABYLON.GroundMesh(name, scene);
  15983. ground._setReady(false);
  15984. ground._subdivisions = options.subdivisions || 1;
  15985. var vertexData = BABYLON.VertexData.CreateGround(options);
  15986. vertexData.applyToMesh(ground, updatable || options.updatable);
  15987. ground._setReady(true);
  15988. return ground;
  15989. };
  15990. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15991. var tiledGround = new Mesh(name, scene);
  15992. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15993. vertexData.applyToMesh(tiledGround, updatable);
  15994. return tiledGround;
  15995. };
  15996. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15997. var ground = new BABYLON.GroundMesh(name, scene);
  15998. ground._subdivisions = subdivisions;
  15999. ground._setReady(false);
  16000. var onload = function (img) {
  16001. // Getting height map data
  16002. var canvas = document.createElement("canvas");
  16003. var context = canvas.getContext("2d");
  16004. var heightMapWidth = img.width;
  16005. var heightMapHeight = img.height;
  16006. canvas.width = heightMapWidth;
  16007. canvas.height = heightMapHeight;
  16008. context.drawImage(img, 0, 0);
  16009. // Create VertexData from map data
  16010. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16011. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  16012. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  16013. vertexData.applyToMesh(ground, updatable);
  16014. ground._setReady(true);
  16015. //execute ready callback, if set
  16016. if (onReady) {
  16017. onReady(ground);
  16018. }
  16019. };
  16020. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16021. return ground;
  16022. };
  16023. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  16024. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16025. if (tubeInstance === void 0) { tubeInstance = null; }
  16026. // tube geometry
  16027. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  16028. var tangents = path3D.getTangents();
  16029. var normals = path3D.getNormals();
  16030. var distances = path3D.getDistances();
  16031. var pi2 = Math.PI * 2;
  16032. var step = pi2 / tessellation;
  16033. var returnRadius = function (i, distance) { return radius; };
  16034. var radiusFunctionFinal = radiusFunction || returnRadius;
  16035. var circlePath;
  16036. var rad;
  16037. var normal;
  16038. var rotated;
  16039. var rotationMatrix;
  16040. var index = 0;
  16041. for (var i = 0; i < path.length; i++) {
  16042. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16043. circlePath = Array(); // current circle array
  16044. normal = normals[i]; // current normal
  16045. for (var t = 0; t < tessellation; t++) {
  16046. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  16047. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16048. circlePath.push(rotated);
  16049. }
  16050. circlePaths[index] = circlePath;
  16051. index++;
  16052. }
  16053. // cap
  16054. var capPath = function (nbPoints, pathIndex) {
  16055. var pointCap = Array();
  16056. for (var i = 0; i < nbPoints; i++) {
  16057. pointCap.push(path[pathIndex]);
  16058. }
  16059. return pointCap;
  16060. };
  16061. switch (cap) {
  16062. case Mesh.NO_CAP:
  16063. break;
  16064. case Mesh.CAP_START:
  16065. circlePaths.unshift(capPath(tessellation + 1, 0));
  16066. break;
  16067. case Mesh.CAP_END:
  16068. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16069. break;
  16070. case Mesh.CAP_ALL:
  16071. circlePaths.unshift(capPath(tessellation + 1, 0));
  16072. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  16073. break;
  16074. default:
  16075. break;
  16076. }
  16077. return circlePaths;
  16078. };
  16079. var path3D;
  16080. var pathArray;
  16081. if (tubeInstance) {
  16082. path3D = (tubeInstance.path3D).update(path);
  16083. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  16084. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  16085. return tubeInstance;
  16086. }
  16087. // tube creation
  16088. path3D = new BABYLON.Path3D(path);
  16089. var newPathArray = new Array();
  16090. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16091. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16092. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16093. tube.pathArray = pathArray;
  16094. tube.path3D = path3D;
  16095. tube.tessellation = tessellation;
  16096. tube.cap = cap;
  16097. return tube;
  16098. };
  16099. // Decals
  16100. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16101. if (angle === void 0) { angle = 0; }
  16102. var indices = sourceMesh.getIndices();
  16103. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16104. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16105. // Getting correct rotation
  16106. if (!normal) {
  16107. var target = new BABYLON.Vector3(0, 0, 1);
  16108. var camera = sourceMesh.getScene().activeCamera;
  16109. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16110. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16111. }
  16112. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16113. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16114. var pitch = Math.atan2(normal.y, len);
  16115. // Matrix
  16116. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16117. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16118. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16119. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16120. var vertexData = new BABYLON.VertexData();
  16121. vertexData.indices = [];
  16122. vertexData.positions = [];
  16123. vertexData.normals = [];
  16124. vertexData.uvs = [];
  16125. var currentVertexDataIndex = 0;
  16126. var extractDecalVector3 = function (indexId) {
  16127. var vertexId = indices[indexId];
  16128. var result = new BABYLON.PositionNormalVertex();
  16129. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16130. // Send vector to decal local world
  16131. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16132. // Get normal
  16133. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16134. return result;
  16135. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16136. var clip = function (vertices, axis) {
  16137. if (vertices.length === 0) {
  16138. return vertices;
  16139. }
  16140. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16141. var clipVertices = function (v0, v1) {
  16142. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16143. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16144. };
  16145. var result = new Array();
  16146. for (var index = 0; index < vertices.length; index += 3) {
  16147. var v1Out;
  16148. var v2Out;
  16149. var v3Out;
  16150. var total = 0;
  16151. var nV1, nV2, nV3, nV4;
  16152. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16153. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16154. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16155. v1Out = d1 > 0;
  16156. v2Out = d2 > 0;
  16157. v3Out = d3 > 0;
  16158. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16159. switch (total) {
  16160. case 0:
  16161. result.push(vertices[index]);
  16162. result.push(vertices[index + 1]);
  16163. result.push(vertices[index + 2]);
  16164. break;
  16165. case 1:
  16166. if (v1Out) {
  16167. nV1 = vertices[index + 1];
  16168. nV2 = vertices[index + 2];
  16169. nV3 = clipVertices(vertices[index], nV1);
  16170. nV4 = clipVertices(vertices[index], nV2);
  16171. }
  16172. if (v2Out) {
  16173. nV1 = vertices[index];
  16174. nV2 = vertices[index + 2];
  16175. nV3 = clipVertices(vertices[index + 1], nV1);
  16176. nV4 = clipVertices(vertices[index + 1], nV2);
  16177. result.push(nV3);
  16178. result.push(nV2.clone());
  16179. result.push(nV1.clone());
  16180. result.push(nV2.clone());
  16181. result.push(nV3.clone());
  16182. result.push(nV4);
  16183. break;
  16184. }
  16185. if (v3Out) {
  16186. nV1 = vertices[index];
  16187. nV2 = vertices[index + 1];
  16188. nV3 = clipVertices(vertices[index + 2], nV1);
  16189. nV4 = clipVertices(vertices[index + 2], nV2);
  16190. }
  16191. result.push(nV1.clone());
  16192. result.push(nV2.clone());
  16193. result.push(nV3);
  16194. result.push(nV4);
  16195. result.push(nV3.clone());
  16196. result.push(nV2.clone());
  16197. break;
  16198. case 2:
  16199. if (!v1Out) {
  16200. nV1 = vertices[index].clone();
  16201. nV2 = clipVertices(nV1, vertices[index + 1]);
  16202. nV3 = clipVertices(nV1, vertices[index + 2]);
  16203. result.push(nV1);
  16204. result.push(nV2);
  16205. result.push(nV3);
  16206. }
  16207. if (!v2Out) {
  16208. nV1 = vertices[index + 1].clone();
  16209. nV2 = clipVertices(nV1, vertices[index + 2]);
  16210. nV3 = clipVertices(nV1, vertices[index]);
  16211. result.push(nV1);
  16212. result.push(nV2);
  16213. result.push(nV3);
  16214. }
  16215. if (!v3Out) {
  16216. nV1 = vertices[index + 2].clone();
  16217. nV2 = clipVertices(nV1, vertices[index]);
  16218. nV3 = clipVertices(nV1, vertices[index + 1]);
  16219. result.push(nV1);
  16220. result.push(nV2);
  16221. result.push(nV3);
  16222. }
  16223. break;
  16224. case 3:
  16225. break;
  16226. }
  16227. }
  16228. return result;
  16229. };
  16230. for (var index = 0; index < indices.length; index += 3) {
  16231. var faceVertices = new Array();
  16232. faceVertices.push(extractDecalVector3(index));
  16233. faceVertices.push(extractDecalVector3(index + 1));
  16234. faceVertices.push(extractDecalVector3(index + 2));
  16235. // Clip
  16236. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16237. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16238. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16239. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16240. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16241. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16242. if (faceVertices.length === 0) {
  16243. continue;
  16244. }
  16245. // Add UVs and get back to world
  16246. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16247. var vertex = faceVertices[vIndex];
  16248. vertexData.indices.push(currentVertexDataIndex);
  16249. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16250. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16251. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16252. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16253. currentVertexDataIndex++;
  16254. }
  16255. }
  16256. // Return mesh
  16257. var decal = new Mesh(name, sourceMesh.getScene());
  16258. vertexData.applyToMesh(decal);
  16259. decal.position = position.clone();
  16260. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16261. return decal;
  16262. };
  16263. // Skeletons
  16264. /**
  16265. * Update the vertex buffers by applying transformation from the bones
  16266. * @param {skeleton} skeleton to apply
  16267. */
  16268. Mesh.prototype.applySkeleton = function (skeleton) {
  16269. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16270. return this;
  16271. }
  16272. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16273. return this;
  16274. }
  16275. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16276. return this;
  16277. }
  16278. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16279. return this;
  16280. }
  16281. var source;
  16282. if (!this._sourcePositions) {
  16283. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16284. this._sourcePositions = new Float32Array(source);
  16285. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16286. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16287. }
  16288. }
  16289. if (!this._sourceNormals) {
  16290. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16291. this._sourceNormals = new Float32Array(source);
  16292. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16293. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16294. }
  16295. }
  16296. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16297. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16298. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16299. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16300. var skeletonMatrices = skeleton.getTransformMatrices();
  16301. var tempVector3 = BABYLON.Vector3.Zero();
  16302. var finalMatrix = new BABYLON.Matrix();
  16303. var tempMatrix = new BABYLON.Matrix();
  16304. for (var index = 0; index < positionsData.length; index += 3) {
  16305. var index4 = (index / 3) * 4;
  16306. var matricesWeight0 = matricesWeightsData[index4];
  16307. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16308. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16309. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16310. if (matricesWeight0 > 0) {
  16311. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16312. finalMatrix.addToSelf(tempMatrix);
  16313. }
  16314. if (matricesWeight1 > 0) {
  16315. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16316. finalMatrix.addToSelf(tempMatrix);
  16317. }
  16318. if (matricesWeight2 > 0) {
  16319. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16320. finalMatrix.addToSelf(tempMatrix);
  16321. }
  16322. if (matricesWeight3 > 0) {
  16323. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16324. finalMatrix.addToSelf(tempMatrix);
  16325. }
  16326. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16327. tempVector3.toArray(positionsData, index);
  16328. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16329. tempVector3.toArray(normalsData, index);
  16330. finalMatrix.reset();
  16331. }
  16332. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16333. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16334. return this;
  16335. };
  16336. // Tools
  16337. Mesh.MinMax = function (meshes) {
  16338. var minVector = null;
  16339. var maxVector = null;
  16340. for (var i in meshes) {
  16341. var mesh = meshes[i];
  16342. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16343. if (!minVector) {
  16344. minVector = boundingBox.minimumWorld;
  16345. maxVector = boundingBox.maximumWorld;
  16346. continue;
  16347. }
  16348. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16349. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16350. }
  16351. return {
  16352. min: minVector,
  16353. max: maxVector
  16354. };
  16355. };
  16356. Mesh.Center = function (meshesOrMinMaxVector) {
  16357. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16358. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16359. };
  16360. /**
  16361. * Merge the array of meshes into a single mesh for performance reasons.
  16362. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16363. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16364. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16365. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16366. */
  16367. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16368. if (disposeSource === void 0) { disposeSource = true; }
  16369. var index;
  16370. if (!allow32BitsIndices) {
  16371. var totalVertices = 0;
  16372. // Counting vertices
  16373. for (index = 0; index < meshes.length; index++) {
  16374. if (meshes[index]) {
  16375. totalVertices += meshes[index].getTotalVertices();
  16376. if (totalVertices > 65536) {
  16377. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16378. return null;
  16379. }
  16380. }
  16381. }
  16382. }
  16383. // Merge
  16384. var vertexData;
  16385. var otherVertexData;
  16386. var source;
  16387. for (index = 0; index < meshes.length; index++) {
  16388. if (meshes[index]) {
  16389. meshes[index].computeWorldMatrix(true);
  16390. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16391. otherVertexData.transform(meshes[index].getWorldMatrix());
  16392. if (vertexData) {
  16393. vertexData.merge(otherVertexData);
  16394. }
  16395. else {
  16396. vertexData = otherVertexData;
  16397. source = meshes[index];
  16398. }
  16399. }
  16400. }
  16401. if (!meshSubclass) {
  16402. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16403. }
  16404. vertexData.applyToMesh(meshSubclass);
  16405. // Setting properties
  16406. meshSubclass.material = source.material;
  16407. meshSubclass.checkCollisions = source.checkCollisions;
  16408. // Cleaning
  16409. if (disposeSource) {
  16410. for (index = 0; index < meshes.length; index++) {
  16411. if (meshes[index]) {
  16412. meshes[index].dispose();
  16413. }
  16414. }
  16415. }
  16416. return meshSubclass;
  16417. };
  16418. // Consts
  16419. Mesh._FRONTSIDE = 0;
  16420. Mesh._BACKSIDE = 1;
  16421. Mesh._DOUBLESIDE = 2;
  16422. Mesh._DEFAULTSIDE = 0;
  16423. Mesh._NO_CAP = 0;
  16424. Mesh._CAP_START = 1;
  16425. Mesh._CAP_END = 2;
  16426. Mesh._CAP_ALL = 3;
  16427. return Mesh;
  16428. })(BABYLON.AbstractMesh);
  16429. BABYLON.Mesh = Mesh;
  16430. })(BABYLON || (BABYLON = {}));
  16431. var BABYLON;
  16432. (function (BABYLON) {
  16433. var SubMesh = (function () {
  16434. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16435. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16436. this.materialIndex = materialIndex;
  16437. this.verticesStart = verticesStart;
  16438. this.verticesCount = verticesCount;
  16439. this.indexStart = indexStart;
  16440. this.indexCount = indexCount;
  16441. this._renderId = 0;
  16442. this._mesh = mesh;
  16443. this._renderingMesh = renderingMesh || mesh;
  16444. mesh.subMeshes.push(this);
  16445. this._trianglePlanes = [];
  16446. this._id = mesh.subMeshes.length - 1;
  16447. if (createBoundingBox) {
  16448. this.refreshBoundingInfo();
  16449. mesh.computeWorldMatrix(true);
  16450. }
  16451. }
  16452. SubMesh.prototype.getBoundingInfo = function () {
  16453. return this._boundingInfo;
  16454. };
  16455. SubMesh.prototype.getMesh = function () {
  16456. return this._mesh;
  16457. };
  16458. SubMesh.prototype.getRenderingMesh = function () {
  16459. return this._renderingMesh;
  16460. };
  16461. SubMesh.prototype.getMaterial = function () {
  16462. var rootMaterial = this._renderingMesh.material;
  16463. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16464. var multiMaterial = rootMaterial;
  16465. return multiMaterial.getSubMaterial(this.materialIndex);
  16466. }
  16467. if (!rootMaterial) {
  16468. return this._mesh.getScene().defaultMaterial;
  16469. }
  16470. return rootMaterial;
  16471. };
  16472. // Methods
  16473. SubMesh.prototype.refreshBoundingInfo = function () {
  16474. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16475. if (!data) {
  16476. this._boundingInfo = this._mesh._boundingInfo;
  16477. return;
  16478. }
  16479. var indices = this._renderingMesh.getIndices();
  16480. var extend;
  16481. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16482. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16483. }
  16484. else {
  16485. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16486. }
  16487. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16488. };
  16489. SubMesh.prototype._checkCollision = function (collider) {
  16490. return this._boundingInfo._checkCollision(collider);
  16491. };
  16492. SubMesh.prototype.updateBoundingInfo = function (world) {
  16493. if (!this._boundingInfo) {
  16494. this.refreshBoundingInfo();
  16495. }
  16496. this._boundingInfo._update(world);
  16497. };
  16498. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16499. return this._boundingInfo.isInFrustum(frustumPlanes);
  16500. };
  16501. SubMesh.prototype.render = function (enableAlphaMode) {
  16502. this._renderingMesh.render(this, enableAlphaMode);
  16503. };
  16504. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16505. if (!this._linesIndexBuffer) {
  16506. var linesIndices = [];
  16507. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16508. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16509. }
  16510. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16511. this.linesIndexCount = linesIndices.length;
  16512. }
  16513. return this._linesIndexBuffer;
  16514. };
  16515. SubMesh.prototype.canIntersects = function (ray) {
  16516. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16517. };
  16518. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16519. var intersectInfo = null;
  16520. // Triangles test
  16521. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16522. var p0 = positions[indices[index]];
  16523. var p1 = positions[indices[index + 1]];
  16524. var p2 = positions[indices[index + 2]];
  16525. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16526. if (currentIntersectInfo) {
  16527. if (currentIntersectInfo.distance < 0) {
  16528. continue;
  16529. }
  16530. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16531. intersectInfo = currentIntersectInfo;
  16532. intersectInfo.faceId = index / 3;
  16533. if (fastCheck) {
  16534. break;
  16535. }
  16536. }
  16537. }
  16538. }
  16539. return intersectInfo;
  16540. };
  16541. // Clone
  16542. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16543. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16544. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16545. return result;
  16546. };
  16547. // Dispose
  16548. SubMesh.prototype.dispose = function () {
  16549. if (this._linesIndexBuffer) {
  16550. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16551. this._linesIndexBuffer = null;
  16552. }
  16553. // Remove from mesh
  16554. var index = this._mesh.subMeshes.indexOf(this);
  16555. this._mesh.subMeshes.splice(index, 1);
  16556. };
  16557. // Statics
  16558. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16559. var minVertexIndex = Number.MAX_VALUE;
  16560. var maxVertexIndex = -Number.MAX_VALUE;
  16561. renderingMesh = renderingMesh || mesh;
  16562. var indices = renderingMesh.getIndices();
  16563. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16564. var vertexIndex = indices[index];
  16565. if (vertexIndex < minVertexIndex)
  16566. minVertexIndex = vertexIndex;
  16567. if (vertexIndex > maxVertexIndex)
  16568. maxVertexIndex = vertexIndex;
  16569. }
  16570. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16571. };
  16572. return SubMesh;
  16573. })();
  16574. BABYLON.SubMesh = SubMesh;
  16575. })(BABYLON || (BABYLON = {}));
  16576. var BABYLON;
  16577. (function (BABYLON) {
  16578. var BaseTexture = (function () {
  16579. function BaseTexture(scene) {
  16580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16581. this.hasAlpha = false;
  16582. this.getAlphaFromRGB = false;
  16583. this.level = 1;
  16584. this.isCube = false;
  16585. this.isRenderTarget = false;
  16586. this.animations = new Array();
  16587. this.coordinatesIndex = 0;
  16588. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16589. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16590. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16591. this.anisotropicFilteringLevel = 4;
  16592. this._scene = scene;
  16593. this._scene.textures.push(this);
  16594. }
  16595. BaseTexture.prototype.getScene = function () {
  16596. return this._scene;
  16597. };
  16598. BaseTexture.prototype.getTextureMatrix = function () {
  16599. return null;
  16600. };
  16601. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16602. return null;
  16603. };
  16604. BaseTexture.prototype.getInternalTexture = function () {
  16605. return this._texture;
  16606. };
  16607. BaseTexture.prototype.isReady = function () {
  16608. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16609. return true;
  16610. }
  16611. if (this._texture) {
  16612. return this._texture.isReady;
  16613. }
  16614. return false;
  16615. };
  16616. BaseTexture.prototype.getSize = function () {
  16617. if (this._texture._width) {
  16618. return { width: this._texture._width, height: this._texture._height };
  16619. }
  16620. if (this._texture._size) {
  16621. return { width: this._texture._size, height: this._texture._size };
  16622. }
  16623. return { width: 0, height: 0 };
  16624. };
  16625. BaseTexture.prototype.getBaseSize = function () {
  16626. if (!this.isReady())
  16627. return { width: 0, height: 0 };
  16628. if (this._texture._size) {
  16629. return { width: this._texture._size, height: this._texture._size };
  16630. }
  16631. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16632. };
  16633. BaseTexture.prototype.scale = function (ratio) {
  16634. };
  16635. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16636. get: function () {
  16637. return false;
  16638. },
  16639. enumerable: true,
  16640. configurable: true
  16641. });
  16642. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16643. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16644. for (var index = 0; index < texturesCache.length; index++) {
  16645. var texturesCacheEntry = texturesCache[index];
  16646. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16647. texturesCache.splice(index, 1);
  16648. return;
  16649. }
  16650. }
  16651. };
  16652. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16653. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16654. for (var index = 0; index < texturesCache.length; index++) {
  16655. var texturesCacheEntry = texturesCache[index];
  16656. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16657. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16658. texturesCacheEntry.references++;
  16659. return texturesCacheEntry;
  16660. }
  16661. }
  16662. }
  16663. return null;
  16664. };
  16665. BaseTexture.prototype.delayLoad = function () {
  16666. };
  16667. BaseTexture.prototype.releaseInternalTexture = function () {
  16668. if (!this._texture) {
  16669. return;
  16670. }
  16671. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16672. this._texture.references--;
  16673. // Final reference ?
  16674. if (this._texture.references === 0) {
  16675. var index = texturesCache.indexOf(this._texture);
  16676. texturesCache.splice(index, 1);
  16677. this._scene.getEngine()._releaseTexture(this._texture);
  16678. delete this._texture;
  16679. }
  16680. };
  16681. BaseTexture.prototype.clone = function () {
  16682. return null;
  16683. };
  16684. BaseTexture.prototype.dispose = function () {
  16685. // Remove from scene
  16686. var index = this._scene.textures.indexOf(this);
  16687. if (index >= 0) {
  16688. this._scene.textures.splice(index, 1);
  16689. }
  16690. if (this._texture === undefined) {
  16691. return;
  16692. }
  16693. this.releaseInternalTexture();
  16694. // Callback
  16695. if (this.onDispose) {
  16696. this.onDispose();
  16697. }
  16698. };
  16699. return BaseTexture;
  16700. })();
  16701. BABYLON.BaseTexture = BaseTexture;
  16702. })(BABYLON || (BABYLON = {}));
  16703. var BABYLON;
  16704. (function (BABYLON) {
  16705. var Texture = (function (_super) {
  16706. __extends(Texture, _super);
  16707. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16708. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16709. if (onLoad === void 0) { onLoad = null; }
  16710. if (onError === void 0) { onError = null; }
  16711. if (buffer === void 0) { buffer = null; }
  16712. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16713. _super.call(this, scene);
  16714. this.uOffset = 0;
  16715. this.vOffset = 0;
  16716. this.uScale = 1.0;
  16717. this.vScale = 1.0;
  16718. this.uAng = 0;
  16719. this.vAng = 0;
  16720. this.wAng = 0;
  16721. this.name = url;
  16722. this.url = url;
  16723. this._noMipmap = noMipmap;
  16724. this._invertY = invertY;
  16725. this._samplingMode = samplingMode;
  16726. this._buffer = buffer;
  16727. this._deleteBuffer = deleteBuffer;
  16728. if (!url) {
  16729. return;
  16730. }
  16731. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16732. if (!this._texture) {
  16733. if (!scene.useDelayedTextureLoading) {
  16734. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16735. if (deleteBuffer) {
  16736. delete this._buffer;
  16737. }
  16738. }
  16739. else {
  16740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16741. }
  16742. }
  16743. else {
  16744. BABYLON.Tools.SetImmediate(function () {
  16745. if (onLoad) {
  16746. onLoad();
  16747. }
  16748. });
  16749. }
  16750. }
  16751. Texture.prototype.delayLoad = function () {
  16752. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16753. return;
  16754. }
  16755. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16756. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16757. if (!this._texture) {
  16758. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16759. if (this._deleteBuffer) {
  16760. delete this._buffer;
  16761. }
  16762. }
  16763. };
  16764. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16765. if (!this._texture) {
  16766. return;
  16767. }
  16768. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16769. };
  16770. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16771. x *= this.uScale;
  16772. y *= this.vScale;
  16773. x -= 0.5 * this.uScale;
  16774. y -= 0.5 * this.vScale;
  16775. z -= 0.5;
  16776. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16777. t.x += 0.5 * this.uScale + this.uOffset;
  16778. t.y += 0.5 * this.vScale + this.vOffset;
  16779. t.z += 0.5;
  16780. };
  16781. Texture.prototype.getTextureMatrix = function () {
  16782. if (this.uOffset === this._cachedUOffset &&
  16783. this.vOffset === this._cachedVOffset &&
  16784. this.uScale === this._cachedUScale &&
  16785. this.vScale === this._cachedVScale &&
  16786. this.uAng === this._cachedUAng &&
  16787. this.vAng === this._cachedVAng &&
  16788. this.wAng === this._cachedWAng) {
  16789. return this._cachedTextureMatrix;
  16790. }
  16791. this._cachedUOffset = this.uOffset;
  16792. this._cachedVOffset = this.vOffset;
  16793. this._cachedUScale = this.uScale;
  16794. this._cachedVScale = this.vScale;
  16795. this._cachedUAng = this.uAng;
  16796. this._cachedVAng = this.vAng;
  16797. this._cachedWAng = this.wAng;
  16798. if (!this._cachedTextureMatrix) {
  16799. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16800. this._rowGenerationMatrix = new BABYLON.Matrix();
  16801. this._t0 = BABYLON.Vector3.Zero();
  16802. this._t1 = BABYLON.Vector3.Zero();
  16803. this._t2 = BABYLON.Vector3.Zero();
  16804. }
  16805. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16806. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16807. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16808. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16809. this._t1.subtractInPlace(this._t0);
  16810. this._t2.subtractInPlace(this._t0);
  16811. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16812. this._cachedTextureMatrix.m[0] = this._t1.x;
  16813. this._cachedTextureMatrix.m[1] = this._t1.y;
  16814. this._cachedTextureMatrix.m[2] = this._t1.z;
  16815. this._cachedTextureMatrix.m[4] = this._t2.x;
  16816. this._cachedTextureMatrix.m[5] = this._t2.y;
  16817. this._cachedTextureMatrix.m[6] = this._t2.z;
  16818. this._cachedTextureMatrix.m[8] = this._t0.x;
  16819. this._cachedTextureMatrix.m[9] = this._t0.y;
  16820. this._cachedTextureMatrix.m[10] = this._t0.z;
  16821. return this._cachedTextureMatrix;
  16822. };
  16823. Texture.prototype.getReflectionTextureMatrix = function () {
  16824. if (this.uOffset === this._cachedUOffset &&
  16825. this.vOffset === this._cachedVOffset &&
  16826. this.uScale === this._cachedUScale &&
  16827. this.vScale === this._cachedVScale &&
  16828. this.coordinatesMode === this._cachedCoordinatesMode) {
  16829. return this._cachedTextureMatrix;
  16830. }
  16831. if (!this._cachedTextureMatrix) {
  16832. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16833. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16834. }
  16835. this._cachedCoordinatesMode = this.coordinatesMode;
  16836. switch (this.coordinatesMode) {
  16837. case Texture.SPHERICAL_MODE:
  16838. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16839. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16840. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16841. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16842. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16843. break;
  16844. case Texture.PLANAR_MODE:
  16845. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16846. this._cachedTextureMatrix[0] = this.uScale;
  16847. this._cachedTextureMatrix[5] = this.vScale;
  16848. this._cachedTextureMatrix[12] = this.uOffset;
  16849. this._cachedTextureMatrix[13] = this.vOffset;
  16850. break;
  16851. case Texture.PROJECTION_MODE:
  16852. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16853. this._projectionModeMatrix.m[0] = 0.5;
  16854. this._projectionModeMatrix.m[5] = -0.5;
  16855. this._projectionModeMatrix.m[10] = 0.0;
  16856. this._projectionModeMatrix.m[12] = 0.5;
  16857. this._projectionModeMatrix.m[13] = 0.5;
  16858. this._projectionModeMatrix.m[14] = 1.0;
  16859. this._projectionModeMatrix.m[15] = 1.0;
  16860. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16861. break;
  16862. default:
  16863. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16864. break;
  16865. }
  16866. return this._cachedTextureMatrix;
  16867. };
  16868. Texture.prototype.clone = function () {
  16869. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16870. // Base texture
  16871. newTexture.hasAlpha = this.hasAlpha;
  16872. newTexture.level = this.level;
  16873. newTexture.wrapU = this.wrapU;
  16874. newTexture.wrapV = this.wrapV;
  16875. newTexture.coordinatesIndex = this.coordinatesIndex;
  16876. newTexture.coordinatesMode = this.coordinatesMode;
  16877. // Texture
  16878. newTexture.uOffset = this.uOffset;
  16879. newTexture.vOffset = this.vOffset;
  16880. newTexture.uScale = this.uScale;
  16881. newTexture.vScale = this.vScale;
  16882. newTexture.uAng = this.uAng;
  16883. newTexture.vAng = this.vAng;
  16884. newTexture.wAng = this.wAng;
  16885. return newTexture;
  16886. };
  16887. // Statics
  16888. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16889. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16890. if (onLoad === void 0) { onLoad = null; }
  16891. if (onError === void 0) { onError = null; }
  16892. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16893. };
  16894. // Constants
  16895. Texture.NEAREST_SAMPLINGMODE = 1;
  16896. Texture.BILINEAR_SAMPLINGMODE = 2;
  16897. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16898. Texture.EXPLICIT_MODE = 0;
  16899. Texture.SPHERICAL_MODE = 1;
  16900. Texture.PLANAR_MODE = 2;
  16901. Texture.CUBIC_MODE = 3;
  16902. Texture.PROJECTION_MODE = 4;
  16903. Texture.SKYBOX_MODE = 5;
  16904. Texture.CLAMP_ADDRESSMODE = 0;
  16905. Texture.WRAP_ADDRESSMODE = 1;
  16906. Texture.MIRROR_ADDRESSMODE = 2;
  16907. return Texture;
  16908. })(BABYLON.BaseTexture);
  16909. BABYLON.Texture = Texture;
  16910. })(BABYLON || (BABYLON = {}));
  16911. var BABYLON;
  16912. (function (BABYLON) {
  16913. var CubeTexture = (function (_super) {
  16914. __extends(CubeTexture, _super);
  16915. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16916. _super.call(this, scene);
  16917. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16918. this.name = rootUrl;
  16919. this.url = rootUrl;
  16920. this._noMipmap = noMipmap;
  16921. this.hasAlpha = false;
  16922. this._texture = this._getFromCache(rootUrl, noMipmap);
  16923. if (!extensions) {
  16924. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16925. }
  16926. this._extensions = extensions;
  16927. if (!this._texture) {
  16928. if (!scene.useDelayedTextureLoading) {
  16929. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16930. }
  16931. else {
  16932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16933. }
  16934. }
  16935. this.isCube = true;
  16936. this._textureMatrix = BABYLON.Matrix.Identity();
  16937. }
  16938. CubeTexture.prototype.clone = function () {
  16939. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16940. // Base texture
  16941. newTexture.level = this.level;
  16942. newTexture.wrapU = this.wrapU;
  16943. newTexture.wrapV = this.wrapV;
  16944. newTexture.coordinatesIndex = this.coordinatesIndex;
  16945. newTexture.coordinatesMode = this.coordinatesMode;
  16946. return newTexture;
  16947. };
  16948. // Methods
  16949. CubeTexture.prototype.delayLoad = function () {
  16950. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16951. return;
  16952. }
  16953. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16954. this._texture = this._getFromCache(this.url, this._noMipmap);
  16955. if (!this._texture) {
  16956. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16957. }
  16958. };
  16959. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16960. return this._textureMatrix;
  16961. };
  16962. return CubeTexture;
  16963. })(BABYLON.BaseTexture);
  16964. BABYLON.CubeTexture = CubeTexture;
  16965. })(BABYLON || (BABYLON = {}));
  16966. var BABYLON;
  16967. (function (BABYLON) {
  16968. var RenderTargetTexture = (function (_super) {
  16969. __extends(RenderTargetTexture, _super);
  16970. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16971. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16972. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16973. _super.call(this, null, scene, !generateMipMaps);
  16974. this.renderList = new Array();
  16975. this.renderParticles = true;
  16976. this.renderSprites = false;
  16977. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16978. this._currentRefreshId = -1;
  16979. this._refreshRate = 1;
  16980. this.name = name;
  16981. this.isRenderTarget = true;
  16982. this._size = size;
  16983. this._generateMipMaps = generateMipMaps;
  16984. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16985. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16986. // Rendering groups
  16987. this._renderingManager = new BABYLON.RenderingManager(scene);
  16988. }
  16989. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16990. this._currentRefreshId = -1;
  16991. };
  16992. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16993. get: function () {
  16994. return this._refreshRate;
  16995. },
  16996. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16997. set: function (value) {
  16998. this._refreshRate = value;
  16999. this.resetRefreshCounter();
  17000. },
  17001. enumerable: true,
  17002. configurable: true
  17003. });
  17004. RenderTargetTexture.prototype._shouldRender = function () {
  17005. if (this._currentRefreshId === -1) {
  17006. this._currentRefreshId = 1;
  17007. return true;
  17008. }
  17009. if (this.refreshRate === this._currentRefreshId) {
  17010. this._currentRefreshId = 1;
  17011. return true;
  17012. }
  17013. this._currentRefreshId++;
  17014. return false;
  17015. };
  17016. RenderTargetTexture.prototype.isReady = function () {
  17017. if (!this.getScene().renderTargetsEnabled) {
  17018. return false;
  17019. }
  17020. return _super.prototype.isReady.call(this);
  17021. };
  17022. RenderTargetTexture.prototype.getRenderSize = function () {
  17023. return this._size;
  17024. };
  17025. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17026. get: function () {
  17027. return true;
  17028. },
  17029. enumerable: true,
  17030. configurable: true
  17031. });
  17032. RenderTargetTexture.prototype.scale = function (ratio) {
  17033. var newSize = this._size * ratio;
  17034. this.resize(newSize, this._generateMipMaps);
  17035. };
  17036. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17037. this.releaseInternalTexture();
  17038. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17039. };
  17040. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17041. var scene = this.getScene();
  17042. var engine = scene.getEngine();
  17043. if (this._waitingRenderList) {
  17044. this.renderList = [];
  17045. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17046. var id = this._waitingRenderList[index];
  17047. this.renderList.push(scene.getMeshByID(id));
  17048. }
  17049. delete this._waitingRenderList;
  17050. }
  17051. if (this.renderList && this.renderList.length === 0) {
  17052. return;
  17053. }
  17054. // Bind
  17055. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17056. engine.bindFramebuffer(this._texture);
  17057. }
  17058. this._renderingManager.reset();
  17059. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17060. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17061. var mesh = currentRenderList[meshIndex];
  17062. if (mesh) {
  17063. if (!mesh.isReady()) {
  17064. // Reset _currentRefreshId
  17065. this.resetRefreshCounter();
  17066. continue;
  17067. }
  17068. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17069. mesh._activate(scene.getRenderId());
  17070. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17071. var subMesh = mesh.subMeshes[subIndex];
  17072. scene._activeIndices += subMesh.indexCount;
  17073. this._renderingManager.dispatch(subMesh);
  17074. }
  17075. }
  17076. }
  17077. }
  17078. if (this.onBeforeRender) {
  17079. this.onBeforeRender();
  17080. }
  17081. // Clear
  17082. if (this.onClear) {
  17083. this.onClear(engine);
  17084. }
  17085. else {
  17086. engine.clear(scene.clearColor, true, true);
  17087. }
  17088. if (!this._doNotChangeAspectRatio) {
  17089. scene.updateTransformMatrix(true);
  17090. }
  17091. // Render
  17092. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17093. if (useCameraPostProcess) {
  17094. scene.postProcessManager._finalizeFrame(false, this._texture);
  17095. }
  17096. if (!this._doNotChangeAspectRatio) {
  17097. scene.updateTransformMatrix(true);
  17098. }
  17099. if (this.onAfterRender) {
  17100. this.onAfterRender();
  17101. }
  17102. // Dump ?
  17103. if (dumpForDebug) {
  17104. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17105. }
  17106. // Unbind
  17107. engine.unBindFramebuffer(this._texture);
  17108. if (this.onAfterUnbind) {
  17109. this.onAfterUnbind();
  17110. }
  17111. };
  17112. RenderTargetTexture.prototype.clone = function () {
  17113. var textureSize = this.getSize();
  17114. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17115. // Base texture
  17116. newTexture.hasAlpha = this.hasAlpha;
  17117. newTexture.level = this.level;
  17118. // RenderTarget Texture
  17119. newTexture.coordinatesMode = this.coordinatesMode;
  17120. newTexture.renderList = this.renderList.slice(0);
  17121. return newTexture;
  17122. };
  17123. return RenderTargetTexture;
  17124. })(BABYLON.Texture);
  17125. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17126. })(BABYLON || (BABYLON = {}));
  17127. var BABYLON;
  17128. (function (BABYLON) {
  17129. var ProceduralTexture = (function (_super) {
  17130. __extends(ProceduralTexture, _super);
  17131. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17132. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17133. _super.call(this, null, scene, !generateMipMaps);
  17134. this.isEnabled = true;
  17135. this._currentRefreshId = -1;
  17136. this._refreshRate = 1;
  17137. this._vertexDeclaration = [2];
  17138. this._vertexStrideSize = 2 * 4;
  17139. this._uniforms = new Array();
  17140. this._samplers = new Array();
  17141. this._textures = new Array();
  17142. this._floats = new Array();
  17143. this._floatsArrays = {};
  17144. this._colors3 = new Array();
  17145. this._colors4 = new Array();
  17146. this._vectors2 = new Array();
  17147. this._vectors3 = new Array();
  17148. this._matrices = new Array();
  17149. this._fallbackTextureUsed = false;
  17150. scene._proceduralTextures.push(this);
  17151. this.name = name;
  17152. this.isRenderTarget = true;
  17153. this._size = size;
  17154. this._generateMipMaps = generateMipMaps;
  17155. this.setFragment(fragment);
  17156. this._fallbackTexture = fallbackTexture;
  17157. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17158. // VBO
  17159. var vertices = [];
  17160. vertices.push(1, 1);
  17161. vertices.push(-1, 1);
  17162. vertices.push(-1, -1);
  17163. vertices.push(1, -1);
  17164. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17165. // Indices
  17166. var indices = [];
  17167. indices.push(0);
  17168. indices.push(1);
  17169. indices.push(2);
  17170. indices.push(0);
  17171. indices.push(2);
  17172. indices.push(3);
  17173. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17174. }
  17175. ProceduralTexture.prototype.reset = function () {
  17176. if (this._effect === undefined) {
  17177. return;
  17178. }
  17179. var engine = this.getScene().getEngine();
  17180. engine._releaseEffect(this._effect);
  17181. };
  17182. ProceduralTexture.prototype.isReady = function () {
  17183. var _this = this;
  17184. var engine = this.getScene().getEngine();
  17185. var shaders;
  17186. if (!this._fragment) {
  17187. return false;
  17188. }
  17189. if (this._fallbackTextureUsed) {
  17190. return true;
  17191. }
  17192. if (this._fragment.fragmentElement !== undefined) {
  17193. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17194. }
  17195. else {
  17196. shaders = { vertex: "procedural", fragment: this._fragment };
  17197. }
  17198. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17199. _this.releaseInternalTexture();
  17200. if (_this._fallbackTexture) {
  17201. _this._texture = _this._fallbackTexture._texture;
  17202. _this._texture.references++;
  17203. }
  17204. _this._fallbackTextureUsed = true;
  17205. });
  17206. return this._effect.isReady();
  17207. };
  17208. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17209. this._currentRefreshId = -1;
  17210. };
  17211. ProceduralTexture.prototype.setFragment = function (fragment) {
  17212. this._fragment = fragment;
  17213. };
  17214. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17215. get: function () {
  17216. return this._refreshRate;
  17217. },
  17218. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17219. set: function (value) {
  17220. this._refreshRate = value;
  17221. this.resetRefreshCounter();
  17222. },
  17223. enumerable: true,
  17224. configurable: true
  17225. });
  17226. ProceduralTexture.prototype._shouldRender = function () {
  17227. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17228. return false;
  17229. }
  17230. if (this._fallbackTextureUsed) {
  17231. return false;
  17232. }
  17233. if (this._currentRefreshId === -1) {
  17234. this._currentRefreshId = 1;
  17235. return true;
  17236. }
  17237. if (this.refreshRate === this._currentRefreshId) {
  17238. this._currentRefreshId = 1;
  17239. return true;
  17240. }
  17241. this._currentRefreshId++;
  17242. return false;
  17243. };
  17244. ProceduralTexture.prototype.getRenderSize = function () {
  17245. return this._size;
  17246. };
  17247. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17248. if (this._fallbackTextureUsed) {
  17249. return;
  17250. }
  17251. this.releaseInternalTexture();
  17252. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17253. };
  17254. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17255. if (this._uniforms.indexOf(uniformName) === -1) {
  17256. this._uniforms.push(uniformName);
  17257. }
  17258. };
  17259. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17260. if (this._samplers.indexOf(name) === -1) {
  17261. this._samplers.push(name);
  17262. }
  17263. this._textures[name] = texture;
  17264. return this;
  17265. };
  17266. ProceduralTexture.prototype.setFloat = function (name, value) {
  17267. this._checkUniform(name);
  17268. this._floats[name] = value;
  17269. return this;
  17270. };
  17271. ProceduralTexture.prototype.setFloats = function (name, value) {
  17272. this._checkUniform(name);
  17273. this._floatsArrays[name] = value;
  17274. return this;
  17275. };
  17276. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17277. this._checkUniform(name);
  17278. this._colors3[name] = value;
  17279. return this;
  17280. };
  17281. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17282. this._checkUniform(name);
  17283. this._colors4[name] = value;
  17284. return this;
  17285. };
  17286. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17287. this._checkUniform(name);
  17288. this._vectors2[name] = value;
  17289. return this;
  17290. };
  17291. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17292. this._checkUniform(name);
  17293. this._vectors3[name] = value;
  17294. return this;
  17295. };
  17296. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17297. this._checkUniform(name);
  17298. this._matrices[name] = value;
  17299. return this;
  17300. };
  17301. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17302. var scene = this.getScene();
  17303. var engine = scene.getEngine();
  17304. engine.bindFramebuffer(this._texture);
  17305. // Clear
  17306. engine.clear(scene.clearColor, true, true);
  17307. // Render
  17308. engine.enableEffect(this._effect);
  17309. engine.setState(false);
  17310. // Texture
  17311. for (var name in this._textures) {
  17312. this._effect.setTexture(name, this._textures[name]);
  17313. }
  17314. // Float
  17315. for (name in this._floats) {
  17316. this._effect.setFloat(name, this._floats[name]);
  17317. }
  17318. // Floats
  17319. for (name in this._floatsArrays) {
  17320. this._effect.setArray(name, this._floatsArrays[name]);
  17321. }
  17322. // Color3
  17323. for (name in this._colors3) {
  17324. this._effect.setColor3(name, this._colors3[name]);
  17325. }
  17326. // Color4
  17327. for (name in this._colors4) {
  17328. var color = this._colors4[name];
  17329. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17330. }
  17331. // Vector2
  17332. for (name in this._vectors2) {
  17333. this._effect.setVector2(name, this._vectors2[name]);
  17334. }
  17335. // Vector3
  17336. for (name in this._vectors3) {
  17337. this._effect.setVector3(name, this._vectors3[name]);
  17338. }
  17339. // Matrix
  17340. for (name in this._matrices) {
  17341. this._effect.setMatrix(name, this._matrices[name]);
  17342. }
  17343. // VBOs
  17344. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17345. // Draw order
  17346. engine.draw(true, 0, 6);
  17347. // Unbind
  17348. engine.unBindFramebuffer(this._texture);
  17349. };
  17350. ProceduralTexture.prototype.clone = function () {
  17351. var textureSize = this.getSize();
  17352. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17353. // Base texture
  17354. newTexture.hasAlpha = this.hasAlpha;
  17355. newTexture.level = this.level;
  17356. // RenderTarget Texture
  17357. newTexture.coordinatesMode = this.coordinatesMode;
  17358. return newTexture;
  17359. };
  17360. ProceduralTexture.prototype.dispose = function () {
  17361. var index = this.getScene()._proceduralTextures.indexOf(this);
  17362. if (index >= 0) {
  17363. this.getScene()._proceduralTextures.splice(index, 1);
  17364. }
  17365. _super.prototype.dispose.call(this);
  17366. };
  17367. return ProceduralTexture;
  17368. })(BABYLON.Texture);
  17369. BABYLON.ProceduralTexture = ProceduralTexture;
  17370. })(BABYLON || (BABYLON = {}));
  17371. var BABYLON;
  17372. (function (BABYLON) {
  17373. var MirrorTexture = (function (_super) {
  17374. __extends(MirrorTexture, _super);
  17375. function MirrorTexture(name, size, scene, generateMipMaps) {
  17376. var _this = this;
  17377. _super.call(this, name, size, scene, generateMipMaps, true);
  17378. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17379. this._transformMatrix = BABYLON.Matrix.Zero();
  17380. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17381. this.onBeforeRender = function () {
  17382. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17383. _this._savedViewMatrix = scene.getViewMatrix();
  17384. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17385. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17386. scene.clipPlane = _this.mirrorPlane;
  17387. scene.getEngine().cullBackFaces = false;
  17388. };
  17389. this.onAfterRender = function () {
  17390. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17391. scene.getEngine().cullBackFaces = true;
  17392. delete scene.clipPlane;
  17393. };
  17394. }
  17395. MirrorTexture.prototype.clone = function () {
  17396. var textureSize = this.getSize();
  17397. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17398. // Base texture
  17399. newTexture.hasAlpha = this.hasAlpha;
  17400. newTexture.level = this.level;
  17401. // Mirror Texture
  17402. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17403. newTexture.renderList = this.renderList.slice(0);
  17404. return newTexture;
  17405. };
  17406. return MirrorTexture;
  17407. })(BABYLON.RenderTargetTexture);
  17408. BABYLON.MirrorTexture = MirrorTexture;
  17409. })(BABYLON || (BABYLON = {}));
  17410. var BABYLON;
  17411. (function (BABYLON) {
  17412. var DynamicTexture = (function (_super) {
  17413. __extends(DynamicTexture, _super);
  17414. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17415. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17416. _super.call(this, null, scene, !generateMipMaps);
  17417. this.name = name;
  17418. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17419. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17420. this._generateMipMaps = generateMipMaps;
  17421. if (options.getContext) {
  17422. this._canvas = options;
  17423. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17424. }
  17425. else {
  17426. this._canvas = document.createElement("canvas");
  17427. if (options.width) {
  17428. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17429. }
  17430. else {
  17431. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17432. }
  17433. }
  17434. var textureSize = this.getSize();
  17435. this._canvas.width = textureSize.width;
  17436. this._canvas.height = textureSize.height;
  17437. this._context = this._canvas.getContext("2d");
  17438. }
  17439. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17440. get: function () {
  17441. return true;
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. DynamicTexture.prototype.scale = function (ratio) {
  17447. var textureSize = this.getSize();
  17448. textureSize.width *= ratio;
  17449. textureSize.height *= ratio;
  17450. this._canvas.width = textureSize.width;
  17451. this._canvas.height = textureSize.height;
  17452. this.releaseInternalTexture();
  17453. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17454. };
  17455. DynamicTexture.prototype.getContext = function () {
  17456. return this._context;
  17457. };
  17458. DynamicTexture.prototype.clear = function () {
  17459. var size = this.getSize();
  17460. this._context.fillRect(0, 0, size.width, size.height);
  17461. };
  17462. DynamicTexture.prototype.update = function (invertY) {
  17463. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17464. };
  17465. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17466. if (update === void 0) { update = true; }
  17467. var size = this.getSize();
  17468. if (clearColor) {
  17469. this._context.fillStyle = clearColor;
  17470. this._context.fillRect(0, 0, size.width, size.height);
  17471. }
  17472. this._context.font = font;
  17473. if (x === null) {
  17474. var textSize = this._context.measureText(text);
  17475. x = (size.width - textSize.width) / 2;
  17476. }
  17477. this._context.fillStyle = color;
  17478. this._context.fillText(text, x, y);
  17479. if (update) {
  17480. this.update(invertY);
  17481. }
  17482. };
  17483. DynamicTexture.prototype.clone = function () {
  17484. var textureSize = this.getSize();
  17485. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17486. // Base texture
  17487. newTexture.hasAlpha = this.hasAlpha;
  17488. newTexture.level = this.level;
  17489. // Dynamic Texture
  17490. newTexture.wrapU = this.wrapU;
  17491. newTexture.wrapV = this.wrapV;
  17492. return newTexture;
  17493. };
  17494. return DynamicTexture;
  17495. })(BABYLON.Texture);
  17496. BABYLON.DynamicTexture = DynamicTexture;
  17497. })(BABYLON || (BABYLON = {}));
  17498. var BABYLON;
  17499. (function (BABYLON) {
  17500. var VideoTexture = (function (_super) {
  17501. __extends(VideoTexture, _super);
  17502. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17503. var _this = this;
  17504. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17505. if (invertY === void 0) { invertY = false; }
  17506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17507. _super.call(this, null, scene, !generateMipMaps, invertY);
  17508. this._autoLaunch = true;
  17509. this.name = name;
  17510. this.video = document.createElement("video");
  17511. this.video.autoplay = false;
  17512. this.video.loop = true;
  17513. this.video.addEventListener("canplaythrough", function () {
  17514. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17515. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17516. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17517. }
  17518. else {
  17519. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17520. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17521. generateMipMaps = false;
  17522. }
  17523. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17524. _this._texture.isReady = true;
  17525. });
  17526. urls.forEach(function (url) {
  17527. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17528. var source = document.createElement("source");
  17529. source.src = url;
  17530. _this.video.appendChild(source);
  17531. });
  17532. this._lastUpdate = BABYLON.Tools.Now;
  17533. }
  17534. VideoTexture.prototype.update = function () {
  17535. if (this._autoLaunch) {
  17536. this._autoLaunch = false;
  17537. this.video.play();
  17538. }
  17539. var now = BABYLON.Tools.Now;
  17540. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17541. return false;
  17542. }
  17543. this._lastUpdate = now;
  17544. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17545. return true;
  17546. };
  17547. return VideoTexture;
  17548. })(BABYLON.Texture);
  17549. BABYLON.VideoTexture = VideoTexture;
  17550. })(BABYLON || (BABYLON = {}));
  17551. var BABYLON;
  17552. (function (BABYLON) {
  17553. var CustomProceduralTexture = (function (_super) {
  17554. __extends(CustomProceduralTexture, _super);
  17555. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17556. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17557. this._animate = true;
  17558. this._time = 0;
  17559. this._texturePath = texturePath;
  17560. //Try to load json
  17561. this.loadJson(texturePath);
  17562. this.refreshRate = 1;
  17563. }
  17564. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17565. var _this = this;
  17566. var that = this;
  17567. function noConfigFile() {
  17568. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17569. try {
  17570. that.setFragment(that._texturePath);
  17571. }
  17572. catch (ex) {
  17573. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17574. }
  17575. }
  17576. var configFileUrl = jsonUrl + "/config.json";
  17577. var xhr = new XMLHttpRequest();
  17578. xhr.open("GET", configFileUrl, true);
  17579. xhr.addEventListener("load", function () {
  17580. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17581. try {
  17582. _this._config = JSON.parse(xhr.response);
  17583. _this.updateShaderUniforms();
  17584. _this.updateTextures();
  17585. _this.setFragment(_this._texturePath + "/custom");
  17586. _this._animate = _this._config.animate;
  17587. _this.refreshRate = _this._config.refreshrate;
  17588. }
  17589. catch (ex) {
  17590. noConfigFile();
  17591. }
  17592. }
  17593. else {
  17594. noConfigFile();
  17595. }
  17596. }, false);
  17597. xhr.addEventListener("error", function () {
  17598. noConfigFile();
  17599. }, false);
  17600. try {
  17601. xhr.send();
  17602. }
  17603. catch (ex) {
  17604. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17605. }
  17606. };
  17607. CustomProceduralTexture.prototype.isReady = function () {
  17608. if (!_super.prototype.isReady.call(this)) {
  17609. return false;
  17610. }
  17611. for (var name in this._textures) {
  17612. var texture = this._textures[name];
  17613. if (!texture.isReady()) {
  17614. return false;
  17615. }
  17616. }
  17617. return true;
  17618. };
  17619. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17620. if (this._animate) {
  17621. this._time += this.getScene().getAnimationRatio() * 0.03;
  17622. this.updateShaderUniforms();
  17623. }
  17624. _super.prototype.render.call(this, useCameraPostProcess);
  17625. };
  17626. CustomProceduralTexture.prototype.updateTextures = function () {
  17627. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17628. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17629. }
  17630. };
  17631. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17632. if (this._config) {
  17633. for (var j = 0; j < this._config.uniforms.length; j++) {
  17634. var uniform = this._config.uniforms[j];
  17635. switch (uniform.type) {
  17636. case "float":
  17637. this.setFloat(uniform.name, uniform.value);
  17638. break;
  17639. case "color3":
  17640. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17641. break;
  17642. case "color4":
  17643. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17644. break;
  17645. case "vector2":
  17646. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17647. break;
  17648. case "vector3":
  17649. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17650. break;
  17651. }
  17652. }
  17653. }
  17654. this.setFloat("time", this._time);
  17655. };
  17656. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17657. get: function () {
  17658. return this._animate;
  17659. },
  17660. set: function (value) {
  17661. this._animate = value;
  17662. },
  17663. enumerable: true,
  17664. configurable: true
  17665. });
  17666. return CustomProceduralTexture;
  17667. })(BABYLON.ProceduralTexture);
  17668. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17669. })(BABYLON || (BABYLON = {}));
  17670. var BABYLON;
  17671. (function (BABYLON) {
  17672. var WoodProceduralTexture = (function (_super) {
  17673. __extends(WoodProceduralTexture, _super);
  17674. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17675. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17676. this._ampScale = 100.0;
  17677. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17678. this.updateShaderUniforms();
  17679. this.refreshRate = 0;
  17680. }
  17681. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17682. this.setFloat("ampScale", this._ampScale);
  17683. this.setColor3("woodColor", this._woodColor);
  17684. };
  17685. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17686. get: function () {
  17687. return this._ampScale;
  17688. },
  17689. set: function (value) {
  17690. this._ampScale = value;
  17691. this.updateShaderUniforms();
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17697. get: function () {
  17698. return this._woodColor;
  17699. },
  17700. set: function (value) {
  17701. this._woodColor = value;
  17702. this.updateShaderUniforms();
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. return WoodProceduralTexture;
  17708. })(BABYLON.ProceduralTexture);
  17709. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17710. var FireProceduralTexture = (function (_super) {
  17711. __extends(FireProceduralTexture, _super);
  17712. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17713. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17714. this._time = 0.0;
  17715. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17716. this._autoGenerateTime = true;
  17717. this._alphaThreshold = 0.5;
  17718. this._fireColors = FireProceduralTexture.RedFireColors;
  17719. this.updateShaderUniforms();
  17720. this.refreshRate = 1;
  17721. }
  17722. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17723. this.setFloat("time", this._time);
  17724. this.setVector2("speed", this._speed);
  17725. this.setColor3("c1", this._fireColors[0]);
  17726. this.setColor3("c2", this._fireColors[1]);
  17727. this.setColor3("c3", this._fireColors[2]);
  17728. this.setColor3("c4", this._fireColors[3]);
  17729. this.setColor3("c5", this._fireColors[4]);
  17730. this.setColor3("c6", this._fireColors[5]);
  17731. this.setFloat("alphaThreshold", this._alphaThreshold);
  17732. };
  17733. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17734. if (this._autoGenerateTime) {
  17735. this._time += this.getScene().getAnimationRatio() * 0.03;
  17736. this.updateShaderUniforms();
  17737. }
  17738. _super.prototype.render.call(this, useCameraPostProcess);
  17739. };
  17740. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17741. get: function () {
  17742. return [
  17743. new BABYLON.Color3(0.5, 0.0, 1.0),
  17744. new BABYLON.Color3(0.9, 0.0, 1.0),
  17745. new BABYLON.Color3(0.2, 0.0, 1.0),
  17746. new BABYLON.Color3(1.0, 0.9, 1.0),
  17747. new BABYLON.Color3(0.1, 0.1, 1.0),
  17748. new BABYLON.Color3(0.9, 0.9, 1.0)
  17749. ];
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17755. get: function () {
  17756. return [
  17757. new BABYLON.Color3(0.5, 1.0, 0.0),
  17758. new BABYLON.Color3(0.5, 1.0, 0.0),
  17759. new BABYLON.Color3(0.3, 0.4, 0.0),
  17760. new BABYLON.Color3(0.5, 1.0, 0.0),
  17761. new BABYLON.Color3(0.2, 0.0, 0.0),
  17762. new BABYLON.Color3(0.5, 1.0, 0.0)
  17763. ];
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17769. get: function () {
  17770. return [
  17771. new BABYLON.Color3(0.5, 0.0, 0.1),
  17772. new BABYLON.Color3(0.9, 0.0, 0.0),
  17773. new BABYLON.Color3(0.2, 0.0, 0.0),
  17774. new BABYLON.Color3(1.0, 0.9, 0.0),
  17775. new BABYLON.Color3(0.1, 0.1, 0.1),
  17776. new BABYLON.Color3(0.9, 0.9, 0.9)
  17777. ];
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17783. get: function () {
  17784. return [
  17785. new BABYLON.Color3(0.1, 0.0, 0.5),
  17786. new BABYLON.Color3(0.0, 0.0, 0.5),
  17787. new BABYLON.Color3(0.1, 0.0, 0.2),
  17788. new BABYLON.Color3(0.0, 0.0, 1.0),
  17789. new BABYLON.Color3(0.1, 0.2, 0.3),
  17790. new BABYLON.Color3(0.0, 0.2, 0.9)
  17791. ];
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17797. get: function () {
  17798. return this._fireColors;
  17799. },
  17800. set: function (value) {
  17801. this._fireColors = value;
  17802. this.updateShaderUniforms();
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17808. get: function () {
  17809. return this._time;
  17810. },
  17811. set: function (value) {
  17812. this._time = value;
  17813. this.updateShaderUniforms();
  17814. },
  17815. enumerable: true,
  17816. configurable: true
  17817. });
  17818. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17819. get: function () {
  17820. return this._speed;
  17821. },
  17822. set: function (value) {
  17823. this._speed = value;
  17824. this.updateShaderUniforms();
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17830. get: function () {
  17831. return this._alphaThreshold;
  17832. },
  17833. set: function (value) {
  17834. this._alphaThreshold = value;
  17835. this.updateShaderUniforms();
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. return FireProceduralTexture;
  17841. })(BABYLON.ProceduralTexture);
  17842. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17843. var CloudProceduralTexture = (function (_super) {
  17844. __extends(CloudProceduralTexture, _super);
  17845. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17846. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17847. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17848. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17849. this.updateShaderUniforms();
  17850. this.refreshRate = 0;
  17851. }
  17852. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17853. this.setColor4("skyColor", this._skyColor);
  17854. this.setColor4("cloudColor", this._cloudColor);
  17855. };
  17856. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17857. get: function () {
  17858. return this._skyColor;
  17859. },
  17860. set: function (value) {
  17861. this._skyColor = value;
  17862. this.updateShaderUniforms();
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17868. get: function () {
  17869. return this._cloudColor;
  17870. },
  17871. set: function (value) {
  17872. this._cloudColor = value;
  17873. this.updateShaderUniforms();
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. return CloudProceduralTexture;
  17879. })(BABYLON.ProceduralTexture);
  17880. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17881. var GrassProceduralTexture = (function (_super) {
  17882. __extends(GrassProceduralTexture, _super);
  17883. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17884. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17885. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17886. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17887. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17888. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17889. this._grassColors = [
  17890. new BABYLON.Color3(0.29, 0.38, 0.02),
  17891. new BABYLON.Color3(0.36, 0.49, 0.09),
  17892. new BABYLON.Color3(0.51, 0.6, 0.28)
  17893. ];
  17894. this.updateShaderUniforms();
  17895. this.refreshRate = 0;
  17896. }
  17897. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17898. this.setColor3("herb1Color", this._grassColors[0]);
  17899. this.setColor3("herb2Color", this._grassColors[1]);
  17900. this.setColor3("herb3Color", this._grassColors[2]);
  17901. this.setColor3("groundColor", this._groundColor);
  17902. };
  17903. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17904. get: function () {
  17905. return this._grassColors;
  17906. },
  17907. set: function (value) {
  17908. this._grassColors = value;
  17909. this.updateShaderUniforms();
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17915. get: function () {
  17916. return this._groundColor;
  17917. },
  17918. set: function (value) {
  17919. this.groundColor = value;
  17920. this.updateShaderUniforms();
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. return GrassProceduralTexture;
  17926. })(BABYLON.ProceduralTexture);
  17927. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17928. var RoadProceduralTexture = (function (_super) {
  17929. __extends(RoadProceduralTexture, _super);
  17930. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17931. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17932. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17933. this.updateShaderUniforms();
  17934. this.refreshRate = 0;
  17935. }
  17936. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17937. this.setColor3("roadColor", this._roadColor);
  17938. };
  17939. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17940. get: function () {
  17941. return this._roadColor;
  17942. },
  17943. set: function (value) {
  17944. this._roadColor = value;
  17945. this.updateShaderUniforms();
  17946. },
  17947. enumerable: true,
  17948. configurable: true
  17949. });
  17950. return RoadProceduralTexture;
  17951. })(BABYLON.ProceduralTexture);
  17952. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17953. var BrickProceduralTexture = (function (_super) {
  17954. __extends(BrickProceduralTexture, _super);
  17955. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17956. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17957. this._numberOfBricksHeight = 15;
  17958. this._numberOfBricksWidth = 5;
  17959. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17960. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17961. this.updateShaderUniforms();
  17962. this.refreshRate = 0;
  17963. }
  17964. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17965. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17966. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17967. this.setColor3("brickColor", this._brickColor);
  17968. this.setColor3("jointColor", this._jointColor);
  17969. };
  17970. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17971. get: function () {
  17972. return this._numberOfBricksHeight;
  17973. },
  17974. set: function (value) {
  17975. this._numberOfBricksHeight = value;
  17976. this.updateShaderUniforms();
  17977. },
  17978. enumerable: true,
  17979. configurable: true
  17980. });
  17981. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17982. get: function () {
  17983. return this._numberOfBricksWidth;
  17984. },
  17985. set: function (value) {
  17986. this._numberOfBricksWidth = value;
  17987. this.updateShaderUniforms();
  17988. },
  17989. enumerable: true,
  17990. configurable: true
  17991. });
  17992. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17993. get: function () {
  17994. return this._jointColor;
  17995. },
  17996. set: function (value) {
  17997. this._jointColor = value;
  17998. this.updateShaderUniforms();
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  18004. get: function () {
  18005. return this._brickColor;
  18006. },
  18007. set: function (value) {
  18008. this._brickColor = value;
  18009. this.updateShaderUniforms();
  18010. },
  18011. enumerable: true,
  18012. configurable: true
  18013. });
  18014. return BrickProceduralTexture;
  18015. })(BABYLON.ProceduralTexture);
  18016. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  18017. var MarbleProceduralTexture = (function (_super) {
  18018. __extends(MarbleProceduralTexture, _super);
  18019. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18020. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  18021. this._numberOfTilesHeight = 3;
  18022. this._numberOfTilesWidth = 3;
  18023. this._amplitude = 9.0;
  18024. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18025. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18026. this.updateShaderUniforms();
  18027. this.refreshRate = 0;
  18028. }
  18029. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  18030. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  18031. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  18032. this.setFloat("amplitude", this._amplitude);
  18033. this.setColor3("marbleColor", this._marbleColor);
  18034. this.setColor3("jointColor", this._jointColor);
  18035. };
  18036. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  18037. get: function () {
  18038. return this._numberOfTilesHeight;
  18039. },
  18040. set: function (value) {
  18041. this._numberOfTilesHeight = value;
  18042. this.updateShaderUniforms();
  18043. },
  18044. enumerable: true,
  18045. configurable: true
  18046. });
  18047. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  18048. get: function () {
  18049. return this._numberOfTilesWidth;
  18050. },
  18051. set: function (value) {
  18052. this._numberOfTilesWidth = value;
  18053. this.updateShaderUniforms();
  18054. },
  18055. enumerable: true,
  18056. configurable: true
  18057. });
  18058. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18059. get: function () {
  18060. return this._jointColor;
  18061. },
  18062. set: function (value) {
  18063. this._jointColor = value;
  18064. this.updateShaderUniforms();
  18065. },
  18066. enumerable: true,
  18067. configurable: true
  18068. });
  18069. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18070. get: function () {
  18071. return this._marbleColor;
  18072. },
  18073. set: function (value) {
  18074. this._marbleColor = value;
  18075. this.updateShaderUniforms();
  18076. },
  18077. enumerable: true,
  18078. configurable: true
  18079. });
  18080. return MarbleProceduralTexture;
  18081. })(BABYLON.ProceduralTexture);
  18082. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18083. })(BABYLON || (BABYLON = {}));
  18084. var BABYLON;
  18085. (function (BABYLON) {
  18086. var EffectFallbacks = (function () {
  18087. function EffectFallbacks() {
  18088. this._defines = {};
  18089. this._currentRank = 32;
  18090. this._maxRank = -1;
  18091. }
  18092. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18093. if (!this._defines[rank]) {
  18094. if (rank < this._currentRank) {
  18095. this._currentRank = rank;
  18096. }
  18097. if (rank > this._maxRank) {
  18098. this._maxRank = rank;
  18099. }
  18100. this._defines[rank] = new Array();
  18101. }
  18102. this._defines[rank].push(define);
  18103. };
  18104. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18105. get: function () {
  18106. return this._currentRank <= this._maxRank;
  18107. },
  18108. enumerable: true,
  18109. configurable: true
  18110. });
  18111. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18112. var currentFallbacks = this._defines[this._currentRank];
  18113. for (var index = 0; index < currentFallbacks.length; index++) {
  18114. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18115. }
  18116. this._currentRank++;
  18117. return currentDefines;
  18118. };
  18119. return EffectFallbacks;
  18120. })();
  18121. BABYLON.EffectFallbacks = EffectFallbacks;
  18122. var Effect = (function () {
  18123. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18124. var _this = this;
  18125. this._isReady = false;
  18126. this._compilationError = "";
  18127. this._valueCache = [];
  18128. this._engine = engine;
  18129. this.name = baseName;
  18130. this.defines = defines;
  18131. this._uniformsNames = uniformsNames.concat(samplers);
  18132. this._samplers = samplers;
  18133. this._attributesNames = attributesNames;
  18134. this.onError = onError;
  18135. this.onCompiled = onCompiled;
  18136. var vertexSource;
  18137. var fragmentSource;
  18138. if (baseName.vertexElement) {
  18139. vertexSource = document.getElementById(baseName.vertexElement);
  18140. if (!vertexSource) {
  18141. vertexSource = baseName.vertexElement;
  18142. }
  18143. }
  18144. else {
  18145. vertexSource = baseName.vertex || baseName;
  18146. }
  18147. if (baseName.fragmentElement) {
  18148. fragmentSource = document.getElementById(baseName.fragmentElement);
  18149. if (!fragmentSource) {
  18150. fragmentSource = baseName.fragmentElement;
  18151. }
  18152. }
  18153. else {
  18154. fragmentSource = baseName.fragment || baseName;
  18155. }
  18156. this._loadVertexShader(vertexSource, function (vertexCode) {
  18157. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18158. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18159. });
  18160. });
  18161. }
  18162. // Properties
  18163. Effect.prototype.isReady = function () {
  18164. return this._isReady;
  18165. };
  18166. Effect.prototype.getProgram = function () {
  18167. return this._program;
  18168. };
  18169. Effect.prototype.getAttributesNames = function () {
  18170. return this._attributesNames;
  18171. };
  18172. Effect.prototype.getAttributeLocation = function (index) {
  18173. return this._attributes[index];
  18174. };
  18175. Effect.prototype.getAttributeLocationByName = function (name) {
  18176. var index = this._attributesNames.indexOf(name);
  18177. return this._attributes[index];
  18178. };
  18179. Effect.prototype.getAttributesCount = function () {
  18180. return this._attributes.length;
  18181. };
  18182. Effect.prototype.getUniformIndex = function (uniformName) {
  18183. return this._uniformsNames.indexOf(uniformName);
  18184. };
  18185. Effect.prototype.getUniform = function (uniformName) {
  18186. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18187. };
  18188. Effect.prototype.getSamplers = function () {
  18189. return this._samplers;
  18190. };
  18191. Effect.prototype.getCompilationError = function () {
  18192. return this._compilationError;
  18193. };
  18194. // Methods
  18195. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18196. // DOM element ?
  18197. if (vertex instanceof HTMLElement) {
  18198. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18199. callback(vertexCode);
  18200. return;
  18201. }
  18202. // Is in local store ?
  18203. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18204. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18205. return;
  18206. }
  18207. var vertexShaderUrl;
  18208. if (vertex[0] === "." || vertex[0] === "/") {
  18209. vertexShaderUrl = vertex;
  18210. }
  18211. else {
  18212. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18213. }
  18214. // Vertex shader
  18215. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18216. };
  18217. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18218. // DOM element ?
  18219. if (fragment instanceof HTMLElement) {
  18220. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18221. callback(fragmentCode);
  18222. return;
  18223. }
  18224. // Is in local store ?
  18225. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18226. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18227. return;
  18228. }
  18229. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18230. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18231. return;
  18232. }
  18233. var fragmentShaderUrl;
  18234. if (fragment[0] === "." || fragment[0] === "/") {
  18235. fragmentShaderUrl = fragment;
  18236. }
  18237. else {
  18238. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18239. }
  18240. // Fragment shader
  18241. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18242. };
  18243. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18244. try {
  18245. var engine = this._engine;
  18246. if (!engine.getCaps().highPrecisionShaderSupported) {
  18247. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18248. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18249. }
  18250. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18251. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18252. this._attributes = engine.getAttributes(this._program, attributesNames);
  18253. for (var index = 0; index < this._samplers.length; index++) {
  18254. var sampler = this.getUniform(this._samplers[index]);
  18255. if (sampler == null) {
  18256. this._samplers.splice(index, 1);
  18257. index--;
  18258. }
  18259. }
  18260. engine.bindSamplers(this);
  18261. this._isReady = true;
  18262. if (this.onCompiled) {
  18263. this.onCompiled(this);
  18264. }
  18265. }
  18266. catch (e) {
  18267. // Is it a problem with precision?
  18268. if (e.message.indexOf("highp") !== -1) {
  18269. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18270. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18271. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18272. return;
  18273. }
  18274. // Let's go through fallbacks then
  18275. if (fallbacks && fallbacks.isMoreFallbacks) {
  18276. defines = fallbacks.reduce(defines);
  18277. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18278. }
  18279. else {
  18280. BABYLON.Tools.Error("Unable to compile effect: ");
  18281. if (this.name.vertexElement) {
  18282. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18283. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18284. }
  18285. else if (this.name.vertex) {
  18286. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18287. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18288. }
  18289. else {
  18290. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18291. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18292. }
  18293. BABYLON.Tools.Error("Defines: " + defines);
  18294. BABYLON.Tools.Error("Error: " + e.message);
  18295. this._compilationError = e.message;
  18296. if (this.onError) {
  18297. this.onError(this, this._compilationError);
  18298. }
  18299. }
  18300. }
  18301. };
  18302. Effect.prototype._bindTexture = function (channel, texture) {
  18303. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18304. };
  18305. Effect.prototype.setTexture = function (channel, texture) {
  18306. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18307. };
  18308. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18309. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18310. };
  18311. //public _cacheMatrix(uniformName, matrix) {
  18312. // if (!this._valueCache[uniformName]) {
  18313. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18314. // }
  18315. // for (var index = 0; index < 16; index++) {
  18316. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18317. // }
  18318. //};
  18319. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18320. if (!this._valueCache[uniformName]) {
  18321. this._valueCache[uniformName] = [x, y];
  18322. return;
  18323. }
  18324. this._valueCache[uniformName][0] = x;
  18325. this._valueCache[uniformName][1] = y;
  18326. };
  18327. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18328. if (!this._valueCache[uniformName]) {
  18329. this._valueCache[uniformName] = [x, y, z];
  18330. return;
  18331. }
  18332. this._valueCache[uniformName][0] = x;
  18333. this._valueCache[uniformName][1] = y;
  18334. this._valueCache[uniformName][2] = z;
  18335. };
  18336. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18337. if (!this._valueCache[uniformName]) {
  18338. this._valueCache[uniformName] = [x, y, z, w];
  18339. return;
  18340. }
  18341. this._valueCache[uniformName][0] = x;
  18342. this._valueCache[uniformName][1] = y;
  18343. this._valueCache[uniformName][2] = z;
  18344. this._valueCache[uniformName][3] = w;
  18345. };
  18346. Effect.prototype.setArray = function (uniformName, array) {
  18347. this._engine.setArray(this.getUniform(uniformName), array);
  18348. return this;
  18349. };
  18350. Effect.prototype.setArray2 = function (uniformName, array) {
  18351. this._engine.setArray2(this.getUniform(uniformName), array);
  18352. return this;
  18353. };
  18354. Effect.prototype.setArray3 = function (uniformName, array) {
  18355. this._engine.setArray3(this.getUniform(uniformName), array);
  18356. return this;
  18357. };
  18358. Effect.prototype.setArray4 = function (uniformName, array) {
  18359. this._engine.setArray4(this.getUniform(uniformName), array);
  18360. return this;
  18361. };
  18362. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18363. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18364. return this;
  18365. };
  18366. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18367. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18368. // return;
  18369. //this._cacheMatrix(uniformName, matrix);
  18370. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18371. return this;
  18372. };
  18373. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18374. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18375. return this;
  18376. };
  18377. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18378. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18379. return this;
  18380. };
  18381. Effect.prototype.setFloat = function (uniformName, value) {
  18382. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18383. return this;
  18384. this._valueCache[uniformName] = value;
  18385. this._engine.setFloat(this.getUniform(uniformName), value);
  18386. return this;
  18387. };
  18388. Effect.prototype.setBool = function (uniformName, bool) {
  18389. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18390. return this;
  18391. this._valueCache[uniformName] = bool;
  18392. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18393. return this;
  18394. };
  18395. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18396. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18397. return this;
  18398. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18399. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18400. return this;
  18401. };
  18402. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18403. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18404. return this;
  18405. this._cacheFloat2(uniformName, x, y);
  18406. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18407. return this;
  18408. };
  18409. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18410. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18411. return this;
  18412. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18413. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18414. return this;
  18415. };
  18416. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18417. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18418. return this;
  18419. this._cacheFloat3(uniformName, x, y, z);
  18420. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18421. return this;
  18422. };
  18423. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18424. 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)
  18425. return this;
  18426. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18427. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18428. return this;
  18429. };
  18430. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18431. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18432. return this;
  18433. this._cacheFloat4(uniformName, x, y, z, w);
  18434. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18435. return this;
  18436. };
  18437. Effect.prototype.setColor3 = function (uniformName, color3) {
  18438. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18439. return this;
  18440. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18441. this._engine.setColor3(this.getUniform(uniformName), color3);
  18442. return this;
  18443. };
  18444. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18445. 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)
  18446. return this;
  18447. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18448. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18449. return this;
  18450. };
  18451. // Statics
  18452. Effect.ShadersStore = {};
  18453. return Effect;
  18454. })();
  18455. BABYLON.Effect = Effect;
  18456. })(BABYLON || (BABYLON = {}));
  18457. var BABYLON;
  18458. (function (BABYLON) {
  18459. var Material = (function () {
  18460. function Material(name, scene, doNotAdd) {
  18461. this.name = name;
  18462. this.checkReadyOnEveryCall = true;
  18463. this.checkReadyOnlyOnce = false;
  18464. this.state = "";
  18465. this.alpha = 1.0;
  18466. this.backFaceCulling = true;
  18467. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18468. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18469. this.disableDepthWrite = false;
  18470. this._wasPreviouslyReady = false;
  18471. this._fillMode = Material.TriangleFillMode;
  18472. this.pointSize = 1.0;
  18473. this.zOffset = 0;
  18474. this.id = name;
  18475. this._scene = scene;
  18476. if (!doNotAdd) {
  18477. scene.materials.push(this);
  18478. }
  18479. }
  18480. Object.defineProperty(Material, "TriangleFillMode", {
  18481. get: function () {
  18482. return Material._TriangleFillMode;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(Material, "WireFrameFillMode", {
  18488. get: function () {
  18489. return Material._WireFrameFillMode;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. Object.defineProperty(Material, "PointFillMode", {
  18495. get: function () {
  18496. return Material._PointFillMode;
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18502. get: function () {
  18503. return Material._ClockWiseSideOrientation;
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18509. get: function () {
  18510. return Material._CounterClockWiseSideOrientation;
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. Object.defineProperty(Material.prototype, "wireframe", {
  18516. get: function () {
  18517. return this._fillMode === Material.WireFrameFillMode;
  18518. },
  18519. set: function (value) {
  18520. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18521. },
  18522. enumerable: true,
  18523. configurable: true
  18524. });
  18525. Object.defineProperty(Material.prototype, "pointsCloud", {
  18526. get: function () {
  18527. return this._fillMode === Material.PointFillMode;
  18528. },
  18529. set: function (value) {
  18530. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18531. },
  18532. enumerable: true,
  18533. configurable: true
  18534. });
  18535. Object.defineProperty(Material.prototype, "fillMode", {
  18536. get: function () {
  18537. return this._fillMode;
  18538. },
  18539. set: function (value) {
  18540. this._fillMode = value;
  18541. },
  18542. enumerable: true,
  18543. configurable: true
  18544. });
  18545. Material.prototype.isReady = function (mesh, useInstances) {
  18546. return true;
  18547. };
  18548. Material.prototype.getEffect = function () {
  18549. return this._effect;
  18550. };
  18551. Material.prototype.getScene = function () {
  18552. return this._scene;
  18553. };
  18554. Material.prototype.needAlphaBlending = function () {
  18555. return (this.alpha < 1.0);
  18556. };
  18557. Material.prototype.needAlphaTesting = function () {
  18558. return false;
  18559. };
  18560. Material.prototype.getAlphaTestTexture = function () {
  18561. return null;
  18562. };
  18563. Material.prototype.trackCreation = function (onCompiled, onError) {
  18564. };
  18565. Material.prototype._preBind = function () {
  18566. var engine = this._scene.getEngine();
  18567. engine.enableEffect(this._effect);
  18568. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18569. };
  18570. Material.prototype.bind = function (world, mesh) {
  18571. this._scene._cachedMaterial = this;
  18572. if (this.onBind) {
  18573. this.onBind(this, mesh);
  18574. }
  18575. if (this.disableDepthWrite) {
  18576. var engine = this._scene.getEngine();
  18577. this._cachedDepthWriteState = engine.getDepthWrite();
  18578. engine.setDepthWrite(false);
  18579. }
  18580. };
  18581. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18582. };
  18583. Material.prototype.unbind = function () {
  18584. if (this.disableDepthWrite) {
  18585. var engine = this._scene.getEngine();
  18586. engine.setDepthWrite(this._cachedDepthWriteState);
  18587. }
  18588. };
  18589. Material.prototype.clone = function (name) {
  18590. return null;
  18591. };
  18592. Material.prototype.dispose = function (forceDisposeEffect) {
  18593. // Remove from scene
  18594. var index = this._scene.materials.indexOf(this);
  18595. this._scene.materials.splice(index, 1);
  18596. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18597. if (forceDisposeEffect && this._effect) {
  18598. this._scene.getEngine()._releaseEffect(this._effect);
  18599. this._effect = null;
  18600. }
  18601. // Callback
  18602. if (this.onDispose) {
  18603. this.onDispose();
  18604. }
  18605. };
  18606. Material._TriangleFillMode = 0;
  18607. Material._WireFrameFillMode = 1;
  18608. Material._PointFillMode = 2;
  18609. Material._ClockWiseSideOrientation = 0;
  18610. Material._CounterClockWiseSideOrientation = 1;
  18611. return Material;
  18612. })();
  18613. BABYLON.Material = Material;
  18614. })(BABYLON || (BABYLON = {}));
  18615. var BABYLON;
  18616. (function (BABYLON) {
  18617. var maxSimultaneousLights = 4;
  18618. var FresnelParameters = (function () {
  18619. function FresnelParameters() {
  18620. this.isEnabled = true;
  18621. this.leftColor = BABYLON.Color3.White();
  18622. this.rightColor = BABYLON.Color3.Black();
  18623. this.bias = 0;
  18624. this.power = 1;
  18625. }
  18626. return FresnelParameters;
  18627. })();
  18628. BABYLON.FresnelParameters = FresnelParameters;
  18629. var StandardMaterialDefines = (function () {
  18630. function StandardMaterialDefines() {
  18631. this.DIFFUSE = false;
  18632. this.AMBIENT = false;
  18633. this.OPACITY = false;
  18634. this.OPACITYRGB = false;
  18635. this.REFLECTION = false;
  18636. this.EMISSIVE = false;
  18637. this.SPECULAR = false;
  18638. this.BUMP = false;
  18639. this.SPECULAROVERALPHA = false;
  18640. this.CLIPPLANE = false;
  18641. this.ALPHATEST = false;
  18642. this.ALPHAFROMDIFFUSE = false;
  18643. this.POINTSIZE = false;
  18644. this.FOG = false;
  18645. this.LIGHT0 = false;
  18646. this.LIGHT1 = false;
  18647. this.LIGHT2 = false;
  18648. this.LIGHT3 = false;
  18649. this.SPOTLIGHT0 = false;
  18650. this.SPOTLIGHT1 = false;
  18651. this.SPOTLIGHT2 = false;
  18652. this.SPOTLIGHT3 = false;
  18653. this.HEMILIGHT0 = false;
  18654. this.HEMILIGHT1 = false;
  18655. this.HEMILIGHT2 = false;
  18656. this.HEMILIGHT3 = false;
  18657. this.POINTDIRLIGHT0 = false;
  18658. this.POINTDIRLIGHT1 = false;
  18659. this.POINTDIRLIGHT2 = false;
  18660. this.POINTDIRLIGHT3 = false;
  18661. this.SPECULARTERM = false;
  18662. this.SHADOW0 = false;
  18663. this.SHADOW1 = false;
  18664. this.SHADOW2 = false;
  18665. this.SHADOW3 = false;
  18666. this.SHADOWS = false;
  18667. this.SHADOWVSM0 = false;
  18668. this.SHADOWVSM1 = false;
  18669. this.SHADOWVSM2 = false;
  18670. this.SHADOWVSM3 = false;
  18671. this.SHADOWPCF0 = false;
  18672. this.SHADOWPCF1 = false;
  18673. this.SHADOWPCF2 = false;
  18674. this.SHADOWPCF3 = false;
  18675. this.DIFFUSEFRESNEL = false;
  18676. this.OPACITYFRESNEL = false;
  18677. this.REFLECTIONFRESNEL = false;
  18678. this.EMISSIVEFRESNEL = false;
  18679. this.FRESNEL = false;
  18680. this.NORMAL = false;
  18681. this.UV1 = false;
  18682. this.UV2 = false;
  18683. this.VERTEXCOLOR = false;
  18684. this.VERTEXALPHA = false;
  18685. this.BONES = false;
  18686. this.BONES4 = false;
  18687. this.BonesPerMesh = 0;
  18688. this.INSTANCES = false;
  18689. this.GLOSSINESS = false;
  18690. this.ROUGHNESS = false;
  18691. this.EMISSIVEASILLUMINATION = false;
  18692. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18693. this.LIGHTMAP = false;
  18694. this._keys = Object.keys(this);
  18695. }
  18696. StandardMaterialDefines.prototype.isEqual = function (other) {
  18697. for (var index = 0; index < this._keys.length; index++) {
  18698. var prop = this._keys[index];
  18699. if (this[prop] !== other[prop]) {
  18700. return false;
  18701. }
  18702. }
  18703. return true;
  18704. };
  18705. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18706. for (var index = 0; index < this._keys.length; index++) {
  18707. var prop = this._keys[index];
  18708. other[prop] = this[prop];
  18709. }
  18710. };
  18711. StandardMaterialDefines.prototype.reset = function () {
  18712. for (var index = 0; index < this._keys.length; index++) {
  18713. var prop = this._keys[index];
  18714. if (prop === "BonesPerMesh") {
  18715. this[prop] = 0;
  18716. continue;
  18717. }
  18718. this[prop] = false;
  18719. }
  18720. };
  18721. StandardMaterialDefines.prototype.toString = function () {
  18722. var result = "";
  18723. for (var index = 0; index < this._keys.length; index++) {
  18724. var prop = this._keys[index];
  18725. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18726. result += "#define BonesPerMesh " + this[prop] + "\n";
  18727. continue;
  18728. }
  18729. if (this[prop]) {
  18730. result += "#define " + prop + "\n";
  18731. }
  18732. }
  18733. return result;
  18734. };
  18735. return StandardMaterialDefines;
  18736. })();
  18737. var StandardMaterial = (function (_super) {
  18738. __extends(StandardMaterial, _super);
  18739. function StandardMaterial(name, scene) {
  18740. var _this = this;
  18741. _super.call(this, name, scene);
  18742. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18743. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18744. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18745. this.specularPower = 64;
  18746. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18747. this.useAlphaFromDiffuseTexture = false;
  18748. this.useEmissiveAsIllumination = false;
  18749. this.useReflectionFresnelFromSpecular = false;
  18750. this.useSpecularOverAlpha = true;
  18751. this.fogEnabled = true;
  18752. this.roughness = 0;
  18753. this.lightmapThreshold = 0;
  18754. this.useGlossinessFromSpecularMapAlpha = false;
  18755. this._renderTargets = new BABYLON.SmartArray(16);
  18756. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18757. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18758. this._scaledDiffuse = new BABYLON.Color3();
  18759. this._scaledSpecular = new BABYLON.Color3();
  18760. this._defines = new StandardMaterialDefines();
  18761. this._cachedDefines = new StandardMaterialDefines();
  18762. this._cachedDefines.BonesPerMesh = -1;
  18763. this.getRenderTargetTextures = function () {
  18764. _this._renderTargets.reset();
  18765. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18766. _this._renderTargets.push(_this.reflectionTexture);
  18767. }
  18768. return _this._renderTargets;
  18769. };
  18770. }
  18771. StandardMaterial.prototype.needAlphaBlending = function () {
  18772. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18773. };
  18774. StandardMaterial.prototype.needAlphaTesting = function () {
  18775. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18776. };
  18777. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18778. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18779. };
  18780. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18781. return this.diffuseTexture;
  18782. };
  18783. // Methods
  18784. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18785. if (this.checkReadyOnlyOnce) {
  18786. if (this._wasPreviouslyReady) {
  18787. return true;
  18788. }
  18789. }
  18790. var scene = this.getScene();
  18791. if (!this.checkReadyOnEveryCall) {
  18792. if (this._renderId === scene.getRenderId()) {
  18793. return true;
  18794. }
  18795. }
  18796. var engine = scene.getEngine();
  18797. var needNormals = false;
  18798. var needUVs = false;
  18799. this._defines.reset();
  18800. // Textures
  18801. if (scene.texturesEnabled) {
  18802. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18803. if (!this.diffuseTexture.isReady()) {
  18804. return false;
  18805. }
  18806. else {
  18807. needUVs = true;
  18808. this._defines.DIFFUSE = true;
  18809. }
  18810. }
  18811. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18812. if (!this.ambientTexture.isReady()) {
  18813. return false;
  18814. }
  18815. else {
  18816. needUVs = true;
  18817. this._defines.AMBIENT = true;
  18818. }
  18819. }
  18820. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18821. if (!this.opacityTexture.isReady()) {
  18822. return false;
  18823. }
  18824. else {
  18825. needUVs = true;
  18826. this._defines.OPACITY = true;
  18827. if (this.opacityTexture.getAlphaFromRGB) {
  18828. this._defines.OPACITYRGB = true;
  18829. }
  18830. }
  18831. }
  18832. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18833. if (!this.reflectionTexture.isReady()) {
  18834. return false;
  18835. }
  18836. else {
  18837. needNormals = true;
  18838. needUVs = true;
  18839. this._defines.REFLECTION = true;
  18840. if (this.roughness > 0) {
  18841. this._defines.ROUGHNESS = true;
  18842. }
  18843. }
  18844. }
  18845. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18846. if (!this.emissiveTexture.isReady()) {
  18847. return false;
  18848. }
  18849. else {
  18850. needUVs = true;
  18851. this._defines.EMISSIVE = true;
  18852. }
  18853. }
  18854. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18855. if (!this.lightmapTexture.isReady()) {
  18856. return false;
  18857. }
  18858. else {
  18859. needUVs = true;
  18860. this._defines.LIGHTMAP = true;
  18861. }
  18862. }
  18863. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18864. if (!this.specularTexture.isReady()) {
  18865. return false;
  18866. }
  18867. else {
  18868. needUVs = true;
  18869. this._defines.SPECULAR = true;
  18870. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18871. }
  18872. }
  18873. }
  18874. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18875. if (!this.bumpTexture.isReady()) {
  18876. return false;
  18877. }
  18878. else {
  18879. needUVs = true;
  18880. this._defines.BUMP = true;
  18881. }
  18882. }
  18883. // Effect
  18884. if (scene.clipPlane) {
  18885. this._defines.CLIPPLANE = true;
  18886. }
  18887. if (engine.getAlphaTesting()) {
  18888. this._defines.ALPHATEST = true;
  18889. }
  18890. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18891. this._defines.ALPHAFROMDIFFUSE = true;
  18892. }
  18893. if (this.useEmissiveAsIllumination) {
  18894. this._defines.EMISSIVEASILLUMINATION = true;
  18895. }
  18896. if (this.useReflectionFresnelFromSpecular) {
  18897. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18898. }
  18899. // Point size
  18900. if (this.pointsCloud || scene.forcePointsCloud) {
  18901. this._defines.POINTSIZE = true;
  18902. }
  18903. // Fog
  18904. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18905. this._defines.FOG = true;
  18906. }
  18907. var lightIndex = 0;
  18908. if (scene.lightsEnabled) {
  18909. for (var index = 0; index < scene.lights.length; index++) {
  18910. var light = scene.lights[index];
  18911. if (!light.isEnabled()) {
  18912. continue;
  18913. }
  18914. // Excluded check
  18915. if (light._excludedMeshesIds.length > 0) {
  18916. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18917. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18918. if (excludedMesh) {
  18919. light.excludedMeshes.push(excludedMesh);
  18920. }
  18921. }
  18922. light._excludedMeshesIds = [];
  18923. }
  18924. // Included check
  18925. if (light._includedOnlyMeshesIds.length > 0) {
  18926. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18927. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18928. if (includedOnlyMesh) {
  18929. light.includedOnlyMeshes.push(includedOnlyMesh);
  18930. }
  18931. }
  18932. light._includedOnlyMeshesIds = [];
  18933. }
  18934. if (!light.canAffectMesh(mesh)) {
  18935. continue;
  18936. }
  18937. needNormals = true;
  18938. this._defines["LIGHT" + lightIndex] = true;
  18939. var type;
  18940. if (light instanceof BABYLON.SpotLight) {
  18941. type = "SPOTLIGHT" + lightIndex;
  18942. }
  18943. else if (light instanceof BABYLON.HemisphericLight) {
  18944. type = "HEMILIGHT" + lightIndex;
  18945. }
  18946. else {
  18947. type = "POINTDIRLIGHT" + lightIndex;
  18948. }
  18949. this._defines[type] = true;
  18950. // Specular
  18951. if (!light.specular.equalsFloats(0, 0, 0)) {
  18952. this._defines.SPECULARTERM = true;
  18953. }
  18954. // Shadows
  18955. if (scene.shadowsEnabled) {
  18956. var shadowGenerator = light.getShadowGenerator();
  18957. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18958. this._defines["SHADOW" + lightIndex] = true;
  18959. this._defines.SHADOWS = true;
  18960. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18961. this._defines["SHADOWVSM" + lightIndex] = true;
  18962. }
  18963. if (shadowGenerator.usePoissonSampling) {
  18964. this._defines["SHADOWPCF" + lightIndex] = true;
  18965. }
  18966. }
  18967. }
  18968. lightIndex++;
  18969. if (lightIndex === maxSimultaneousLights)
  18970. break;
  18971. }
  18972. }
  18973. if (StandardMaterial.FresnelEnabled) {
  18974. // Fresnel
  18975. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18976. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18977. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18978. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18979. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18980. this._defines.DIFFUSEFRESNEL = true;
  18981. }
  18982. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18983. this._defines.OPACITYFRESNEL = true;
  18984. }
  18985. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18986. this._defines.REFLECTIONFRESNEL = true;
  18987. }
  18988. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18989. this._defines.EMISSIVEFRESNEL = true;
  18990. }
  18991. needNormals = true;
  18992. this._defines.FRESNEL = true;
  18993. }
  18994. }
  18995. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18996. this._defines.SPECULAROVERALPHA = true;
  18997. }
  18998. // Attribs
  18999. if (mesh) {
  19000. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19001. this._defines.NORMAL = true;
  19002. }
  19003. if (needUVs) {
  19004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19005. this._defines.UV1 = true;
  19006. }
  19007. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19008. this._defines.UV2 = true;
  19009. }
  19010. }
  19011. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19012. this._defines.VERTEXCOLOR = true;
  19013. if (mesh.hasVertexAlpha) {
  19014. this._defines.VERTEXALPHA = true;
  19015. }
  19016. }
  19017. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19018. this._defines.BONES = true;
  19019. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19020. this._defines.BONES4 = true;
  19021. }
  19022. // Instances
  19023. if (useInstances) {
  19024. this._defines.INSTANCES = true;
  19025. }
  19026. }
  19027. // Get correct effect
  19028. if (!this._defines.isEqual(this._cachedDefines)) {
  19029. this._defines.cloneTo(this._cachedDefines);
  19030. scene.resetCachedMaterial();
  19031. // Fallbacks
  19032. var fallbacks = new BABYLON.EffectFallbacks();
  19033. if (this._defines.REFLECTION) {
  19034. fallbacks.addFallback(0, "REFLECTION");
  19035. }
  19036. if (this._defines.SPECULAR) {
  19037. fallbacks.addFallback(0, "SPECULAR");
  19038. }
  19039. if (this._defines.BUMP) {
  19040. fallbacks.addFallback(0, "BUMP");
  19041. }
  19042. if (this._defines.SPECULAROVERALPHA) {
  19043. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19044. }
  19045. if (this._defines.FOG) {
  19046. fallbacks.addFallback(1, "FOG");
  19047. }
  19048. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19049. if (!this._defines["LIGHT" + lightIndex]) {
  19050. continue;
  19051. }
  19052. if (lightIndex > 0) {
  19053. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19054. }
  19055. if (this._defines["SHADOW" + lightIndex]) {
  19056. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19057. }
  19058. if (this._defines["SHADOWPCF" + lightIndex]) {
  19059. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19060. }
  19061. if (this._defines["SHADOWVSM" + lightIndex]) {
  19062. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19063. }
  19064. }
  19065. if (this._defines.SPECULARTERM) {
  19066. fallbacks.addFallback(0, "SPECULARTERM");
  19067. }
  19068. if (this._defines.DIFFUSEFRESNEL) {
  19069. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19070. }
  19071. if (this._defines.OPACITYFRESNEL) {
  19072. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19073. }
  19074. if (this._defines.REFLECTIONFRESNEL) {
  19075. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19076. }
  19077. if (this._defines.EMISSIVEFRESNEL) {
  19078. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19079. }
  19080. if (this._defines.FRESNEL) {
  19081. fallbacks.addFallback(4, "FRESNEL");
  19082. }
  19083. if (this._defines.BONES4) {
  19084. fallbacks.addFallback(0, "BONES4");
  19085. }
  19086. //Attributes
  19087. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19088. if (this._defines.NORMAL) {
  19089. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19090. }
  19091. if (this._defines.UV1) {
  19092. attribs.push(BABYLON.VertexBuffer.UVKind);
  19093. }
  19094. if (this._defines.UV2) {
  19095. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19096. }
  19097. if (this._defines.VERTEXCOLOR) {
  19098. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19099. }
  19100. if (this._defines.BONES) {
  19101. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19102. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19103. }
  19104. if (this._defines.INSTANCES) {
  19105. attribs.push("world0");
  19106. attribs.push("world1");
  19107. attribs.push("world2");
  19108. attribs.push("world3");
  19109. }
  19110. // Legacy browser patch
  19111. var shaderName = "default";
  19112. if (!scene.getEngine().getCaps().standardDerivatives) {
  19113. shaderName = "legacydefault";
  19114. }
  19115. var join = this._defines.toString();
  19116. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19117. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19118. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19119. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19120. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19121. "vFogInfos", "vFogColor", "pointSize",
  19122. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19123. "mBones",
  19124. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19125. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19126. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19127. "roughness"
  19128. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19129. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19130. ], join, fallbacks, this.onCompiled, this.onError);
  19131. }
  19132. if (!this._effect.isReady()) {
  19133. return false;
  19134. }
  19135. this._renderId = scene.getRenderId();
  19136. this._wasPreviouslyReady = true;
  19137. return true;
  19138. };
  19139. StandardMaterial.prototype.unbind = function () {
  19140. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19141. this._effect.setTexture("reflection2DSampler", null);
  19142. }
  19143. _super.prototype.unbind.call(this);
  19144. };
  19145. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19146. this._effect.setMatrix("world", world);
  19147. };
  19148. StandardMaterial.prototype.bind = function (world, mesh) {
  19149. var scene = this.getScene();
  19150. // Matrices
  19151. this.bindOnlyWorldMatrix(world);
  19152. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19153. // Bones
  19154. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19155. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19156. }
  19157. if (scene.getCachedMaterial() !== this) {
  19158. if (StandardMaterial.FresnelEnabled) {
  19159. // Fresnel
  19160. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19161. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19162. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19163. }
  19164. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19165. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19166. }
  19167. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19168. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19169. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19170. }
  19171. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19172. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19173. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19174. }
  19175. }
  19176. // Textures
  19177. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19178. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19179. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19180. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19181. }
  19182. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19183. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19184. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19185. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19186. }
  19187. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19188. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19189. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19190. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19191. }
  19192. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19193. if (this.reflectionTexture.isCube) {
  19194. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19195. if (this._defines.ROUGHNESS) {
  19196. this._effect.setFloat("roughness", this.roughness);
  19197. }
  19198. }
  19199. else {
  19200. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19201. }
  19202. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19203. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19204. }
  19205. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19206. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19207. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19208. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19209. }
  19210. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19211. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19212. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19213. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19214. }
  19215. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19216. this._effect.setTexture("specularSampler", this.specularTexture);
  19217. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19218. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19219. }
  19220. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19221. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19222. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19223. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19224. }
  19225. // Clip plane
  19226. if (scene.clipPlane) {
  19227. var clipPlane = scene.clipPlane;
  19228. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19229. }
  19230. // Point size
  19231. if (this.pointsCloud) {
  19232. this._effect.setFloat("pointSize", this.pointSize);
  19233. }
  19234. // Colors
  19235. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19236. // Scaling down color according to emissive
  19237. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19238. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19239. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19240. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19241. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19242. if (this._defines.SPECULARTERM) {
  19243. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19244. }
  19245. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19246. }
  19247. // Scaling down color according to emissive
  19248. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19249. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19250. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19251. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19252. if (scene.lightsEnabled) {
  19253. var lightIndex = 0;
  19254. for (var index = 0; index < scene.lights.length; index++) {
  19255. var light = scene.lights[index];
  19256. if (!light.isEnabled()) {
  19257. continue;
  19258. }
  19259. if (!light.canAffectMesh(mesh)) {
  19260. continue;
  19261. }
  19262. if (light instanceof BABYLON.PointLight) {
  19263. // Point Light
  19264. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19265. }
  19266. else if (light instanceof BABYLON.DirectionalLight) {
  19267. // Directional Light
  19268. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19269. }
  19270. else if (light instanceof BABYLON.SpotLight) {
  19271. // Spot Light
  19272. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19273. }
  19274. else if (light instanceof BABYLON.HemisphericLight) {
  19275. // Hemispheric Light
  19276. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19277. }
  19278. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19279. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19280. if (this._defines.SPECULARTERM) {
  19281. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19282. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19283. }
  19284. // Shadows
  19285. if (scene.shadowsEnabled) {
  19286. var shadowGenerator = light.getShadowGenerator();
  19287. if (mesh.receiveShadows && shadowGenerator) {
  19288. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19289. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19290. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19291. }
  19292. }
  19293. lightIndex++;
  19294. if (lightIndex === maxSimultaneousLights)
  19295. break;
  19296. }
  19297. }
  19298. // View
  19299. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19300. this._effect.setMatrix("view", scene.getViewMatrix());
  19301. }
  19302. // Fog
  19303. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19304. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19305. this._effect.setColor3("vFogColor", scene.fogColor);
  19306. }
  19307. _super.prototype.bind.call(this, world, mesh);
  19308. };
  19309. StandardMaterial.prototype.getAnimatables = function () {
  19310. var results = [];
  19311. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19312. results.push(this.diffuseTexture);
  19313. }
  19314. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19315. results.push(this.ambientTexture);
  19316. }
  19317. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19318. results.push(this.opacityTexture);
  19319. }
  19320. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19321. results.push(this.reflectionTexture);
  19322. }
  19323. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19324. results.push(this.emissiveTexture);
  19325. }
  19326. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19327. results.push(this.specularTexture);
  19328. }
  19329. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19330. results.push(this.bumpTexture);
  19331. }
  19332. return results;
  19333. };
  19334. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19335. if (this.diffuseTexture) {
  19336. this.diffuseTexture.dispose();
  19337. }
  19338. if (this.ambientTexture) {
  19339. this.ambientTexture.dispose();
  19340. }
  19341. if (this.opacityTexture) {
  19342. this.opacityTexture.dispose();
  19343. }
  19344. if (this.reflectionTexture) {
  19345. this.reflectionTexture.dispose();
  19346. }
  19347. if (this.emissiveTexture) {
  19348. this.emissiveTexture.dispose();
  19349. }
  19350. if (this.specularTexture) {
  19351. this.specularTexture.dispose();
  19352. }
  19353. if (this.bumpTexture) {
  19354. this.bumpTexture.dispose();
  19355. }
  19356. _super.prototype.dispose.call(this, forceDisposeEffect);
  19357. };
  19358. StandardMaterial.prototype.clone = function (name) {
  19359. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19360. // Base material
  19361. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19362. newStandardMaterial.alpha = this.alpha;
  19363. newStandardMaterial.fillMode = this.fillMode;
  19364. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19365. // Standard material
  19366. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19367. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19368. }
  19369. if (this.ambientTexture && this.ambientTexture.clone) {
  19370. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19371. }
  19372. if (this.opacityTexture && this.opacityTexture.clone) {
  19373. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19374. }
  19375. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19376. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19377. }
  19378. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19379. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19380. }
  19381. if (this.specularTexture && this.specularTexture.clone) {
  19382. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19383. }
  19384. if (this.bumpTexture && this.bumpTexture.clone) {
  19385. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19386. }
  19387. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19388. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19389. newStandardMaterial.specularColor = this.specularColor.clone();
  19390. newStandardMaterial.specularPower = this.specularPower;
  19391. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19392. return newStandardMaterial;
  19393. };
  19394. // Statics
  19395. // Flags used to enable or disable a type of texture for all Standard Materials
  19396. StandardMaterial.DiffuseTextureEnabled = true;
  19397. StandardMaterial.AmbientTextureEnabled = true;
  19398. StandardMaterial.OpacityTextureEnabled = true;
  19399. StandardMaterial.ReflectionTextureEnabled = true;
  19400. StandardMaterial.EmissiveTextureEnabled = true;
  19401. StandardMaterial.SpecularTextureEnabled = true;
  19402. StandardMaterial.BumpTextureEnabled = true;
  19403. StandardMaterial.FresnelEnabled = true;
  19404. StandardMaterial.LightmapEnabled = true;
  19405. return StandardMaterial;
  19406. })(BABYLON.Material);
  19407. BABYLON.StandardMaterial = StandardMaterial;
  19408. })(BABYLON || (BABYLON = {}));
  19409. var BABYLON;
  19410. (function (BABYLON) {
  19411. var MultiMaterial = (function (_super) {
  19412. __extends(MultiMaterial, _super);
  19413. function MultiMaterial(name, scene) {
  19414. _super.call(this, name, scene, true);
  19415. this.subMaterials = new Array();
  19416. scene.multiMaterials.push(this);
  19417. }
  19418. // Properties
  19419. MultiMaterial.prototype.getSubMaterial = function (index) {
  19420. if (index < 0 || index >= this.subMaterials.length) {
  19421. return this.getScene().defaultMaterial;
  19422. }
  19423. return this.subMaterials[index];
  19424. };
  19425. // Methods
  19426. MultiMaterial.prototype.isReady = function (mesh) {
  19427. for (var index = 0; index < this.subMaterials.length; index++) {
  19428. var subMaterial = this.subMaterials[index];
  19429. if (subMaterial) {
  19430. if (!this.subMaterials[index].isReady(mesh)) {
  19431. return false;
  19432. }
  19433. }
  19434. }
  19435. return true;
  19436. };
  19437. MultiMaterial.prototype.clone = function (name) {
  19438. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19439. for (var index = 0; index < this.subMaterials.length; index++) {
  19440. var subMaterial = this.subMaterials[index];
  19441. newMultiMaterial.subMaterials.push(subMaterial);
  19442. }
  19443. return newMultiMaterial;
  19444. };
  19445. return MultiMaterial;
  19446. })(BABYLON.Material);
  19447. BABYLON.MultiMaterial = MultiMaterial;
  19448. })(BABYLON || (BABYLON = {}));
  19449. var BABYLON;
  19450. (function (BABYLON) {
  19451. var SceneLoader = (function () {
  19452. function SceneLoader() {
  19453. }
  19454. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19455. get: function () {
  19456. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19457. },
  19458. set: function (value) {
  19459. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19465. get: function () {
  19466. return SceneLoader._ShowLoadingScreen;
  19467. },
  19468. set: function (value) {
  19469. SceneLoader._ShowLoadingScreen = value;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19475. var dotPosition = sceneFilename.lastIndexOf(".");
  19476. var queryStringPosition = sceneFilename.indexOf("?");
  19477. if (queryStringPosition === -1) {
  19478. queryStringPosition = sceneFilename.length;
  19479. }
  19480. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19481. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19482. var plugin = this._registeredPlugins[index];
  19483. if (plugin.extensions.indexOf(extension) !== -1) {
  19484. return plugin;
  19485. }
  19486. }
  19487. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19488. };
  19489. // Public functions
  19490. SceneLoader.RegisterPlugin = function (plugin) {
  19491. plugin.extensions = plugin.extensions.toLowerCase();
  19492. SceneLoader._registeredPlugins.push(plugin);
  19493. };
  19494. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19495. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19496. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19497. return;
  19498. }
  19499. var loadingToken = {};
  19500. scene._addPendingData(loadingToken);
  19501. var manifestChecked = function (success) {
  19502. scene.database = database;
  19503. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19504. var importMeshFromData = function (data) {
  19505. var meshes = [];
  19506. var particleSystems = [];
  19507. var skeletons = [];
  19508. try {
  19509. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19510. if (onerror) {
  19511. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19512. }
  19513. scene._removePendingData(loadingToken);
  19514. return;
  19515. }
  19516. }
  19517. catch (e) {
  19518. if (onerror) {
  19519. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19520. }
  19521. scene._removePendingData(loadingToken);
  19522. return;
  19523. }
  19524. if (onsuccess) {
  19525. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19526. onsuccess(meshes, particleSystems, skeletons);
  19527. scene._removePendingData(loadingToken);
  19528. }
  19529. };
  19530. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19531. // Direct load
  19532. importMeshFromData(sceneFilename.substr(5));
  19533. return;
  19534. }
  19535. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19536. importMeshFromData(data);
  19537. }, progressCallBack, database);
  19538. };
  19539. if (scene.getEngine().enableOfflineSupport) {
  19540. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19541. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19542. }
  19543. else {
  19544. manifestChecked(true);
  19545. }
  19546. };
  19547. /**
  19548. * Load a scene
  19549. * @param rootUrl a string that defines the root url for scene and resources
  19550. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19551. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19552. */
  19553. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19554. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19555. };
  19556. /**
  19557. * Append a scene
  19558. * @param rootUrl a string that defines the root url for scene and resources
  19559. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19560. * @param scene is the instance of BABYLON.Scene to append to
  19561. */
  19562. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19563. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19564. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19565. return;
  19566. }
  19567. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19568. var database;
  19569. var loadingToken = {};
  19570. scene._addPendingData(loadingToken);
  19571. if (SceneLoader.ShowLoadingScreen) {
  19572. scene.getEngine().displayLoadingUI();
  19573. }
  19574. var loadSceneFromData = function (data) {
  19575. scene.database = database;
  19576. if (!plugin.load(scene, data, rootUrl)) {
  19577. if (onerror) {
  19578. onerror(scene);
  19579. }
  19580. scene._removePendingData(loadingToken);
  19581. scene.getEngine().hideLoadingUI();
  19582. return;
  19583. }
  19584. if (onsuccess) {
  19585. onsuccess(scene);
  19586. }
  19587. scene._removePendingData(loadingToken);
  19588. if (SceneLoader.ShowLoadingScreen) {
  19589. scene.executeWhenReady(function () {
  19590. scene.getEngine().hideLoadingUI();
  19591. });
  19592. }
  19593. };
  19594. var manifestChecked = function (success) {
  19595. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19596. };
  19597. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19598. // Direct load
  19599. loadSceneFromData(sceneFilename.substr(5));
  19600. return;
  19601. }
  19602. if (rootUrl.indexOf("file:") === -1) {
  19603. if (scene.getEngine().enableOfflineSupport) {
  19604. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19605. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19606. }
  19607. else {
  19608. manifestChecked(true);
  19609. }
  19610. }
  19611. else {
  19612. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19613. }
  19614. };
  19615. // Flags
  19616. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19617. SceneLoader._ShowLoadingScreen = true;
  19618. // Members
  19619. SceneLoader._registeredPlugins = new Array();
  19620. return SceneLoader;
  19621. })();
  19622. BABYLON.SceneLoader = SceneLoader;
  19623. ;
  19624. })(BABYLON || (BABYLON = {}));
  19625. var BABYLON;
  19626. (function (BABYLON) {
  19627. var Internals;
  19628. (function (Internals) {
  19629. var checkColors4 = function (colors, count) {
  19630. // Check if color3 was used
  19631. if (colors.length === count * 3) {
  19632. var colors4 = [];
  19633. for (var index = 0; index < colors.length; index += 3) {
  19634. var newIndex = (index / 3) * 4;
  19635. colors4[newIndex] = colors[index];
  19636. colors4[newIndex + 1] = colors[index + 1];
  19637. colors4[newIndex + 2] = colors[index + 2];
  19638. colors4[newIndex + 3] = 1.0;
  19639. }
  19640. return colors4;
  19641. }
  19642. return colors;
  19643. };
  19644. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19645. var texture = null;
  19646. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19647. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19648. texture.name = parsedTexture.name;
  19649. texture.hasAlpha = parsedTexture.hasAlpha;
  19650. texture.level = parsedTexture.level;
  19651. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19652. }
  19653. return texture;
  19654. };
  19655. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19656. if (parsedTexture.isCube) {
  19657. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19658. }
  19659. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19660. return null;
  19661. }
  19662. var texture;
  19663. if (parsedTexture.mirrorPlane) {
  19664. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19665. texture._waitingRenderList = parsedTexture.renderList;
  19666. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19667. }
  19668. else if (parsedTexture.isRenderTarget) {
  19669. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19670. texture._waitingRenderList = parsedTexture.renderList;
  19671. }
  19672. else {
  19673. if (parsedTexture.base64String) {
  19674. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19675. }
  19676. else {
  19677. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19678. }
  19679. }
  19680. texture.name = parsedTexture.name;
  19681. texture.hasAlpha = parsedTexture.hasAlpha;
  19682. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19683. texture.level = parsedTexture.level;
  19684. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19685. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19686. texture.uOffset = parsedTexture.uOffset;
  19687. texture.vOffset = parsedTexture.vOffset;
  19688. texture.uScale = parsedTexture.uScale;
  19689. texture.vScale = parsedTexture.vScale;
  19690. texture.uAng = parsedTexture.uAng;
  19691. texture.vAng = parsedTexture.vAng;
  19692. texture.wAng = parsedTexture.wAng;
  19693. texture.wrapU = parsedTexture.wrapU;
  19694. texture.wrapV = parsedTexture.wrapV;
  19695. // Animations
  19696. if (parsedTexture.animations) {
  19697. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19698. var parsedAnimation = parsedTexture.animations[animationIndex];
  19699. texture.animations.push(parseAnimation(parsedAnimation));
  19700. }
  19701. }
  19702. return texture;
  19703. };
  19704. var parseSkeleton = function (parsedSkeleton, scene) {
  19705. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19706. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19707. var parsedBone = parsedSkeleton.bones[index];
  19708. var parentBone = null;
  19709. if (parsedBone.parentBoneIndex > -1) {
  19710. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19711. }
  19712. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19713. if (parsedBone.animation) {
  19714. bone.animations.push(parseAnimation(parsedBone.animation));
  19715. }
  19716. }
  19717. return skeleton;
  19718. };
  19719. var parseFresnelParameters = function (parsedFresnelParameters) {
  19720. var fresnelParameters = new BABYLON.FresnelParameters();
  19721. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19722. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19723. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19724. fresnelParameters.bias = parsedFresnelParameters.bias;
  19725. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19726. return fresnelParameters;
  19727. };
  19728. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19729. var material;
  19730. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19731. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19732. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19733. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19734. material.specularPower = parsedMaterial.specularPower;
  19735. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19736. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19737. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19738. material.alpha = parsedMaterial.alpha;
  19739. material.id = parsedMaterial.id;
  19740. if (parsedMaterial.disableDepthWrite) {
  19741. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19742. }
  19743. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19744. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19745. material.wireframe = parsedMaterial.wireframe;
  19746. if (parsedMaterial.diffuseTexture) {
  19747. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19748. }
  19749. if (parsedMaterial.diffuseFresnelParameters) {
  19750. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19751. }
  19752. if (parsedMaterial.ambientTexture) {
  19753. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19754. }
  19755. if (parsedMaterial.opacityTexture) {
  19756. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19757. }
  19758. if (parsedMaterial.opacityFresnelParameters) {
  19759. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19760. }
  19761. if (parsedMaterial.reflectionTexture) {
  19762. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19763. }
  19764. if (parsedMaterial.reflectionFresnelParameters) {
  19765. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19766. }
  19767. if (parsedMaterial.emissiveTexture) {
  19768. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19769. }
  19770. if (parsedMaterial.lightmapTexture) {
  19771. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19772. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19773. }
  19774. if (parsedMaterial.emissiveFresnelParameters) {
  19775. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19776. }
  19777. if (parsedMaterial.specularTexture) {
  19778. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19779. }
  19780. if (parsedMaterial.bumpTexture) {
  19781. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19782. }
  19783. if (parsedMaterial.checkReadyOnlyOnce) {
  19784. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19785. }
  19786. return material;
  19787. };
  19788. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19789. for (var index = 0; index < parsedData.materials.length; index++) {
  19790. var parsedMaterial = parsedData.materials[index];
  19791. if (parsedMaterial.id === id) {
  19792. return parseMaterial(parsedMaterial, scene, rootUrl);
  19793. }
  19794. }
  19795. return null;
  19796. };
  19797. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19798. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19799. multiMaterial.id = parsedMultiMaterial.id;
  19800. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19801. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19802. var subMatId = parsedMultiMaterial.materials[matIndex];
  19803. if (subMatId) {
  19804. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19805. }
  19806. else {
  19807. multiMaterial.subMaterials.push(null);
  19808. }
  19809. }
  19810. return multiMaterial;
  19811. };
  19812. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19813. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19814. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19815. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19816. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19817. var parsedFlare = parsedLensFlareSystem.flares[index];
  19818. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19819. }
  19820. return lensFlareSystem;
  19821. };
  19822. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19823. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19824. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19825. if (parsedParticleSystem.textureName) {
  19826. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19827. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19828. }
  19829. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19830. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19831. particleSystem.minSize = parsedParticleSystem.minSize;
  19832. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19833. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19834. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19835. particleSystem.emitter = emitter;
  19836. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19837. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19838. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19839. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19840. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19841. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19842. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19843. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19844. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19845. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19846. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19847. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19848. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19849. particleSystem.start();
  19850. return particleSystem;
  19851. };
  19852. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19853. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19854. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19855. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19856. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19857. shadowGenerator.getShadowMap().renderList.push(mesh);
  19858. }
  19859. if (parsedShadowGenerator.usePoissonSampling) {
  19860. shadowGenerator.usePoissonSampling = true;
  19861. }
  19862. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19863. shadowGenerator.useVarianceShadowMap = true;
  19864. }
  19865. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19866. shadowGenerator.useBlurVarianceShadowMap = true;
  19867. if (parsedShadowGenerator.blurScale) {
  19868. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19869. }
  19870. if (parsedShadowGenerator.blurBoxOffset) {
  19871. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19872. }
  19873. }
  19874. if (parsedShadowGenerator.bias !== undefined) {
  19875. shadowGenerator.bias = parsedShadowGenerator.bias;
  19876. }
  19877. return shadowGenerator;
  19878. };
  19879. var parseAnimation = function (parsedAnimation) {
  19880. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19881. var dataType = parsedAnimation.dataType;
  19882. var keys = [];
  19883. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19884. var key = parsedAnimation.keys[index];
  19885. var data;
  19886. switch (dataType) {
  19887. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19888. data = key.values[0];
  19889. break;
  19890. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19891. data = BABYLON.Quaternion.FromArray(key.values);
  19892. break;
  19893. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19894. data = BABYLON.Matrix.FromArray(key.values);
  19895. break;
  19896. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19897. default:
  19898. data = BABYLON.Vector3.FromArray(key.values);
  19899. break;
  19900. }
  19901. keys.push({
  19902. frame: key.frame,
  19903. value: data
  19904. });
  19905. }
  19906. animation.setKeys(keys);
  19907. return animation;
  19908. };
  19909. var parseLight = function (parsedLight, scene) {
  19910. var light;
  19911. switch (parsedLight.type) {
  19912. case 0:
  19913. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19914. break;
  19915. case 1:
  19916. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19917. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19918. break;
  19919. case 2:
  19920. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19921. break;
  19922. case 3:
  19923. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19924. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19925. break;
  19926. }
  19927. light.id = parsedLight.id;
  19928. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19929. if (parsedLight.intensity !== undefined) {
  19930. light.intensity = parsedLight.intensity;
  19931. }
  19932. if (parsedLight.range) {
  19933. light.range = parsedLight.range;
  19934. }
  19935. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19936. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19937. if (parsedLight.excludedMeshesIds) {
  19938. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19939. }
  19940. // Parent
  19941. if (parsedLight.parentId) {
  19942. light._waitingParentId = parsedLight.parentId;
  19943. }
  19944. if (parsedLight.includedOnlyMeshesIds) {
  19945. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19946. }
  19947. // Animations
  19948. if (parsedLight.animations) {
  19949. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19950. var parsedAnimation = parsedLight.animations[animationIndex];
  19951. light.animations.push(parseAnimation(parsedAnimation));
  19952. }
  19953. }
  19954. if (parsedLight.autoAnimate) {
  19955. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19956. }
  19957. };
  19958. var parseCamera = function (parsedCamera, scene) {
  19959. var camera;
  19960. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19961. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19962. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19963. var alpha = parsedCamera.alpha;
  19964. var beta = parsedCamera.beta;
  19965. var radius = parsedCamera.radius;
  19966. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19967. var interaxial_distance = parsedCamera.interaxial_distance;
  19968. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19969. }
  19970. else {
  19971. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19972. }
  19973. }
  19974. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19975. interaxial_distance = parsedCamera.interaxial_distance;
  19976. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19977. }
  19978. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19979. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19980. }
  19981. else if (parsedCamera.type === "FollowCamera") {
  19982. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19983. camera.heightOffset = parsedCamera.heightOffset;
  19984. camera.radius = parsedCamera.radius;
  19985. camera.rotationOffset = parsedCamera.rotationOffset;
  19986. if (lockedTargetMesh)
  19987. camera.target = lockedTargetMesh;
  19988. }
  19989. else if (parsedCamera.type === "GamepadCamera") {
  19990. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19991. }
  19992. else if (parsedCamera.type === "TouchCamera") {
  19993. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19994. }
  19995. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19996. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19997. }
  19998. else if (parsedCamera.type === "WebVRFreeCamera") {
  19999. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  20000. }
  20001. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  20002. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  20003. }
  20004. else {
  20005. // Free Camera is the default value
  20006. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20007. }
  20008. // apply 3d rig, when found
  20009. if (parsedCamera.cameraRigMode) {
  20010. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20011. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20012. }
  20013. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20014. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20015. camera.lockedTarget = lockedTargetMesh;
  20016. }
  20017. camera.id = parsedCamera.id;
  20018. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20019. // Parent
  20020. if (parsedCamera.parentId) {
  20021. camera._waitingParentId = parsedCamera.parentId;
  20022. }
  20023. // Target
  20024. if (parsedCamera.target) {
  20025. if (camera.setTarget) {
  20026. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20027. }
  20028. else {
  20029. //For ArcRotate
  20030. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20031. }
  20032. }
  20033. else {
  20034. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20035. }
  20036. camera.fov = parsedCamera.fov;
  20037. camera.minZ = parsedCamera.minZ;
  20038. camera.maxZ = parsedCamera.maxZ;
  20039. camera.speed = parsedCamera.speed;
  20040. camera.inertia = parsedCamera.inertia;
  20041. camera.checkCollisions = parsedCamera.checkCollisions;
  20042. camera.applyGravity = parsedCamera.applyGravity;
  20043. if (parsedCamera.ellipsoid) {
  20044. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20045. }
  20046. // Animations
  20047. if (parsedCamera.animations) {
  20048. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20049. var parsedAnimation = parsedCamera.animations[animationIndex];
  20050. camera.animations.push(parseAnimation(parsedAnimation));
  20051. }
  20052. }
  20053. if (parsedCamera.autoAnimate) {
  20054. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20055. }
  20056. // Layer Mask
  20057. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20058. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20059. }
  20060. else {
  20061. camera.layerMask = 0x0FFFFFFF;
  20062. }
  20063. return camera;
  20064. };
  20065. var parseGeometry = function (parsedGeometry, scene) {
  20066. var id = parsedGeometry.id;
  20067. return scene.getGeometryByID(id);
  20068. };
  20069. var parseBox = function (parsedBox, scene) {
  20070. if (parseGeometry(parsedBox, scene)) {
  20071. return null; // null since geometry could be something else than a box...
  20072. }
  20073. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20074. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20075. scene.pushGeometry(box, true);
  20076. return box;
  20077. };
  20078. var parseSphere = function (parsedSphere, scene) {
  20079. if (parseGeometry(parsedSphere, scene)) {
  20080. return null; // null since geometry could be something else than a sphere...
  20081. }
  20082. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20083. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20084. scene.pushGeometry(sphere, true);
  20085. return sphere;
  20086. };
  20087. var parseCylinder = function (parsedCylinder, scene) {
  20088. if (parseGeometry(parsedCylinder, scene)) {
  20089. return null; // null since geometry could be something else than a cylinder...
  20090. }
  20091. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20092. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20093. scene.pushGeometry(cylinder, true);
  20094. return cylinder;
  20095. };
  20096. var parseTorus = function (parsedTorus, scene) {
  20097. if (parseGeometry(parsedTorus, scene)) {
  20098. return null; // null since geometry could be something else than a torus...
  20099. }
  20100. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20101. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20102. scene.pushGeometry(torus, true);
  20103. return torus;
  20104. };
  20105. var parseGround = function (parsedGround, scene) {
  20106. if (parseGeometry(parsedGround, scene)) {
  20107. return null; // null since geometry could be something else than a ground...
  20108. }
  20109. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20110. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20111. scene.pushGeometry(ground, true);
  20112. return ground;
  20113. };
  20114. var parsePlane = function (parsedPlane, scene) {
  20115. if (parseGeometry(parsedPlane, scene)) {
  20116. return null; // null since geometry could be something else than a plane...
  20117. }
  20118. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20119. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20120. scene.pushGeometry(plane, true);
  20121. return plane;
  20122. };
  20123. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20124. if (parseGeometry(parsedTorusKnot, scene)) {
  20125. return null; // null since geometry could be something else than a torusKnot...
  20126. }
  20127. 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);
  20128. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20129. scene.pushGeometry(torusKnot, true);
  20130. return torusKnot;
  20131. };
  20132. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20133. if (parseGeometry(parsedVertexData, scene)) {
  20134. return null; // null since geometry could be a primitive
  20135. }
  20136. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20137. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20138. if (parsedVertexData.delayLoadingFile) {
  20139. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20140. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20141. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20142. geometry._delayInfo = [];
  20143. if (parsedVertexData.hasUVs) {
  20144. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20145. }
  20146. if (parsedVertexData.hasUVs2) {
  20147. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20148. }
  20149. if (parsedVertexData.hasUVs3) {
  20150. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20151. }
  20152. if (parsedVertexData.hasUVs4) {
  20153. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20154. }
  20155. if (parsedVertexData.hasUVs5) {
  20156. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20157. }
  20158. if (parsedVertexData.hasUVs6) {
  20159. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20160. }
  20161. if (parsedVertexData.hasColors) {
  20162. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20163. }
  20164. if (parsedVertexData.hasMatricesIndices) {
  20165. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20166. }
  20167. if (parsedVertexData.hasMatricesWeights) {
  20168. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20169. }
  20170. geometry._delayLoadingFunction = importVertexData;
  20171. }
  20172. else {
  20173. importVertexData(parsedVertexData, geometry);
  20174. }
  20175. scene.pushGeometry(geometry, true);
  20176. return geometry;
  20177. };
  20178. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20179. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20180. mesh.id = parsedMesh.id;
  20181. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20182. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20183. if (parsedMesh.rotationQuaternion) {
  20184. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20185. }
  20186. else if (parsedMesh.rotation) {
  20187. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20188. }
  20189. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20190. if (parsedMesh.localMatrix) {
  20191. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20192. }
  20193. else if (parsedMesh.pivotMatrix) {
  20194. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20195. }
  20196. mesh.setEnabled(parsedMesh.isEnabled);
  20197. mesh.isVisible = parsedMesh.isVisible;
  20198. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20199. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20200. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20201. if (parsedMesh.applyFog !== undefined) {
  20202. mesh.applyFog = parsedMesh.applyFog;
  20203. }
  20204. if (parsedMesh.pickable !== undefined) {
  20205. mesh.isPickable = parsedMesh.pickable;
  20206. }
  20207. if (parsedMesh.alphaIndex !== undefined) {
  20208. mesh.alphaIndex = parsedMesh.alphaIndex;
  20209. }
  20210. mesh.receiveShadows = parsedMesh.receiveShadows;
  20211. mesh.billboardMode = parsedMesh.billboardMode;
  20212. if (parsedMesh.visibility !== undefined) {
  20213. mesh.visibility = parsedMesh.visibility;
  20214. }
  20215. mesh.checkCollisions = parsedMesh.checkCollisions;
  20216. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20217. // freezeWorldMatrix
  20218. if (parsedMesh.freezeWorldMatrix) {
  20219. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20220. }
  20221. // Parent
  20222. if (parsedMesh.parentId) {
  20223. mesh._waitingParentId = parsedMesh.parentId;
  20224. }
  20225. // Actions
  20226. if (parsedMesh.actions !== undefined) {
  20227. mesh._waitingActions = parsedMesh.actions;
  20228. }
  20229. // Geometry
  20230. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20231. if (parsedMesh.delayLoadingFile) {
  20232. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20233. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20234. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20235. if (parsedMesh._binaryInfo) {
  20236. mesh._binaryInfo = parsedMesh._binaryInfo;
  20237. }
  20238. mesh._delayInfo = [];
  20239. if (parsedMesh.hasUVs) {
  20240. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20241. }
  20242. if (parsedMesh.hasUVs2) {
  20243. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20244. }
  20245. if (parsedMesh.hasUVs3) {
  20246. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20247. }
  20248. if (parsedMesh.hasUVs4) {
  20249. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20250. }
  20251. if (parsedMesh.hasUVs5) {
  20252. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20253. }
  20254. if (parsedMesh.hasUVs6) {
  20255. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20256. }
  20257. if (parsedMesh.hasColors) {
  20258. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20259. }
  20260. if (parsedMesh.hasMatricesIndices) {
  20261. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20262. }
  20263. if (parsedMesh.hasMatricesWeights) {
  20264. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20265. }
  20266. mesh._delayLoadingFunction = importGeometry;
  20267. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20268. mesh._checkDelayState();
  20269. }
  20270. }
  20271. else {
  20272. importGeometry(parsedMesh, mesh);
  20273. }
  20274. // Material
  20275. if (parsedMesh.materialId) {
  20276. mesh.setMaterialByID(parsedMesh.materialId);
  20277. }
  20278. else {
  20279. mesh.material = null;
  20280. }
  20281. // Skeleton
  20282. if (parsedMesh.skeletonId > -1) {
  20283. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20284. }
  20285. // Physics
  20286. if (parsedMesh.physicsImpostor) {
  20287. if (!scene.isPhysicsEnabled()) {
  20288. scene.enablePhysics();
  20289. }
  20290. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20291. }
  20292. // Animations
  20293. if (parsedMesh.animations) {
  20294. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20295. var parsedAnimation = parsedMesh.animations[animationIndex];
  20296. mesh.animations.push(parseAnimation(parsedAnimation));
  20297. }
  20298. }
  20299. if (parsedMesh.autoAnimate) {
  20300. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20301. }
  20302. // Layer Mask
  20303. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20304. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20305. }
  20306. else {
  20307. mesh.layerMask = 0x0FFFFFFF;
  20308. }
  20309. // Instances
  20310. if (parsedMesh.instances) {
  20311. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20312. var parsedInstance = parsedMesh.instances[index];
  20313. var instance = mesh.createInstance(parsedInstance.name);
  20314. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20315. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20316. if (parsedInstance.rotationQuaternion) {
  20317. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20318. }
  20319. else if (parsedInstance.rotation) {
  20320. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20321. }
  20322. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20323. instance.checkCollisions = mesh.checkCollisions;
  20324. if (parsedMesh.animations) {
  20325. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20326. parsedAnimation = parsedMesh.animations[animationIndex];
  20327. instance.animations.push(parseAnimation(parsedAnimation));
  20328. }
  20329. }
  20330. }
  20331. }
  20332. return mesh;
  20333. };
  20334. var parseActions = function (parsedActions, object, scene) {
  20335. var actionManager = new BABYLON.ActionManager(scene);
  20336. if (object === null)
  20337. scene.actionManager = actionManager;
  20338. else
  20339. object.actionManager = actionManager;
  20340. // instanciate a new object
  20341. var instanciate = function (name, params) {
  20342. var newInstance = Object.create(BABYLON[name].prototype);
  20343. newInstance.constructor.apply(newInstance, params);
  20344. return newInstance;
  20345. };
  20346. var parseParameter = function (name, value, target, propertyPath) {
  20347. if (propertyPath === null) {
  20348. // String, boolean or float
  20349. var floatValue = parseFloat(value);
  20350. if (value === "true" || value === "false")
  20351. return value === "true";
  20352. else
  20353. return isNaN(floatValue) ? value : floatValue;
  20354. }
  20355. var effectiveTarget = propertyPath.split(".");
  20356. var values = value.split(",");
  20357. // Get effective Target
  20358. for (var i = 0; i < effectiveTarget.length; i++) {
  20359. target = target[effectiveTarget[i]];
  20360. }
  20361. // Return appropriate value with its type
  20362. if (typeof (target) === "boolean")
  20363. return values[0] === "true";
  20364. if (typeof (target) === "string")
  20365. return values[0];
  20366. // Parameters with multiple values such as Vector3 etc.
  20367. var split = new Array();
  20368. for (var i = 0; i < values.length; i++)
  20369. split.push(parseFloat(values[i]));
  20370. if (target instanceof BABYLON.Vector3)
  20371. return BABYLON.Vector3.FromArray(split);
  20372. if (target instanceof BABYLON.Vector4)
  20373. return BABYLON.Vector4.FromArray(split);
  20374. if (target instanceof BABYLON.Color3)
  20375. return BABYLON.Color3.FromArray(split);
  20376. if (target instanceof BABYLON.Color4)
  20377. return BABYLON.Color4.FromArray(split);
  20378. return parseFloat(values[0]);
  20379. };
  20380. // traverse graph per trigger
  20381. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20382. if (combineArray === void 0) { combineArray = null; }
  20383. if (parsedAction.detached)
  20384. return;
  20385. var parameters = new Array();
  20386. var target = null;
  20387. var propertyPath = null;
  20388. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20389. // Parameters
  20390. if (parsedAction.type === 2)
  20391. parameters.push(actionManager);
  20392. else
  20393. parameters.push(trigger);
  20394. if (combine) {
  20395. var actions = new Array();
  20396. for (var j = 0; j < parsedAction.combine.length; j++) {
  20397. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20398. }
  20399. parameters.push(actions);
  20400. }
  20401. else {
  20402. for (var i = 0; i < parsedAction.properties.length; i++) {
  20403. var value = parsedAction.properties[i].value;
  20404. var name = parsedAction.properties[i].name;
  20405. var targetType = parsedAction.properties[i].targetType;
  20406. if (name === "target")
  20407. if (targetType !== null && targetType === "SceneProperties")
  20408. value = target = scene;
  20409. else
  20410. value = target = scene.getNodeByName(value);
  20411. else if (name === "parent")
  20412. value = scene.getNodeByName(value);
  20413. else if (name === "sound")
  20414. value = scene.getSoundByName(value);
  20415. else if (name !== "propertyPath") {
  20416. if (parsedAction.type === 2 && name === "operator")
  20417. value = BABYLON.ValueCondition[value];
  20418. else
  20419. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20420. }
  20421. else {
  20422. propertyPath = value;
  20423. }
  20424. parameters.push(value);
  20425. }
  20426. }
  20427. if (combineArray === null) {
  20428. parameters.push(condition);
  20429. }
  20430. else {
  20431. parameters.push(null);
  20432. }
  20433. // If interpolate value action
  20434. if (parsedAction.name === "InterpolateValueAction") {
  20435. var param = parameters[parameters.length - 2];
  20436. parameters[parameters.length - 1] = param;
  20437. parameters[parameters.length - 2] = condition;
  20438. }
  20439. // Action or condition(s) and not CombineAction
  20440. var newAction = instanciate(parsedAction.name, parameters);
  20441. if (combineArray === null) {
  20442. if (newAction instanceof BABYLON.Condition) {
  20443. condition = newAction;
  20444. newAction = action;
  20445. }
  20446. else {
  20447. condition = null;
  20448. if (action)
  20449. action.then(newAction);
  20450. else
  20451. actionManager.registerAction(newAction);
  20452. }
  20453. }
  20454. else {
  20455. combineArray.push(newAction);
  20456. }
  20457. for (var i = 0; i < parsedAction.children.length; i++)
  20458. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20459. };
  20460. // triggers
  20461. for (var i = 0; i < parsedActions.children.length; i++) {
  20462. var triggerParams;
  20463. var trigger = parsedActions.children[i];
  20464. if (trigger.properties.length > 0) {
  20465. var param = trigger.properties[0].value;
  20466. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20467. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20468. }
  20469. else
  20470. triggerParams = BABYLON.ActionManager[trigger.name];
  20471. for (var j = 0; j < trigger.children.length; j++) {
  20472. if (!trigger.detached)
  20473. traverse(trigger.children[j], triggerParams, null, null);
  20474. }
  20475. }
  20476. };
  20477. var parseSound = function (parsedSound, scene, rootUrl) {
  20478. var soundName = parsedSound.name;
  20479. var soundUrl = rootUrl + soundName;
  20480. var options = {
  20481. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20482. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20483. rolloffFactor: parsedSound.rolloffFactor,
  20484. refDistance: parsedSound.refDistance,
  20485. distanceModel: parsedSound.distanceModel,
  20486. playbackRate: parsedSound.playbackRate
  20487. };
  20488. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20489. scene._addPendingData(newSound);
  20490. if (parsedSound.position) {
  20491. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20492. newSound.setPosition(soundPosition);
  20493. }
  20494. if (parsedSound.isDirectional) {
  20495. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20496. if (parsedSound.localDirectionToMesh) {
  20497. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20498. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20499. }
  20500. }
  20501. if (parsedSound.connectedMeshId) {
  20502. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20503. if (connectedMesh) {
  20504. newSound.attachToMesh(connectedMesh);
  20505. }
  20506. }
  20507. };
  20508. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20509. names = (names instanceof Array) ? names : [names];
  20510. for (var i in names) {
  20511. if (mesh.name === names[i]) {
  20512. hierarchyIds.push(mesh.id);
  20513. return true;
  20514. }
  20515. }
  20516. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20517. hierarchyIds.push(mesh.id);
  20518. return true;
  20519. }
  20520. return false;
  20521. };
  20522. var importVertexData = function (parsedVertexData, geometry) {
  20523. var vertexData = new BABYLON.VertexData();
  20524. // positions
  20525. var positions = parsedVertexData.positions;
  20526. if (positions) {
  20527. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20528. }
  20529. // normals
  20530. var normals = parsedVertexData.normals;
  20531. if (normals) {
  20532. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20533. }
  20534. // uvs
  20535. var uvs = parsedVertexData.uvs;
  20536. if (uvs) {
  20537. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20538. }
  20539. // uv2s
  20540. var uv2s = parsedVertexData.uv2s;
  20541. if (uv2s) {
  20542. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20543. }
  20544. // uv3s
  20545. var uv3s = parsedVertexData.uv3s;
  20546. if (uv3s) {
  20547. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20548. }
  20549. // uv4s
  20550. var uv4s = parsedVertexData.uv4s;
  20551. if (uv4s) {
  20552. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20553. }
  20554. // uv5s
  20555. var uv5s = parsedVertexData.uv5s;
  20556. if (uv5s) {
  20557. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20558. }
  20559. // uv6s
  20560. var uv6s = parsedVertexData.uv6s;
  20561. if (uv6s) {
  20562. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20563. }
  20564. // colors
  20565. var colors = parsedVertexData.colors;
  20566. if (colors) {
  20567. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20568. }
  20569. // matricesIndices
  20570. var matricesIndices = parsedVertexData.matricesIndices;
  20571. if (matricesIndices) {
  20572. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20573. }
  20574. // matricesWeights
  20575. var matricesWeights = parsedVertexData.matricesWeights;
  20576. if (matricesWeights) {
  20577. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20578. }
  20579. // indices
  20580. var indices = parsedVertexData.indices;
  20581. if (indices) {
  20582. vertexData.indices = indices;
  20583. }
  20584. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20585. };
  20586. var importGeometry = function (parsedGeometry, mesh) {
  20587. var scene = mesh.getScene();
  20588. // Geometry
  20589. var geometryId = parsedGeometry.geometryId;
  20590. if (geometryId) {
  20591. var geometry = scene.getGeometryByID(geometryId);
  20592. if (geometry) {
  20593. geometry.applyToMesh(mesh);
  20594. }
  20595. }
  20596. else if (parsedGeometry instanceof ArrayBuffer) {
  20597. var binaryInfo = mesh._binaryInfo;
  20598. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20599. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20600. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20601. }
  20602. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20603. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20604. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20605. }
  20606. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20607. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20608. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20609. }
  20610. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20611. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20612. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20613. }
  20614. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20615. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20616. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20617. }
  20618. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20619. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20620. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20621. }
  20622. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20623. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20624. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20625. }
  20626. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20627. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20628. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20629. }
  20630. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20631. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20632. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20633. }
  20634. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20635. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20637. }
  20638. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20639. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20641. }
  20642. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20643. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20644. mesh.setIndices(indicesData);
  20645. }
  20646. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20647. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20648. mesh.subMeshes = [];
  20649. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20650. var materialIndex = subMeshesData[(i * 5) + 0];
  20651. var verticesStart = subMeshesData[(i * 5) + 1];
  20652. var verticesCount = subMeshesData[(i * 5) + 2];
  20653. var indexStart = subMeshesData[(i * 5) + 3];
  20654. var indexCount = subMeshesData[(i * 5) + 4];
  20655. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20656. }
  20657. }
  20658. }
  20659. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20660. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20661. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20662. if (parsedGeometry.uvs) {
  20663. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20664. }
  20665. if (parsedGeometry.uvs2) {
  20666. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20667. }
  20668. if (parsedGeometry.uvs3) {
  20669. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20670. }
  20671. if (parsedGeometry.uvs4) {
  20672. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20673. }
  20674. if (parsedGeometry.uvs5) {
  20675. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20676. }
  20677. if (parsedGeometry.uvs6) {
  20678. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20679. }
  20680. if (parsedGeometry.colors) {
  20681. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20682. }
  20683. if (parsedGeometry.matricesIndices) {
  20684. if (!parsedGeometry.matricesIndices._isExpanded) {
  20685. var floatIndices = [];
  20686. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20687. var matricesIndex = parsedGeometry.matricesIndices[i];
  20688. floatIndices.push(matricesIndex & 0x000000FF);
  20689. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20690. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20691. floatIndices.push(matricesIndex >> 24);
  20692. }
  20693. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20694. }
  20695. else {
  20696. delete parsedGeometry.matricesIndices._isExpanded;
  20697. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20698. }
  20699. }
  20700. if (parsedGeometry.matricesWeights) {
  20701. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20702. }
  20703. mesh.setIndices(parsedGeometry.indices);
  20704. }
  20705. // SubMeshes
  20706. if (parsedGeometry.subMeshes) {
  20707. mesh.subMeshes = [];
  20708. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20709. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20710. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20711. }
  20712. }
  20713. // Flat shading
  20714. if (mesh._shouldGenerateFlatShading) {
  20715. mesh.convertToFlatShadedMesh();
  20716. delete mesh._shouldGenerateFlatShading;
  20717. }
  20718. // Update
  20719. mesh.computeWorldMatrix(true);
  20720. // Octree
  20721. if (scene._selectionOctree) {
  20722. scene._selectionOctree.addMesh(mesh);
  20723. }
  20724. };
  20725. BABYLON.SceneLoader.RegisterPlugin({
  20726. extensions: ".babylon",
  20727. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20728. var parsedData = JSON.parse(data);
  20729. var loadedSkeletonsIds = [];
  20730. var loadedMaterialsIds = [];
  20731. var hierarchyIds = [];
  20732. for (var index = 0; index < parsedData.meshes.length; index++) {
  20733. var parsedMesh = parsedData.meshes[index];
  20734. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20735. if (meshesNames instanceof Array) {
  20736. // Remove found mesh name from list.
  20737. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20738. }
  20739. //Geometry?
  20740. if (parsedMesh.geometryId) {
  20741. //does the file contain geometries?
  20742. if (parsedData.geometries) {
  20743. //find the correct geometry and add it to the scene
  20744. var found = false;
  20745. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20746. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20747. return;
  20748. }
  20749. else {
  20750. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20751. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20752. switch (geometryType) {
  20753. case "boxes":
  20754. parseBox(parsedGeometryData, scene);
  20755. break;
  20756. case "spheres":
  20757. parseSphere(parsedGeometryData, scene);
  20758. break;
  20759. case "cylinders":
  20760. parseCylinder(parsedGeometryData, scene);
  20761. break;
  20762. case "toruses":
  20763. parseTorus(parsedGeometryData, scene);
  20764. break;
  20765. case "grounds":
  20766. parseGround(parsedGeometryData, scene);
  20767. break;
  20768. case "planes":
  20769. parsePlane(parsedGeometryData, scene);
  20770. break;
  20771. case "torusKnots":
  20772. parseTorusKnot(parsedGeometryData, scene);
  20773. break;
  20774. case "vertexData":
  20775. parseVertexData(parsedGeometryData, scene, rootUrl);
  20776. break;
  20777. }
  20778. found = true;
  20779. }
  20780. });
  20781. }
  20782. });
  20783. if (!found) {
  20784. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20785. }
  20786. }
  20787. }
  20788. // Material ?
  20789. if (parsedMesh.materialId) {
  20790. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20791. if (!materialFound && parsedData.multiMaterials) {
  20792. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20793. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20794. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20795. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20796. var subMatId = parsedMultiMaterial.materials[matIndex];
  20797. loadedMaterialsIds.push(subMatId);
  20798. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20799. }
  20800. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20801. parseMultiMaterial(parsedMultiMaterial, scene);
  20802. materialFound = true;
  20803. break;
  20804. }
  20805. }
  20806. }
  20807. if (!materialFound) {
  20808. loadedMaterialsIds.push(parsedMesh.materialId);
  20809. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20810. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20811. }
  20812. }
  20813. }
  20814. // Skeleton ?
  20815. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20816. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20817. if (!skeletonAlreadyLoaded) {
  20818. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20819. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20820. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20821. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20822. loadedSkeletonsIds.push(parsedSkeleton.id);
  20823. }
  20824. }
  20825. }
  20826. }
  20827. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20828. meshes.push(mesh);
  20829. }
  20830. }
  20831. // Connecting parents
  20832. for (index = 0; index < scene.meshes.length; index++) {
  20833. var currentMesh = scene.meshes[index];
  20834. if (currentMesh._waitingParentId) {
  20835. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20836. currentMesh._waitingParentId = undefined;
  20837. }
  20838. }
  20839. // freeze world matrix application
  20840. for (index = 0; index < scene.meshes.length; index++) {
  20841. var currentMesh = scene.meshes[index];
  20842. if (currentMesh._waitingFreezeWorldMatrix) {
  20843. currentMesh.freezeWorldMatrix();
  20844. currentMesh._waitingFreezeWorldMatrix = undefined;
  20845. }
  20846. }
  20847. // Particles
  20848. if (parsedData.particleSystems) {
  20849. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20850. var parsedParticleSystem = parsedData.particleSystems[index];
  20851. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20852. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20853. }
  20854. }
  20855. }
  20856. return true;
  20857. },
  20858. load: function (scene, data, rootUrl) {
  20859. var parsedData = JSON.parse(data);
  20860. // Scene
  20861. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20862. scene.autoClear = parsedData.autoClear;
  20863. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20864. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20865. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20866. // Fog
  20867. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20868. scene.fogMode = parsedData.fogMode;
  20869. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20870. scene.fogStart = parsedData.fogStart;
  20871. scene.fogEnd = parsedData.fogEnd;
  20872. scene.fogDensity = parsedData.fogDensity;
  20873. }
  20874. // Lights
  20875. for (var index = 0; index < parsedData.lights.length; index++) {
  20876. var parsedLight = parsedData.lights[index];
  20877. parseLight(parsedLight, scene);
  20878. }
  20879. // Materials
  20880. if (parsedData.materials) {
  20881. for (index = 0; index < parsedData.materials.length; index++) {
  20882. var parsedMaterial = parsedData.materials[index];
  20883. parseMaterial(parsedMaterial, scene, rootUrl);
  20884. }
  20885. }
  20886. if (parsedData.multiMaterials) {
  20887. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20888. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20889. parseMultiMaterial(parsedMultiMaterial, scene);
  20890. }
  20891. }
  20892. // Skeletons
  20893. if (parsedData.skeletons) {
  20894. for (index = 0; index < parsedData.skeletons.length; index++) {
  20895. var parsedSkeleton = parsedData.skeletons[index];
  20896. parseSkeleton(parsedSkeleton, scene);
  20897. }
  20898. }
  20899. // Geometries
  20900. var geometries = parsedData.geometries;
  20901. if (geometries) {
  20902. // Boxes
  20903. var boxes = geometries.boxes;
  20904. if (boxes) {
  20905. for (index = 0; index < boxes.length; index++) {
  20906. var parsedBox = boxes[index];
  20907. parseBox(parsedBox, scene);
  20908. }
  20909. }
  20910. // Spheres
  20911. var spheres = geometries.spheres;
  20912. if (spheres) {
  20913. for (index = 0; index < spheres.length; index++) {
  20914. var parsedSphere = spheres[index];
  20915. parseSphere(parsedSphere, scene);
  20916. }
  20917. }
  20918. // Cylinders
  20919. var cylinders = geometries.cylinders;
  20920. if (cylinders) {
  20921. for (index = 0; index < cylinders.length; index++) {
  20922. var parsedCylinder = cylinders[index];
  20923. parseCylinder(parsedCylinder, scene);
  20924. }
  20925. }
  20926. // Toruses
  20927. var toruses = geometries.toruses;
  20928. if (toruses) {
  20929. for (index = 0; index < toruses.length; index++) {
  20930. var parsedTorus = toruses[index];
  20931. parseTorus(parsedTorus, scene);
  20932. }
  20933. }
  20934. // Grounds
  20935. var grounds = geometries.grounds;
  20936. if (grounds) {
  20937. for (index = 0; index < grounds.length; index++) {
  20938. var parsedGround = grounds[index];
  20939. parseGround(parsedGround, scene);
  20940. }
  20941. }
  20942. // Planes
  20943. var planes = geometries.planes;
  20944. if (planes) {
  20945. for (index = 0; index < planes.length; index++) {
  20946. var parsedPlane = planes[index];
  20947. parsePlane(parsedPlane, scene);
  20948. }
  20949. }
  20950. // TorusKnots
  20951. var torusKnots = geometries.torusKnots;
  20952. if (torusKnots) {
  20953. for (index = 0; index < torusKnots.length; index++) {
  20954. var parsedTorusKnot = torusKnots[index];
  20955. parseTorusKnot(parsedTorusKnot, scene);
  20956. }
  20957. }
  20958. // VertexData
  20959. var vertexData = geometries.vertexData;
  20960. if (vertexData) {
  20961. for (index = 0; index < vertexData.length; index++) {
  20962. var parsedVertexData = vertexData[index];
  20963. parseVertexData(parsedVertexData, scene, rootUrl);
  20964. }
  20965. }
  20966. }
  20967. // Meshes
  20968. for (index = 0; index < parsedData.meshes.length; index++) {
  20969. var parsedMesh = parsedData.meshes[index];
  20970. parseMesh(parsedMesh, scene, rootUrl);
  20971. }
  20972. // Cameras
  20973. for (index = 0; index < parsedData.cameras.length; index++) {
  20974. var parsedCamera = parsedData.cameras[index];
  20975. parseCamera(parsedCamera, scene);
  20976. }
  20977. if (parsedData.activeCameraID) {
  20978. scene.setActiveCameraByID(parsedData.activeCameraID);
  20979. }
  20980. // Browsing all the graph to connect the dots
  20981. for (index = 0; index < scene.cameras.length; index++) {
  20982. var camera = scene.cameras[index];
  20983. if (camera._waitingParentId) {
  20984. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20985. camera._waitingParentId = undefined;
  20986. }
  20987. }
  20988. for (index = 0; index < scene.lights.length; index++) {
  20989. var light = scene.lights[index];
  20990. if (light._waitingParentId) {
  20991. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20992. light._waitingParentId = undefined;
  20993. }
  20994. }
  20995. // Sounds
  20996. if (parsedData.sounds) {
  20997. for (index = 0; index < parsedData.sounds.length; index++) {
  20998. var parsedSound = parsedData.sounds[index];
  20999. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21000. parseSound(parsedSound, scene, rootUrl);
  21001. }
  21002. else {
  21003. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21004. }
  21005. }
  21006. }
  21007. // Connect parents & children and parse actions
  21008. for (index = 0; index < scene.meshes.length; index++) {
  21009. var mesh = scene.meshes[index];
  21010. if (mesh._waitingParentId) {
  21011. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21012. mesh._waitingParentId = undefined;
  21013. }
  21014. if (mesh._waitingActions) {
  21015. parseActions(mesh._waitingActions, mesh, scene);
  21016. mesh._waitingActions = undefined;
  21017. }
  21018. }
  21019. // freeze world matrix application
  21020. for (index = 0; index < scene.meshes.length; index++) {
  21021. var currentMesh = scene.meshes[index];
  21022. if (currentMesh._waitingFreezeWorldMatrix) {
  21023. currentMesh.freezeWorldMatrix();
  21024. currentMesh._waitingFreezeWorldMatrix = undefined;
  21025. }
  21026. }
  21027. // Particles Systems
  21028. if (parsedData.particleSystems) {
  21029. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21030. var parsedParticleSystem = parsedData.particleSystems[index];
  21031. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  21032. }
  21033. }
  21034. // Lens flares
  21035. if (parsedData.lensFlareSystems) {
  21036. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  21037. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21038. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  21039. }
  21040. }
  21041. // Shadows
  21042. if (parsedData.shadowGenerators) {
  21043. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  21044. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21045. parseShadowGenerator(parsedShadowGenerator, scene);
  21046. }
  21047. }
  21048. // Actions (scene)
  21049. if (parsedData.actions) {
  21050. parseActions(parsedData.actions, null, scene);
  21051. }
  21052. // Finish
  21053. return true;
  21054. }
  21055. });
  21056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21057. })(BABYLON || (BABYLON = {}));
  21058. var BABYLON;
  21059. (function (BABYLON) {
  21060. var SpriteManager = (function () {
  21061. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21063. this.name = name;
  21064. this.cellSize = cellSize;
  21065. this.sprites = new Array();
  21066. this.renderingGroupId = 0;
  21067. this.layerMask = 0x0FFFFFFF;
  21068. this.fogEnabled = true;
  21069. this._vertexDeclaration = [4, 4, 4, 4];
  21070. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21071. this._capacity = capacity;
  21072. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21073. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21074. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21075. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21076. this._scene = scene;
  21077. this._scene.spriteManagers.push(this);
  21078. // VBO
  21079. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21080. var indices = [];
  21081. var index = 0;
  21082. for (var count = 0; count < capacity; count++) {
  21083. indices.push(index);
  21084. indices.push(index + 1);
  21085. indices.push(index + 2);
  21086. indices.push(index);
  21087. indices.push(index + 2);
  21088. indices.push(index + 3);
  21089. index += 4;
  21090. }
  21091. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21092. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21093. // Effects
  21094. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21095. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21096. }
  21097. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21098. var arrayOffset = index * 16;
  21099. if (offsetX === 0)
  21100. offsetX = this._epsilon;
  21101. else if (offsetX === 1)
  21102. offsetX = 1 - this._epsilon;
  21103. if (offsetY === 0)
  21104. offsetY = this._epsilon;
  21105. else if (offsetY === 1)
  21106. offsetY = 1 - this._epsilon;
  21107. this._vertices[arrayOffset] = sprite.position.x;
  21108. this._vertices[arrayOffset + 1] = sprite.position.y;
  21109. this._vertices[arrayOffset + 2] = sprite.position.z;
  21110. this._vertices[arrayOffset + 3] = sprite.angle;
  21111. this._vertices[arrayOffset + 4] = sprite.width;
  21112. this._vertices[arrayOffset + 5] = sprite.height;
  21113. this._vertices[arrayOffset + 6] = offsetX;
  21114. this._vertices[arrayOffset + 7] = offsetY;
  21115. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21116. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21117. var offset = (sprite.cellIndex / rowSize) >> 0;
  21118. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21119. this._vertices[arrayOffset + 11] = offset;
  21120. // Color
  21121. this._vertices[arrayOffset + 12] = sprite.color.r;
  21122. this._vertices[arrayOffset + 13] = sprite.color.g;
  21123. this._vertices[arrayOffset + 14] = sprite.color.b;
  21124. this._vertices[arrayOffset + 15] = sprite.color.a;
  21125. };
  21126. SpriteManager.prototype.render = function () {
  21127. // Check
  21128. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21129. return;
  21130. var engine = this._scene.getEngine();
  21131. var baseSize = this._spriteTexture.getBaseSize();
  21132. // Sprites
  21133. var deltaTime = engine.getDeltaTime();
  21134. var max = Math.min(this._capacity, this.sprites.length);
  21135. var rowSize = baseSize.width / this.cellSize;
  21136. var offset = 0;
  21137. for (var index = 0; index < max; index++) {
  21138. var sprite = this.sprites[index];
  21139. if (!sprite) {
  21140. continue;
  21141. }
  21142. sprite._animate(deltaTime);
  21143. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21144. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21145. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21146. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21147. }
  21148. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21149. // Render
  21150. var effect = this._effectBase;
  21151. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21152. effect = this._effectFog;
  21153. }
  21154. engine.enableEffect(effect);
  21155. var viewMatrix = this._scene.getViewMatrix();
  21156. effect.setTexture("diffuseSampler", this._spriteTexture);
  21157. effect.setMatrix("view", viewMatrix);
  21158. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21159. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21160. // Fog
  21161. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21162. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21163. effect.setColor3("vFogColor", this._scene.fogColor);
  21164. }
  21165. // VBOs
  21166. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21167. // Draw order
  21168. engine.setDepthFunctionToLessOrEqual();
  21169. effect.setBool("alphaTest", true);
  21170. engine.setColorWrite(false);
  21171. engine.draw(true, 0, max * 6);
  21172. engine.setColorWrite(true);
  21173. effect.setBool("alphaTest", false);
  21174. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21175. engine.draw(true, 0, max * 6);
  21176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21177. };
  21178. SpriteManager.prototype.dispose = function () {
  21179. if (this._vertexBuffer) {
  21180. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21181. this._vertexBuffer = null;
  21182. }
  21183. if (this._indexBuffer) {
  21184. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21185. this._indexBuffer = null;
  21186. }
  21187. if (this._spriteTexture) {
  21188. this._spriteTexture.dispose();
  21189. this._spriteTexture = null;
  21190. }
  21191. // Remove from scene
  21192. var index = this._scene.spriteManagers.indexOf(this);
  21193. this._scene.spriteManagers.splice(index, 1);
  21194. // Callback
  21195. if (this.onDispose) {
  21196. this.onDispose();
  21197. }
  21198. };
  21199. return SpriteManager;
  21200. })();
  21201. BABYLON.SpriteManager = SpriteManager;
  21202. })(BABYLON || (BABYLON = {}));
  21203. var BABYLON;
  21204. (function (BABYLON) {
  21205. var Sprite = (function () {
  21206. function Sprite(name, manager) {
  21207. this.name = name;
  21208. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21209. this.width = 1.0;
  21210. this.height = 1.0;
  21211. this.angle = 0;
  21212. this.cellIndex = 0;
  21213. this.invertU = 0;
  21214. this.invertV = 0;
  21215. this.animations = new Array();
  21216. this._animationStarted = false;
  21217. this._loopAnimation = false;
  21218. this._fromIndex = 0;
  21219. this._toIndex = 0;
  21220. this._delay = 0;
  21221. this._direction = 1;
  21222. this._frameCount = 0;
  21223. this._time = 0;
  21224. this._manager = manager;
  21225. this._manager.sprites.push(this);
  21226. this.position = BABYLON.Vector3.Zero();
  21227. }
  21228. Object.defineProperty(Sprite.prototype, "size", {
  21229. get: function () {
  21230. return this.width;
  21231. },
  21232. set: function (value) {
  21233. this.width = value;
  21234. this.height = value;
  21235. },
  21236. enumerable: true,
  21237. configurable: true
  21238. });
  21239. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21240. this._fromIndex = from;
  21241. this._toIndex = to;
  21242. this._loopAnimation = loop;
  21243. this._delay = delay;
  21244. this._animationStarted = true;
  21245. this._direction = from < to ? 1 : -1;
  21246. this.cellIndex = from;
  21247. this._time = 0;
  21248. };
  21249. Sprite.prototype.stopAnimation = function () {
  21250. this._animationStarted = false;
  21251. };
  21252. Sprite.prototype._animate = function (deltaTime) {
  21253. if (!this._animationStarted)
  21254. return;
  21255. this._time += deltaTime;
  21256. if (this._time > this._delay) {
  21257. this._time = this._time % this._delay;
  21258. this.cellIndex += this._direction;
  21259. if (this.cellIndex == this._toIndex) {
  21260. if (this._loopAnimation) {
  21261. this.cellIndex = this._fromIndex;
  21262. }
  21263. else {
  21264. this._animationStarted = false;
  21265. if (this.disposeWhenFinishedAnimating) {
  21266. this.dispose();
  21267. }
  21268. }
  21269. }
  21270. }
  21271. };
  21272. Sprite.prototype.dispose = function () {
  21273. for (var i = 0; i < this._manager.sprites.length; i++) {
  21274. if (this._manager.sprites[i] == this) {
  21275. this._manager.sprites.splice(i, 1);
  21276. }
  21277. }
  21278. };
  21279. return Sprite;
  21280. })();
  21281. BABYLON.Sprite = Sprite;
  21282. })(BABYLON || (BABYLON = {}));
  21283. var BABYLON;
  21284. (function (BABYLON) {
  21285. var Layer = (function () {
  21286. function Layer(name, imgUrl, scene, isBackground, color) {
  21287. this.name = name;
  21288. this._vertexDeclaration = [2];
  21289. this._vertexStrideSize = 2 * 4;
  21290. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21291. this.isBackground = isBackground === undefined ? true : isBackground;
  21292. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21293. this._scene = scene;
  21294. this._scene.layers.push(this);
  21295. // VBO
  21296. var vertices = [];
  21297. vertices.push(1, 1);
  21298. vertices.push(-1, 1);
  21299. vertices.push(-1, -1);
  21300. vertices.push(1, -1);
  21301. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21302. // Indices
  21303. var indices = [];
  21304. indices.push(0);
  21305. indices.push(1);
  21306. indices.push(2);
  21307. indices.push(0);
  21308. indices.push(2);
  21309. indices.push(3);
  21310. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21311. // Effects
  21312. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21313. }
  21314. Layer.prototype.render = function () {
  21315. // Check
  21316. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21317. return;
  21318. var engine = this._scene.getEngine();
  21319. // Render
  21320. engine.enableEffect(this._effect);
  21321. engine.setState(false);
  21322. // Texture
  21323. this._effect.setTexture("textureSampler", this.texture);
  21324. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21325. // Color
  21326. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21327. // VBOs
  21328. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21329. // Draw order
  21330. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21331. engine.draw(true, 0, 6);
  21332. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21333. };
  21334. Layer.prototype.dispose = function () {
  21335. if (this._vertexBuffer) {
  21336. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21337. this._vertexBuffer = null;
  21338. }
  21339. if (this._indexBuffer) {
  21340. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21341. this._indexBuffer = null;
  21342. }
  21343. if (this.texture) {
  21344. this.texture.dispose();
  21345. this.texture = null;
  21346. }
  21347. // Remove from scene
  21348. var index = this._scene.layers.indexOf(this);
  21349. this._scene.layers.splice(index, 1);
  21350. // Callback
  21351. if (this.onDispose) {
  21352. this.onDispose();
  21353. }
  21354. };
  21355. return Layer;
  21356. })();
  21357. BABYLON.Layer = Layer;
  21358. })(BABYLON || (BABYLON = {}));
  21359. var BABYLON;
  21360. (function (BABYLON) {
  21361. var Particle = (function () {
  21362. function Particle() {
  21363. this.position = BABYLON.Vector3.Zero();
  21364. this.direction = BABYLON.Vector3.Zero();
  21365. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21366. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21367. this.lifeTime = 1.0;
  21368. this.age = 0;
  21369. this.size = 0;
  21370. this.angle = 0;
  21371. this.angularSpeed = 0;
  21372. }
  21373. Particle.prototype.copyTo = function (other) {
  21374. other.position.copyFrom(this.position);
  21375. other.direction.copyFrom(this.direction);
  21376. other.color.copyFrom(this.color);
  21377. other.colorStep.copyFrom(this.colorStep);
  21378. other.lifeTime = this.lifeTime;
  21379. other.age = this.age;
  21380. other.size = this.size;
  21381. other.angle = this.angle;
  21382. other.angularSpeed = this.angularSpeed;
  21383. };
  21384. return Particle;
  21385. })();
  21386. BABYLON.Particle = Particle;
  21387. })(BABYLON || (BABYLON = {}));
  21388. var BABYLON;
  21389. (function (BABYLON) {
  21390. var randomNumber = function (min, max) {
  21391. if (min === max) {
  21392. return (min);
  21393. }
  21394. var random = Math.random();
  21395. return ((random * (max - min)) + min);
  21396. };
  21397. var ParticleSystem = (function () {
  21398. function ParticleSystem(name, capacity, scene, customEffect) {
  21399. var _this = this;
  21400. this.name = name;
  21401. this.renderingGroupId = 0;
  21402. this.emitter = null;
  21403. this.emitRate = 10;
  21404. this.manualEmitCount = -1;
  21405. this.updateSpeed = 0.01;
  21406. this.targetStopDuration = 0;
  21407. this.disposeOnStop = false;
  21408. this.minEmitPower = 1;
  21409. this.maxEmitPower = 1;
  21410. this.minLifeTime = 1;
  21411. this.maxLifeTime = 1;
  21412. this.minSize = 1;
  21413. this.maxSize = 1;
  21414. this.minAngularSpeed = 0;
  21415. this.maxAngularSpeed = 0;
  21416. this.layerMask = 0x0FFFFFFF;
  21417. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21418. this.forceDepthWrite = false;
  21419. this.gravity = BABYLON.Vector3.Zero();
  21420. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21421. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21422. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21423. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21424. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21425. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21426. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21427. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21428. this.particles = new Array();
  21429. this._vertexDeclaration = [3, 4, 4];
  21430. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21431. this._stockParticles = new Array();
  21432. this._newPartsExcess = 0;
  21433. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21434. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21435. this._scaledDirection = BABYLON.Vector3.Zero();
  21436. this._scaledGravity = BABYLON.Vector3.Zero();
  21437. this._currentRenderId = -1;
  21438. this._started = false;
  21439. this._stopped = false;
  21440. this._actualFrame = 0;
  21441. this.id = name;
  21442. this._capacity = capacity;
  21443. this._scene = scene;
  21444. this._customEffect = customEffect;
  21445. scene.particleSystems.push(this);
  21446. // VBO
  21447. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21448. var indices = [];
  21449. var index = 0;
  21450. for (var count = 0; count < capacity; count++) {
  21451. indices.push(index);
  21452. indices.push(index + 1);
  21453. indices.push(index + 2);
  21454. indices.push(index);
  21455. indices.push(index + 2);
  21456. indices.push(index + 3);
  21457. index += 4;
  21458. }
  21459. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21460. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21461. // Default behaviors
  21462. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21463. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21464. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21465. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21466. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21467. };
  21468. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21469. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21470. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21471. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21472. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21473. };
  21474. this.updateFunction = function (particles) {
  21475. for (var index = 0; index < particles.length; index++) {
  21476. var particle = particles[index];
  21477. particle.age += _this._scaledUpdateSpeed;
  21478. if (particle.age >= particle.lifeTime) {
  21479. _this.recycleParticle(particle);
  21480. index--;
  21481. continue;
  21482. }
  21483. else {
  21484. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21485. particle.color.addInPlace(_this._scaledColorStep);
  21486. if (particle.color.a < 0)
  21487. particle.color.a = 0;
  21488. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21489. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21490. particle.position.addInPlace(_this._scaledDirection);
  21491. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21492. particle.direction.addInPlace(_this._scaledGravity);
  21493. }
  21494. }
  21495. };
  21496. }
  21497. ParticleSystem.prototype.recycleParticle = function (particle) {
  21498. var lastParticle = this.particles.pop();
  21499. if (lastParticle !== particle) {
  21500. lastParticle.copyTo(particle);
  21501. this._stockParticles.push(lastParticle);
  21502. }
  21503. };
  21504. ParticleSystem.prototype.getCapacity = function () {
  21505. return this._capacity;
  21506. };
  21507. ParticleSystem.prototype.isAlive = function () {
  21508. return this._alive;
  21509. };
  21510. ParticleSystem.prototype.isStarted = function () {
  21511. return this._started;
  21512. };
  21513. ParticleSystem.prototype.start = function () {
  21514. this._started = true;
  21515. this._stopped = false;
  21516. this._actualFrame = 0;
  21517. };
  21518. ParticleSystem.prototype.stop = function () {
  21519. this._stopped = true;
  21520. };
  21521. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21522. var offset = index * 11;
  21523. this._vertices[offset] = particle.position.x;
  21524. this._vertices[offset + 1] = particle.position.y;
  21525. this._vertices[offset + 2] = particle.position.z;
  21526. this._vertices[offset + 3] = particle.color.r;
  21527. this._vertices[offset + 4] = particle.color.g;
  21528. this._vertices[offset + 5] = particle.color.b;
  21529. this._vertices[offset + 6] = particle.color.a;
  21530. this._vertices[offset + 7] = particle.angle;
  21531. this._vertices[offset + 8] = particle.size;
  21532. this._vertices[offset + 9] = offsetX;
  21533. this._vertices[offset + 10] = offsetY;
  21534. };
  21535. ParticleSystem.prototype._update = function (newParticles) {
  21536. // Update current
  21537. this._alive = this.particles.length > 0;
  21538. this.updateFunction(this.particles);
  21539. // Add new ones
  21540. var worldMatrix;
  21541. if (this.emitter.position) {
  21542. worldMatrix = this.emitter.getWorldMatrix();
  21543. }
  21544. else {
  21545. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21546. }
  21547. for (var index = 0; index < newParticles; index++) {
  21548. if (this.particles.length === this._capacity) {
  21549. break;
  21550. }
  21551. if (this._stockParticles.length !== 0) {
  21552. var particle = this._stockParticles.pop();
  21553. particle.age = 0;
  21554. }
  21555. else {
  21556. particle = new BABYLON.Particle();
  21557. }
  21558. this.particles.push(particle);
  21559. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21560. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21561. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21562. particle.size = randomNumber(this.minSize, this.maxSize);
  21563. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21564. this.startPositionFunction(worldMatrix, particle.position);
  21565. var step = randomNumber(0, 1.0);
  21566. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21567. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21568. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21569. }
  21570. };
  21571. ParticleSystem.prototype._getEffect = function () {
  21572. if (this._customEffect) {
  21573. return this._customEffect;
  21574. }
  21575. ;
  21576. var defines = [];
  21577. if (this._scene.clipPlane) {
  21578. defines.push("#define CLIPPLANE");
  21579. }
  21580. // Effect
  21581. var join = defines.join("\n");
  21582. if (this._cachedDefines !== join) {
  21583. this._cachedDefines = join;
  21584. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21585. }
  21586. return this._effect;
  21587. };
  21588. ParticleSystem.prototype.animate = function () {
  21589. if (!this._started)
  21590. return;
  21591. var effect = this._getEffect();
  21592. // Check
  21593. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21594. return;
  21595. if (this._currentRenderId === this._scene.getRenderId()) {
  21596. return;
  21597. }
  21598. this._currentRenderId = this._scene.getRenderId();
  21599. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21600. // determine the number of particles we need to create
  21601. var emitCout;
  21602. if (this.manualEmitCount > -1) {
  21603. emitCout = this.manualEmitCount;
  21604. this.manualEmitCount = 0;
  21605. }
  21606. else {
  21607. emitCout = this.emitRate;
  21608. }
  21609. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21610. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21611. if (this._newPartsExcess > 1.0) {
  21612. newParticles += this._newPartsExcess >> 0;
  21613. this._newPartsExcess -= this._newPartsExcess >> 0;
  21614. }
  21615. this._alive = false;
  21616. if (!this._stopped) {
  21617. this._actualFrame += this._scaledUpdateSpeed;
  21618. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21619. this.stop();
  21620. }
  21621. else {
  21622. newParticles = 0;
  21623. }
  21624. this._update(newParticles);
  21625. // Stopped?
  21626. if (this._stopped) {
  21627. if (!this._alive) {
  21628. this._started = false;
  21629. if (this.disposeOnStop) {
  21630. this._scene._toBeDisposed.push(this);
  21631. }
  21632. }
  21633. }
  21634. // Update VBO
  21635. var offset = 0;
  21636. for (var index = 0; index < this.particles.length; index++) {
  21637. var particle = this.particles[index];
  21638. this._appendParticleVertex(offset++, particle, 0, 0);
  21639. this._appendParticleVertex(offset++, particle, 1, 0);
  21640. this._appendParticleVertex(offset++, particle, 1, 1);
  21641. this._appendParticleVertex(offset++, particle, 0, 1);
  21642. }
  21643. var engine = this._scene.getEngine();
  21644. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21645. };
  21646. ParticleSystem.prototype.render = function () {
  21647. var effect = this._getEffect();
  21648. // Check
  21649. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21650. return 0;
  21651. var engine = this._scene.getEngine();
  21652. // Render
  21653. engine.enableEffect(effect);
  21654. engine.setState(false);
  21655. var viewMatrix = this._scene.getViewMatrix();
  21656. effect.setTexture("diffuseSampler", this.particleTexture);
  21657. effect.setMatrix("view", viewMatrix);
  21658. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21659. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21660. if (this._scene.clipPlane) {
  21661. var clipPlane = this._scene.clipPlane;
  21662. var invView = viewMatrix.clone();
  21663. invView.invert();
  21664. effect.setMatrix("invView", invView);
  21665. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21666. }
  21667. // VBOs
  21668. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21669. // Draw order
  21670. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21671. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21672. }
  21673. else {
  21674. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21675. }
  21676. if (this.forceDepthWrite) {
  21677. engine.setDepthWrite(true);
  21678. }
  21679. engine.draw(true, 0, this.particles.length * 6);
  21680. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21681. return this.particles.length;
  21682. };
  21683. ParticleSystem.prototype.dispose = function () {
  21684. if (this._vertexBuffer) {
  21685. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21686. this._vertexBuffer = null;
  21687. }
  21688. if (this._indexBuffer) {
  21689. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21690. this._indexBuffer = null;
  21691. }
  21692. if (this.particleTexture) {
  21693. this.particleTexture.dispose();
  21694. this.particleTexture = null;
  21695. }
  21696. // Remove from scene
  21697. var index = this._scene.particleSystems.indexOf(this);
  21698. this._scene.particleSystems.splice(index, 1);
  21699. // Callback
  21700. if (this.onDispose) {
  21701. this.onDispose();
  21702. }
  21703. };
  21704. // Clone
  21705. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21706. var result = new ParticleSystem(name, this._capacity, this._scene);
  21707. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21708. if (newEmitter === undefined) {
  21709. newEmitter = this.emitter;
  21710. }
  21711. result.emitter = newEmitter;
  21712. if (this.particleTexture) {
  21713. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21714. }
  21715. result.start();
  21716. return result;
  21717. };
  21718. // Statics
  21719. ParticleSystem.BLENDMODE_ONEONE = 0;
  21720. ParticleSystem.BLENDMODE_STANDARD = 1;
  21721. return ParticleSystem;
  21722. })();
  21723. BABYLON.ParticleSystem = ParticleSystem;
  21724. })(BABYLON || (BABYLON = {}));
  21725. var BABYLON;
  21726. (function (BABYLON) {
  21727. var Animation = (function () {
  21728. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21729. this.name = name;
  21730. this.targetProperty = targetProperty;
  21731. this.framePerSecond = framePerSecond;
  21732. this.dataType = dataType;
  21733. this.loopMode = loopMode;
  21734. this._offsetsCache = {};
  21735. this._highLimitsCache = {};
  21736. this._stopped = false;
  21737. this.allowMatricesInterpolation = false;
  21738. this.targetPropertyPath = targetProperty.split(".");
  21739. this.dataType = dataType;
  21740. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21741. }
  21742. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21743. var dataType = undefined;
  21744. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21745. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21746. }
  21747. else if (from instanceof BABYLON.Quaternion) {
  21748. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21749. }
  21750. else if (from instanceof BABYLON.Vector3) {
  21751. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21752. }
  21753. else if (from instanceof BABYLON.Vector2) {
  21754. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21755. }
  21756. else if (from instanceof BABYLON.Color3) {
  21757. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21758. }
  21759. if (dataType == undefined) {
  21760. return null;
  21761. }
  21762. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21763. var keys = [];
  21764. keys.push({ frame: 0, value: from });
  21765. keys.push({ frame: totalFrame, value: to });
  21766. animation.setKeys(keys);
  21767. if (easingFunction !== undefined) {
  21768. animation.setEasingFunction(easingFunction);
  21769. }
  21770. mesh.animations.push(animation);
  21771. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21772. };
  21773. // Methods
  21774. Animation.prototype.reset = function () {
  21775. this._offsetsCache = {};
  21776. this._highLimitsCache = {};
  21777. this.currentFrame = 0;
  21778. };
  21779. Animation.prototype.isStopped = function () {
  21780. return this._stopped;
  21781. };
  21782. Animation.prototype.getKeys = function () {
  21783. return this._keys;
  21784. };
  21785. Animation.prototype.getEasingFunction = function () {
  21786. return this._easingFunction;
  21787. };
  21788. Animation.prototype.setEasingFunction = function (easingFunction) {
  21789. this._easingFunction = easingFunction;
  21790. };
  21791. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21792. return startValue + (endValue - startValue) * gradient;
  21793. };
  21794. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21795. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21796. };
  21797. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21798. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21799. };
  21800. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21801. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21802. };
  21803. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21804. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21805. };
  21806. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21807. var startScale = new BABYLON.Vector3(0, 0, 0);
  21808. var startRotation = new BABYLON.Quaternion();
  21809. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21810. startValue.decompose(startScale, startRotation, startTranslation);
  21811. var endScale = new BABYLON.Vector3(0, 0, 0);
  21812. var endRotation = new BABYLON.Quaternion();
  21813. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21814. endValue.decompose(endScale, endRotation, endTranslation);
  21815. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21816. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21817. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21818. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21819. return result;
  21820. };
  21821. Animation.prototype.clone = function () {
  21822. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21823. clone.setKeys(this._keys);
  21824. return clone;
  21825. };
  21826. Animation.prototype.setKeys = function (values) {
  21827. this._keys = values.slice(0);
  21828. this._offsetsCache = {};
  21829. this._highLimitsCache = {};
  21830. };
  21831. Animation.prototype._getKeyValue = function (value) {
  21832. if (typeof value === "function") {
  21833. return value();
  21834. }
  21835. return value;
  21836. };
  21837. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21838. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21839. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21840. }
  21841. this.currentFrame = currentFrame;
  21842. // Try to get a hash to find the right key
  21843. 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));
  21844. if (this._keys[startKey].frame >= currentFrame) {
  21845. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21846. startKey--;
  21847. }
  21848. }
  21849. for (var key = startKey; key < this._keys.length; key++) {
  21850. if (this._keys[key + 1].frame >= currentFrame) {
  21851. var startValue = this._getKeyValue(this._keys[key].value);
  21852. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21853. // gradient : percent of currentFrame between the frame inf and the frame sup
  21854. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21855. // check for easingFunction and correction of gradient
  21856. if (this._easingFunction != null) {
  21857. gradient = this._easingFunction.ease(gradient);
  21858. }
  21859. switch (this.dataType) {
  21860. // Float
  21861. case Animation.ANIMATIONTYPE_FLOAT:
  21862. switch (loopMode) {
  21863. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21864. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21865. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21866. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21867. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21868. }
  21869. break;
  21870. // Quaternion
  21871. case Animation.ANIMATIONTYPE_QUATERNION:
  21872. var quaternion = null;
  21873. switch (loopMode) {
  21874. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21875. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21876. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21877. break;
  21878. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21879. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21880. break;
  21881. }
  21882. return quaternion;
  21883. // Vector3
  21884. case Animation.ANIMATIONTYPE_VECTOR3:
  21885. switch (loopMode) {
  21886. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21887. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21888. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21889. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21890. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21891. }
  21892. // Vector2
  21893. case Animation.ANIMATIONTYPE_VECTOR2:
  21894. switch (loopMode) {
  21895. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21896. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21897. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21898. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21899. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21900. }
  21901. // Color3
  21902. case Animation.ANIMATIONTYPE_COLOR3:
  21903. switch (loopMode) {
  21904. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21905. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21906. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21907. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21908. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21909. }
  21910. // Matrix
  21911. case Animation.ANIMATIONTYPE_MATRIX:
  21912. switch (loopMode) {
  21913. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21914. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21915. if (this.allowMatricesInterpolation) {
  21916. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21917. }
  21918. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21919. return startValue;
  21920. }
  21921. default:
  21922. break;
  21923. }
  21924. break;
  21925. }
  21926. }
  21927. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21928. };
  21929. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21930. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21931. this._stopped = true;
  21932. return false;
  21933. }
  21934. var returnValue = true;
  21935. // Adding a start key at frame 0 if missing
  21936. if (this._keys[0].frame !== 0) {
  21937. var newKey = { frame: 0, value: this._keys[0].value };
  21938. this._keys.splice(0, 0, newKey);
  21939. }
  21940. // Check limits
  21941. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21942. from = this._keys[0].frame;
  21943. }
  21944. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21945. to = this._keys[this._keys.length - 1].frame;
  21946. }
  21947. // Compute ratio
  21948. var range = to - from;
  21949. var offsetValue;
  21950. // ratio represents the frame delta between from and to
  21951. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21952. var highLimitValue = 0;
  21953. if (ratio > range && !loop) {
  21954. returnValue = false;
  21955. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21956. }
  21957. else {
  21958. // Get max value if required
  21959. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21960. var keyOffset = to.toString() + from.toString();
  21961. if (!this._offsetsCache[keyOffset]) {
  21962. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21963. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21964. switch (this.dataType) {
  21965. // Float
  21966. case Animation.ANIMATIONTYPE_FLOAT:
  21967. this._offsetsCache[keyOffset] = toValue - fromValue;
  21968. break;
  21969. // Quaternion
  21970. case Animation.ANIMATIONTYPE_QUATERNION:
  21971. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21972. break;
  21973. // Vector3
  21974. case Animation.ANIMATIONTYPE_VECTOR3:
  21975. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21976. // Vector2
  21977. case Animation.ANIMATIONTYPE_VECTOR2:
  21978. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21979. // Color3
  21980. case Animation.ANIMATIONTYPE_COLOR3:
  21981. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21982. default:
  21983. break;
  21984. }
  21985. this._highLimitsCache[keyOffset] = toValue;
  21986. }
  21987. highLimitValue = this._highLimitsCache[keyOffset];
  21988. offsetValue = this._offsetsCache[keyOffset];
  21989. }
  21990. }
  21991. if (offsetValue === undefined) {
  21992. switch (this.dataType) {
  21993. // Float
  21994. case Animation.ANIMATIONTYPE_FLOAT:
  21995. offsetValue = 0;
  21996. break;
  21997. // Quaternion
  21998. case Animation.ANIMATIONTYPE_QUATERNION:
  21999. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22000. break;
  22001. // Vector3
  22002. case Animation.ANIMATIONTYPE_VECTOR3:
  22003. offsetValue = BABYLON.Vector3.Zero();
  22004. break;
  22005. // Vector2
  22006. case Animation.ANIMATIONTYPE_VECTOR2:
  22007. offsetValue = BABYLON.Vector2.Zero();
  22008. break;
  22009. // Color3
  22010. case Animation.ANIMATIONTYPE_COLOR3:
  22011. offsetValue = BABYLON.Color3.Black();
  22012. }
  22013. }
  22014. // Compute value
  22015. var repeatCount = (ratio / range) >> 0;
  22016. var currentFrame = returnValue ? from + ratio % range : to;
  22017. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22018. // Set value
  22019. if (this.targetPropertyPath.length > 1) {
  22020. var property = this._target[this.targetPropertyPath[0]];
  22021. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22022. property = property[this.targetPropertyPath[index]];
  22023. }
  22024. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22025. }
  22026. else {
  22027. this._target[this.targetPropertyPath[0]] = currentValue;
  22028. }
  22029. if (this._target.markAsDirty) {
  22030. this._target.markAsDirty(this.targetProperty);
  22031. }
  22032. if (!returnValue) {
  22033. this._stopped = true;
  22034. }
  22035. return returnValue;
  22036. };
  22037. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22038. get: function () {
  22039. return Animation._ANIMATIONTYPE_FLOAT;
  22040. },
  22041. enumerable: true,
  22042. configurable: true
  22043. });
  22044. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22045. get: function () {
  22046. return Animation._ANIMATIONTYPE_VECTOR3;
  22047. },
  22048. enumerable: true,
  22049. configurable: true
  22050. });
  22051. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22052. get: function () {
  22053. return Animation._ANIMATIONTYPE_VECTOR2;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22059. get: function () {
  22060. return Animation._ANIMATIONTYPE_QUATERNION;
  22061. },
  22062. enumerable: true,
  22063. configurable: true
  22064. });
  22065. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22066. get: function () {
  22067. return Animation._ANIMATIONTYPE_MATRIX;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22073. get: function () {
  22074. return Animation._ANIMATIONTYPE_COLOR3;
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22080. get: function () {
  22081. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22082. },
  22083. enumerable: true,
  22084. configurable: true
  22085. });
  22086. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22087. get: function () {
  22088. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22089. },
  22090. enumerable: true,
  22091. configurable: true
  22092. });
  22093. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22094. get: function () {
  22095. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22096. },
  22097. enumerable: true,
  22098. configurable: true
  22099. });
  22100. // Statics
  22101. Animation._ANIMATIONTYPE_FLOAT = 0;
  22102. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22103. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22104. Animation._ANIMATIONTYPE_MATRIX = 3;
  22105. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22106. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22107. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22108. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22109. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22110. return Animation;
  22111. })();
  22112. BABYLON.Animation = Animation;
  22113. })(BABYLON || (BABYLON = {}));
  22114. var BABYLON;
  22115. (function (BABYLON) {
  22116. var Animatable = (function () {
  22117. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22118. if (fromFrame === void 0) { fromFrame = 0; }
  22119. if (toFrame === void 0) { toFrame = 100; }
  22120. if (loopAnimation === void 0) { loopAnimation = false; }
  22121. if (speedRatio === void 0) { speedRatio = 1.0; }
  22122. this.target = target;
  22123. this.fromFrame = fromFrame;
  22124. this.toFrame = toFrame;
  22125. this.loopAnimation = loopAnimation;
  22126. this.speedRatio = speedRatio;
  22127. this.onAnimationEnd = onAnimationEnd;
  22128. this._animations = new Array();
  22129. this._paused = false;
  22130. this.animationStarted = false;
  22131. if (animations) {
  22132. this.appendAnimations(target, animations);
  22133. }
  22134. this._scene = scene;
  22135. scene._activeAnimatables.push(this);
  22136. }
  22137. // Methods
  22138. Animatable.prototype.appendAnimations = function (target, animations) {
  22139. for (var index = 0; index < animations.length; index++) {
  22140. var animation = animations[index];
  22141. animation._target = target;
  22142. this._animations.push(animation);
  22143. }
  22144. };
  22145. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22146. var animations = this._animations;
  22147. for (var index = 0; index < animations.length; index++) {
  22148. if (animations[index].targetProperty === property) {
  22149. return animations[index];
  22150. }
  22151. }
  22152. return null;
  22153. };
  22154. Animatable.prototype.reset = function () {
  22155. var animations = this._animations;
  22156. for (var index = 0; index < animations.length; index++) {
  22157. animations[index].reset();
  22158. }
  22159. this._localDelayOffset = null;
  22160. this._pausedDelay = null;
  22161. };
  22162. Animatable.prototype.pause = function () {
  22163. if (this._paused) {
  22164. return;
  22165. }
  22166. this._paused = true;
  22167. };
  22168. Animatable.prototype.restart = function () {
  22169. this._paused = false;
  22170. };
  22171. Animatable.prototype.stop = function () {
  22172. var index = this._scene._activeAnimatables.indexOf(this);
  22173. if (index > -1) {
  22174. this._scene._activeAnimatables.splice(index, 1);
  22175. }
  22176. if (this.onAnimationEnd) {
  22177. this.onAnimationEnd();
  22178. }
  22179. };
  22180. Animatable.prototype._animate = function (delay) {
  22181. if (this._paused) {
  22182. if (!this._pausedDelay) {
  22183. this._pausedDelay = delay;
  22184. }
  22185. return true;
  22186. }
  22187. if (!this._localDelayOffset) {
  22188. this._localDelayOffset = delay;
  22189. }
  22190. else if (this._pausedDelay) {
  22191. this._localDelayOffset += delay - this._pausedDelay;
  22192. this._pausedDelay = null;
  22193. }
  22194. // Animating
  22195. var running = false;
  22196. var animations = this._animations;
  22197. for (var index = 0; index < animations.length; index++) {
  22198. var animation = animations[index];
  22199. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22200. running = running || isRunning;
  22201. }
  22202. if (!running) {
  22203. // Remove from active animatables
  22204. index = this._scene._activeAnimatables.indexOf(this);
  22205. this._scene._activeAnimatables.splice(index, 1);
  22206. }
  22207. if (!running && this.onAnimationEnd) {
  22208. this.onAnimationEnd();
  22209. }
  22210. return running;
  22211. };
  22212. return Animatable;
  22213. })();
  22214. BABYLON.Animatable = Animatable;
  22215. })(BABYLON || (BABYLON = {}));
  22216. var BABYLON;
  22217. (function (BABYLON) {
  22218. var EasingFunction = (function () {
  22219. function EasingFunction() {
  22220. // Properties
  22221. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22222. }
  22223. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22224. get: function () {
  22225. return EasingFunction._EASINGMODE_EASEIN;
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22231. get: function () {
  22232. return EasingFunction._EASINGMODE_EASEOUT;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22238. get: function () {
  22239. return EasingFunction._EASINGMODE_EASEINOUT;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22245. var n = Math.min(Math.max(easingMode, 0), 2);
  22246. this._easingMode = n;
  22247. };
  22248. EasingFunction.prototype.getEasingMode = function () {
  22249. return this._easingMode;
  22250. };
  22251. EasingFunction.prototype.easeInCore = function (gradient) {
  22252. throw new Error('You must implement this method');
  22253. };
  22254. EasingFunction.prototype.ease = function (gradient) {
  22255. switch (this._easingMode) {
  22256. case EasingFunction.EASINGMODE_EASEIN:
  22257. return this.easeInCore(gradient);
  22258. case EasingFunction.EASINGMODE_EASEOUT:
  22259. return (1 - this.easeInCore(1 - gradient));
  22260. }
  22261. if (gradient >= 0.5) {
  22262. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22263. }
  22264. return (this.easeInCore(gradient * 2) * 0.5);
  22265. };
  22266. //Statics
  22267. EasingFunction._EASINGMODE_EASEIN = 0;
  22268. EasingFunction._EASINGMODE_EASEOUT = 1;
  22269. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22270. return EasingFunction;
  22271. })();
  22272. BABYLON.EasingFunction = EasingFunction;
  22273. var CircleEase = (function (_super) {
  22274. __extends(CircleEase, _super);
  22275. function CircleEase() {
  22276. _super.apply(this, arguments);
  22277. }
  22278. CircleEase.prototype.easeInCore = function (gradient) {
  22279. gradient = Math.max(0, Math.min(1, gradient));
  22280. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22281. };
  22282. return CircleEase;
  22283. })(EasingFunction);
  22284. BABYLON.CircleEase = CircleEase;
  22285. var BackEase = (function (_super) {
  22286. __extends(BackEase, _super);
  22287. function BackEase(amplitude) {
  22288. if (amplitude === void 0) { amplitude = 1; }
  22289. _super.call(this);
  22290. this.amplitude = amplitude;
  22291. }
  22292. BackEase.prototype.easeInCore = function (gradient) {
  22293. var num = Math.max(0, this.amplitude);
  22294. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22295. };
  22296. return BackEase;
  22297. })(EasingFunction);
  22298. BABYLON.BackEase = BackEase;
  22299. var BounceEase = (function (_super) {
  22300. __extends(BounceEase, _super);
  22301. function BounceEase(bounces, bounciness) {
  22302. if (bounces === void 0) { bounces = 3; }
  22303. if (bounciness === void 0) { bounciness = 2; }
  22304. _super.call(this);
  22305. this.bounces = bounces;
  22306. this.bounciness = bounciness;
  22307. }
  22308. BounceEase.prototype.easeInCore = function (gradient) {
  22309. var y = Math.max(0.0, this.bounces);
  22310. var bounciness = this.bounciness;
  22311. if (bounciness <= 1.0) {
  22312. bounciness = 1.001;
  22313. }
  22314. var num9 = Math.pow(bounciness, y);
  22315. var num5 = 1.0 - bounciness;
  22316. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22317. var num15 = gradient * num4;
  22318. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22319. var num3 = Math.floor(num65);
  22320. var num13 = num3 + 1.0;
  22321. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22322. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22323. var num7 = (num8 + num12) * 0.5;
  22324. var num6 = gradient - num7;
  22325. var num2 = num7 - num8;
  22326. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22327. };
  22328. return BounceEase;
  22329. })(EasingFunction);
  22330. BABYLON.BounceEase = BounceEase;
  22331. var CubicEase = (function (_super) {
  22332. __extends(CubicEase, _super);
  22333. function CubicEase() {
  22334. _super.apply(this, arguments);
  22335. }
  22336. CubicEase.prototype.easeInCore = function (gradient) {
  22337. return (gradient * gradient * gradient);
  22338. };
  22339. return CubicEase;
  22340. })(EasingFunction);
  22341. BABYLON.CubicEase = CubicEase;
  22342. var ElasticEase = (function (_super) {
  22343. __extends(ElasticEase, _super);
  22344. function ElasticEase(oscillations, springiness) {
  22345. if (oscillations === void 0) { oscillations = 3; }
  22346. if (springiness === void 0) { springiness = 3; }
  22347. _super.call(this);
  22348. this.oscillations = oscillations;
  22349. this.springiness = springiness;
  22350. }
  22351. ElasticEase.prototype.easeInCore = function (gradient) {
  22352. var num2;
  22353. var num3 = Math.max(0.0, this.oscillations);
  22354. var num = Math.max(0.0, this.springiness);
  22355. if (num == 0) {
  22356. num2 = gradient;
  22357. }
  22358. else {
  22359. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22360. }
  22361. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22362. };
  22363. return ElasticEase;
  22364. })(EasingFunction);
  22365. BABYLON.ElasticEase = ElasticEase;
  22366. var ExponentialEase = (function (_super) {
  22367. __extends(ExponentialEase, _super);
  22368. function ExponentialEase(exponent) {
  22369. if (exponent === void 0) { exponent = 2; }
  22370. _super.call(this);
  22371. this.exponent = exponent;
  22372. }
  22373. ExponentialEase.prototype.easeInCore = function (gradient) {
  22374. if (this.exponent <= 0) {
  22375. return gradient;
  22376. }
  22377. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22378. };
  22379. return ExponentialEase;
  22380. })(EasingFunction);
  22381. BABYLON.ExponentialEase = ExponentialEase;
  22382. var PowerEase = (function (_super) {
  22383. __extends(PowerEase, _super);
  22384. function PowerEase(power) {
  22385. if (power === void 0) { power = 2; }
  22386. _super.call(this);
  22387. this.power = power;
  22388. }
  22389. PowerEase.prototype.easeInCore = function (gradient) {
  22390. var y = Math.max(0.0, this.power);
  22391. return Math.pow(gradient, y);
  22392. };
  22393. return PowerEase;
  22394. })(EasingFunction);
  22395. BABYLON.PowerEase = PowerEase;
  22396. var QuadraticEase = (function (_super) {
  22397. __extends(QuadraticEase, _super);
  22398. function QuadraticEase() {
  22399. _super.apply(this, arguments);
  22400. }
  22401. QuadraticEase.prototype.easeInCore = function (gradient) {
  22402. return (gradient * gradient);
  22403. };
  22404. return QuadraticEase;
  22405. })(EasingFunction);
  22406. BABYLON.QuadraticEase = QuadraticEase;
  22407. var QuarticEase = (function (_super) {
  22408. __extends(QuarticEase, _super);
  22409. function QuarticEase() {
  22410. _super.apply(this, arguments);
  22411. }
  22412. QuarticEase.prototype.easeInCore = function (gradient) {
  22413. return (gradient * gradient * gradient * gradient);
  22414. };
  22415. return QuarticEase;
  22416. })(EasingFunction);
  22417. BABYLON.QuarticEase = QuarticEase;
  22418. var QuinticEase = (function (_super) {
  22419. __extends(QuinticEase, _super);
  22420. function QuinticEase() {
  22421. _super.apply(this, arguments);
  22422. }
  22423. QuinticEase.prototype.easeInCore = function (gradient) {
  22424. return (gradient * gradient * gradient * gradient * gradient);
  22425. };
  22426. return QuinticEase;
  22427. })(EasingFunction);
  22428. BABYLON.QuinticEase = QuinticEase;
  22429. var SineEase = (function (_super) {
  22430. __extends(SineEase, _super);
  22431. function SineEase() {
  22432. _super.apply(this, arguments);
  22433. }
  22434. SineEase.prototype.easeInCore = function (gradient) {
  22435. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22436. };
  22437. return SineEase;
  22438. })(EasingFunction);
  22439. BABYLON.SineEase = SineEase;
  22440. var BezierCurveEase = (function (_super) {
  22441. __extends(BezierCurveEase, _super);
  22442. function BezierCurveEase(x1, y1, x2, y2) {
  22443. if (x1 === void 0) { x1 = 0; }
  22444. if (y1 === void 0) { y1 = 0; }
  22445. if (x2 === void 0) { x2 = 1; }
  22446. if (y2 === void 0) { y2 = 1; }
  22447. _super.call(this);
  22448. this.x1 = x1;
  22449. this.y1 = y1;
  22450. this.x2 = x2;
  22451. this.y2 = y2;
  22452. }
  22453. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22454. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22455. };
  22456. return BezierCurveEase;
  22457. })(EasingFunction);
  22458. BABYLON.BezierCurveEase = BezierCurveEase;
  22459. })(BABYLON || (BABYLON = {}));
  22460. var BABYLON;
  22461. (function (BABYLON) {
  22462. var Octree = (function () {
  22463. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22464. if (maxDepth === void 0) { maxDepth = 2; }
  22465. this.maxDepth = maxDepth;
  22466. this.dynamicContent = new Array();
  22467. this._maxBlockCapacity = maxBlockCapacity || 64;
  22468. this._selectionContent = new BABYLON.SmartArray(1024);
  22469. this._creationFunc = creationFunc;
  22470. }
  22471. // Methods
  22472. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22473. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22474. };
  22475. Octree.prototype.addMesh = function (entry) {
  22476. for (var index = 0; index < this.blocks.length; index++) {
  22477. var block = this.blocks[index];
  22478. block.addEntry(entry);
  22479. }
  22480. };
  22481. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22482. this._selectionContent.reset();
  22483. for (var index = 0; index < this.blocks.length; index++) {
  22484. var block = this.blocks[index];
  22485. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22486. }
  22487. if (allowDuplicate) {
  22488. this._selectionContent.concat(this.dynamicContent);
  22489. }
  22490. else {
  22491. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22492. }
  22493. return this._selectionContent;
  22494. };
  22495. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22496. this._selectionContent.reset();
  22497. for (var index = 0; index < this.blocks.length; index++) {
  22498. var block = this.blocks[index];
  22499. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22500. }
  22501. if (allowDuplicate) {
  22502. this._selectionContent.concat(this.dynamicContent);
  22503. }
  22504. else {
  22505. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22506. }
  22507. return this._selectionContent;
  22508. };
  22509. Octree.prototype.intersectsRay = function (ray) {
  22510. this._selectionContent.reset();
  22511. for (var index = 0; index < this.blocks.length; index++) {
  22512. var block = this.blocks[index];
  22513. block.intersectsRay(ray, this._selectionContent);
  22514. }
  22515. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22516. return this._selectionContent;
  22517. };
  22518. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22519. target.blocks = new Array();
  22520. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22521. // Segmenting space
  22522. for (var x = 0; x < 2; x++) {
  22523. for (var y = 0; y < 2; y++) {
  22524. for (var z = 0; z < 2; z++) {
  22525. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22526. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22527. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22528. block.addEntries(entries);
  22529. target.blocks.push(block);
  22530. }
  22531. }
  22532. }
  22533. };
  22534. Octree.CreationFuncForMeshes = function (entry, block) {
  22535. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22536. block.entries.push(entry);
  22537. }
  22538. };
  22539. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22540. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22541. block.entries.push(entry);
  22542. }
  22543. };
  22544. return Octree;
  22545. })();
  22546. BABYLON.Octree = Octree;
  22547. })(BABYLON || (BABYLON = {}));
  22548. var BABYLON;
  22549. (function (BABYLON) {
  22550. var OctreeBlock = (function () {
  22551. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22552. this.entries = new Array();
  22553. this._boundingVectors = new Array();
  22554. this._capacity = capacity;
  22555. this._depth = depth;
  22556. this._maxDepth = maxDepth;
  22557. this._creationFunc = creationFunc;
  22558. this._minPoint = minPoint;
  22559. this._maxPoint = maxPoint;
  22560. this._boundingVectors.push(minPoint.clone());
  22561. this._boundingVectors.push(maxPoint.clone());
  22562. this._boundingVectors.push(minPoint.clone());
  22563. this._boundingVectors[2].x = maxPoint.x;
  22564. this._boundingVectors.push(minPoint.clone());
  22565. this._boundingVectors[3].y = maxPoint.y;
  22566. this._boundingVectors.push(minPoint.clone());
  22567. this._boundingVectors[4].z = maxPoint.z;
  22568. this._boundingVectors.push(maxPoint.clone());
  22569. this._boundingVectors[5].z = minPoint.z;
  22570. this._boundingVectors.push(maxPoint.clone());
  22571. this._boundingVectors[6].x = minPoint.x;
  22572. this._boundingVectors.push(maxPoint.clone());
  22573. this._boundingVectors[7].y = minPoint.y;
  22574. }
  22575. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22576. // Property
  22577. get: function () {
  22578. return this._capacity;
  22579. },
  22580. enumerable: true,
  22581. configurable: true
  22582. });
  22583. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22584. get: function () {
  22585. return this._minPoint;
  22586. },
  22587. enumerable: true,
  22588. configurable: true
  22589. });
  22590. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22591. get: function () {
  22592. return this._maxPoint;
  22593. },
  22594. enumerable: true,
  22595. configurable: true
  22596. });
  22597. // Methods
  22598. OctreeBlock.prototype.addEntry = function (entry) {
  22599. if (this.blocks) {
  22600. for (var index = 0; index < this.blocks.length; index++) {
  22601. var block = this.blocks[index];
  22602. block.addEntry(entry);
  22603. }
  22604. return;
  22605. }
  22606. this._creationFunc(entry, this);
  22607. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22608. this.createInnerBlocks();
  22609. }
  22610. };
  22611. OctreeBlock.prototype.addEntries = function (entries) {
  22612. for (var index = 0; index < entries.length; index++) {
  22613. var mesh = entries[index];
  22614. this.addEntry(mesh);
  22615. }
  22616. };
  22617. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22618. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22619. if (this.blocks) {
  22620. for (var index = 0; index < this.blocks.length; index++) {
  22621. var block = this.blocks[index];
  22622. block.select(frustumPlanes, selection, allowDuplicate);
  22623. }
  22624. return;
  22625. }
  22626. if (allowDuplicate) {
  22627. selection.concat(this.entries);
  22628. }
  22629. else {
  22630. selection.concatWithNoDuplicate(this.entries);
  22631. }
  22632. }
  22633. };
  22634. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22635. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22636. if (this.blocks) {
  22637. for (var index = 0; index < this.blocks.length; index++) {
  22638. var block = this.blocks[index];
  22639. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22640. }
  22641. return;
  22642. }
  22643. if (allowDuplicate) {
  22644. selection.concat(this.entries);
  22645. }
  22646. else {
  22647. selection.concatWithNoDuplicate(this.entries);
  22648. }
  22649. }
  22650. };
  22651. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22652. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22653. if (this.blocks) {
  22654. for (var index = 0; index < this.blocks.length; index++) {
  22655. var block = this.blocks[index];
  22656. block.intersectsRay(ray, selection);
  22657. }
  22658. return;
  22659. }
  22660. selection.concatWithNoDuplicate(this.entries);
  22661. }
  22662. };
  22663. OctreeBlock.prototype.createInnerBlocks = function () {
  22664. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22665. };
  22666. return OctreeBlock;
  22667. })();
  22668. BABYLON.OctreeBlock = OctreeBlock;
  22669. })(BABYLON || (BABYLON = {}));
  22670. var BABYLON;
  22671. (function (BABYLON) {
  22672. var Bone = (function (_super) {
  22673. __extends(Bone, _super);
  22674. function Bone(name, skeleton, parentBone, matrix) {
  22675. _super.call(this, name, skeleton.getScene());
  22676. this.name = name;
  22677. this.children = new Array();
  22678. this.animations = new Array();
  22679. this._worldTransform = new BABYLON.Matrix();
  22680. this._absoluteTransform = new BABYLON.Matrix();
  22681. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22682. this._skeleton = skeleton;
  22683. this._matrix = matrix;
  22684. this._baseMatrix = matrix;
  22685. skeleton.bones.push(this);
  22686. if (parentBone) {
  22687. this._parent = parentBone;
  22688. parentBone.children.push(this);
  22689. }
  22690. else {
  22691. this._parent = null;
  22692. }
  22693. this._updateDifferenceMatrix();
  22694. }
  22695. // Members
  22696. Bone.prototype.getParent = function () {
  22697. return this._parent;
  22698. };
  22699. Bone.prototype.getLocalMatrix = function () {
  22700. return this._matrix;
  22701. };
  22702. Bone.prototype.getBaseMatrix = function () {
  22703. return this._baseMatrix;
  22704. };
  22705. Bone.prototype.getWorldMatrix = function () {
  22706. return this._worldTransform;
  22707. };
  22708. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22709. return this._invertedAbsoluteTransform;
  22710. };
  22711. Bone.prototype.getAbsoluteMatrix = function () {
  22712. var matrix = this._matrix.clone();
  22713. var parent = this._parent;
  22714. while (parent) {
  22715. matrix = matrix.multiply(parent.getLocalMatrix());
  22716. parent = parent.getParent();
  22717. }
  22718. return matrix;
  22719. };
  22720. // Methods
  22721. Bone.prototype.updateMatrix = function (matrix) {
  22722. this._matrix = matrix;
  22723. this._skeleton._markAsDirty();
  22724. this._updateDifferenceMatrix();
  22725. };
  22726. Bone.prototype._updateDifferenceMatrix = function () {
  22727. if (this._parent) {
  22728. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22729. }
  22730. else {
  22731. this._absoluteTransform.copyFrom(this._matrix);
  22732. }
  22733. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22734. for (var index = 0; index < this.children.length; index++) {
  22735. this.children[index]._updateDifferenceMatrix();
  22736. }
  22737. };
  22738. Bone.prototype.markAsDirty = function () {
  22739. this._currentRenderId++;
  22740. this._skeleton._markAsDirty();
  22741. };
  22742. return Bone;
  22743. })(BABYLON.Node);
  22744. BABYLON.Bone = Bone;
  22745. })(BABYLON || (BABYLON = {}));
  22746. var BABYLON;
  22747. (function (BABYLON) {
  22748. var Skeleton = (function () {
  22749. function Skeleton(name, id, scene) {
  22750. this.name = name;
  22751. this.id = id;
  22752. this.bones = new Array();
  22753. this._isDirty = true;
  22754. this._identity = BABYLON.Matrix.Identity();
  22755. this.bones = [];
  22756. this._scene = scene;
  22757. scene.skeletons.push(this);
  22758. this.prepare();
  22759. //make sure it will recalculate the matrix next time prepare is called.
  22760. this._isDirty = true;
  22761. }
  22762. // Members
  22763. Skeleton.prototype.getTransformMatrices = function () {
  22764. return this._transformMatrices;
  22765. };
  22766. Skeleton.prototype.getScene = function () {
  22767. return this._scene;
  22768. };
  22769. // Methods
  22770. Skeleton.prototype._markAsDirty = function () {
  22771. this._isDirty = true;
  22772. };
  22773. Skeleton.prototype.prepare = function () {
  22774. if (!this._isDirty) {
  22775. return;
  22776. }
  22777. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22778. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22779. }
  22780. for (var index = 0; index < this.bones.length; index++) {
  22781. var bone = this.bones[index];
  22782. var parentBone = bone.getParent();
  22783. if (parentBone) {
  22784. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22785. }
  22786. else {
  22787. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22788. }
  22789. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22790. }
  22791. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22792. this._isDirty = false;
  22793. this._scene._activeBones += this.bones.length;
  22794. };
  22795. Skeleton.prototype.getAnimatables = function () {
  22796. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22797. this._animatables = [];
  22798. for (var index = 0; index < this.bones.length; index++) {
  22799. this._animatables.push(this.bones[index]);
  22800. }
  22801. }
  22802. return this._animatables;
  22803. };
  22804. Skeleton.prototype.clone = function (name, id) {
  22805. var result = new Skeleton(name, id || name, this._scene);
  22806. for (var index = 0; index < this.bones.length; index++) {
  22807. var source = this.bones[index];
  22808. var parentBone = null;
  22809. if (source.getParent()) {
  22810. var parentIndex = this.bones.indexOf(source.getParent());
  22811. parentBone = result.bones[parentIndex];
  22812. }
  22813. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22814. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22815. }
  22816. return result;
  22817. };
  22818. return Skeleton;
  22819. })();
  22820. BABYLON.Skeleton = Skeleton;
  22821. })(BABYLON || (BABYLON = {}));
  22822. var BABYLON;
  22823. (function (BABYLON) {
  22824. var PostProcess = (function () {
  22825. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22827. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22828. this.name = name;
  22829. this.width = -1;
  22830. this.height = -1;
  22831. this._reusable = false;
  22832. this._textures = new BABYLON.SmartArray(2);
  22833. this._currentRenderTextureInd = 0;
  22834. if (camera != null) {
  22835. this._camera = camera;
  22836. this._scene = camera.getScene();
  22837. camera.attachPostProcess(this);
  22838. this._engine = this._scene.getEngine();
  22839. }
  22840. else {
  22841. this._engine = engine;
  22842. }
  22843. this._renderRatio = ratio;
  22844. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22845. this._reusable = reusable || false;
  22846. this._textureType = textureType;
  22847. samplers = samplers || [];
  22848. samplers.push("textureSampler");
  22849. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22850. }
  22851. PostProcess.prototype.isReusable = function () {
  22852. return this._reusable;
  22853. };
  22854. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22855. camera = camera || this._camera;
  22856. var scene = camera.getScene();
  22857. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22858. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22859. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22860. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22861. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22862. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22863. if (this._textures.length > 0) {
  22864. for (var i = 0; i < this._textures.length; i++) {
  22865. this._engine._releaseTexture(this._textures.data[i]);
  22866. }
  22867. this._textures.reset();
  22868. }
  22869. this.width = desiredWidth;
  22870. this.height = desiredHeight;
  22871. 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 }));
  22872. if (this._reusable) {
  22873. 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 }));
  22874. }
  22875. if (this.onSizeChanged) {
  22876. this.onSizeChanged();
  22877. }
  22878. }
  22879. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22880. if (this.onActivate) {
  22881. this.onActivate(camera);
  22882. }
  22883. // Clear
  22884. if (this.clearColor) {
  22885. this._engine.clear(this.clearColor, true, true);
  22886. }
  22887. else {
  22888. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22889. }
  22890. if (this._reusable) {
  22891. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22892. }
  22893. };
  22894. PostProcess.prototype.apply = function () {
  22895. // Check
  22896. if (!this._effect.isReady())
  22897. return null;
  22898. // States
  22899. this._engine.enableEffect(this._effect);
  22900. this._engine.setState(false);
  22901. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22902. this._engine.setDepthBuffer(false);
  22903. this._engine.setDepthWrite(false);
  22904. // Texture
  22905. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22906. // Parameters
  22907. if (this.onApply) {
  22908. this.onApply(this._effect);
  22909. }
  22910. return this._effect;
  22911. };
  22912. PostProcess.prototype.dispose = function (camera) {
  22913. camera = camera || this._camera;
  22914. if (this._textures.length > 0) {
  22915. for (var i = 0; i < this._textures.length; i++) {
  22916. this._engine._releaseTexture(this._textures.data[i]);
  22917. }
  22918. this._textures.reset();
  22919. }
  22920. if (!camera) {
  22921. return;
  22922. }
  22923. camera.detachPostProcess(this);
  22924. var index = camera._postProcesses.indexOf(this);
  22925. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22926. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22927. }
  22928. };
  22929. return PostProcess;
  22930. })();
  22931. BABYLON.PostProcess = PostProcess;
  22932. })(BABYLON || (BABYLON = {}));
  22933. var BABYLON;
  22934. (function (BABYLON) {
  22935. var PostProcessManager = (function () {
  22936. function PostProcessManager(scene) {
  22937. this._vertexDeclaration = [2];
  22938. this._vertexStrideSize = 2 * 4;
  22939. this._scene = scene;
  22940. }
  22941. PostProcessManager.prototype._prepareBuffers = function () {
  22942. if (this._vertexBuffer) {
  22943. return;
  22944. }
  22945. // VBO
  22946. var vertices = [];
  22947. vertices.push(1, 1);
  22948. vertices.push(-1, 1);
  22949. vertices.push(-1, -1);
  22950. vertices.push(1, -1);
  22951. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22952. // Indices
  22953. var indices = [];
  22954. indices.push(0);
  22955. indices.push(1);
  22956. indices.push(2);
  22957. indices.push(0);
  22958. indices.push(2);
  22959. indices.push(3);
  22960. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22961. };
  22962. // Methods
  22963. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22964. var postProcesses = this._scene.activeCamera._postProcesses;
  22965. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22966. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22967. return false;
  22968. }
  22969. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22970. return true;
  22971. };
  22972. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22973. var engine = this._scene.getEngine();
  22974. for (var index = 0; index < postProcesses.length; index++) {
  22975. if (index < postProcesses.length - 1) {
  22976. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22977. }
  22978. else {
  22979. if (targetTexture) {
  22980. engine.bindFramebuffer(targetTexture);
  22981. }
  22982. else {
  22983. engine.restoreDefaultFramebuffer();
  22984. }
  22985. }
  22986. var pp = postProcesses[index];
  22987. var effect = pp.apply();
  22988. if (effect) {
  22989. if (pp.onBeforeRender) {
  22990. pp.onBeforeRender(effect);
  22991. }
  22992. // VBOs
  22993. this._prepareBuffers();
  22994. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22995. // Draw order
  22996. engine.draw(true, 0, 6);
  22997. if (pp.onAfterRender) {
  22998. pp.onAfterRender(effect);
  22999. }
  23000. }
  23001. }
  23002. // Restore depth buffer
  23003. engine.setDepthBuffer(true);
  23004. engine.setDepthWrite(true);
  23005. };
  23006. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  23007. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23008. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23009. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23010. return;
  23011. }
  23012. var engine = this._scene.getEngine();
  23013. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23014. if (index < postProcessesTakenIndices.length - 1) {
  23015. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  23016. }
  23017. else {
  23018. if (targetTexture) {
  23019. engine.bindFramebuffer(targetTexture);
  23020. }
  23021. else {
  23022. engine.restoreDefaultFramebuffer();
  23023. }
  23024. }
  23025. if (doNotPresent) {
  23026. break;
  23027. }
  23028. var pp = postProcesses[postProcessesTakenIndices[index]];
  23029. var effect = pp.apply();
  23030. if (effect) {
  23031. if (pp.onBeforeRender) {
  23032. pp.onBeforeRender(effect);
  23033. }
  23034. // VBOs
  23035. this._prepareBuffers();
  23036. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23037. // Draw order
  23038. engine.draw(true, 0, 6);
  23039. if (pp.onAfterRender) {
  23040. pp.onAfterRender(effect);
  23041. }
  23042. }
  23043. }
  23044. // Restore depth buffer
  23045. engine.setDepthBuffer(true);
  23046. engine.setDepthWrite(true);
  23047. };
  23048. PostProcessManager.prototype.dispose = function () {
  23049. if (this._vertexBuffer) {
  23050. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23051. this._vertexBuffer = null;
  23052. }
  23053. if (this._indexBuffer) {
  23054. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23055. this._indexBuffer = null;
  23056. }
  23057. };
  23058. return PostProcessManager;
  23059. })();
  23060. BABYLON.PostProcessManager = PostProcessManager;
  23061. })(BABYLON || (BABYLON = {}));
  23062. var BABYLON;
  23063. (function (BABYLON) {
  23064. var PassPostProcess = (function (_super) {
  23065. __extends(PassPostProcess, _super);
  23066. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23067. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23068. }
  23069. return PassPostProcess;
  23070. })(BABYLON.PostProcess);
  23071. BABYLON.PassPostProcess = PassPostProcess;
  23072. })(BABYLON || (BABYLON = {}));
  23073. var BABYLON;
  23074. (function (BABYLON) {
  23075. var BlurPostProcess = (function (_super) {
  23076. __extends(BlurPostProcess, _super);
  23077. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23078. var _this = this;
  23079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23080. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23081. this.direction = direction;
  23082. this.blurWidth = blurWidth;
  23083. this.onApply = function (effect) {
  23084. effect.setFloat2("screenSize", _this.width, _this.height);
  23085. effect.setVector2("direction", _this.direction);
  23086. effect.setFloat("blurWidth", _this.blurWidth);
  23087. };
  23088. }
  23089. return BlurPostProcess;
  23090. })(BABYLON.PostProcess);
  23091. BABYLON.BlurPostProcess = BlurPostProcess;
  23092. })(BABYLON || (BABYLON = {}));
  23093. var BABYLON;
  23094. (function (BABYLON) {
  23095. var RefractionPostProcess = (function (_super) {
  23096. __extends(RefractionPostProcess, _super);
  23097. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23098. var _this = this;
  23099. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23100. this.color = color;
  23101. this.depth = depth;
  23102. this.colorLevel = colorLevel;
  23103. this.onActivate = function (cam) {
  23104. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23105. };
  23106. this.onApply = function (effect) {
  23107. effect.setColor3("baseColor", _this.color);
  23108. effect.setFloat("depth", _this.depth);
  23109. effect.setFloat("colorLevel", _this.colorLevel);
  23110. effect.setTexture("refractionSampler", _this._refRexture);
  23111. };
  23112. }
  23113. // Methods
  23114. RefractionPostProcess.prototype.dispose = function (camera) {
  23115. if (this._refRexture) {
  23116. this._refRexture.dispose();
  23117. }
  23118. _super.prototype.dispose.call(this, camera);
  23119. };
  23120. return RefractionPostProcess;
  23121. })(BABYLON.PostProcess);
  23122. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23123. })(BABYLON || (BABYLON = {}));
  23124. var BABYLON;
  23125. (function (BABYLON) {
  23126. var BlackAndWhitePostProcess = (function (_super) {
  23127. __extends(BlackAndWhitePostProcess, _super);
  23128. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23129. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23130. }
  23131. return BlackAndWhitePostProcess;
  23132. })(BABYLON.PostProcess);
  23133. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23134. })(BABYLON || (BABYLON = {}));
  23135. var BABYLON;
  23136. (function (BABYLON) {
  23137. var ConvolutionPostProcess = (function (_super) {
  23138. __extends(ConvolutionPostProcess, _super);
  23139. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23140. var _this = this;
  23141. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23142. this.kernel = kernel;
  23143. this.onApply = function (effect) {
  23144. effect.setFloat2("screenSize", _this.width, _this.height);
  23145. effect.setArray("kernel", _this.kernel);
  23146. };
  23147. }
  23148. // Statics
  23149. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23150. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23151. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23152. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23153. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23154. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23155. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23156. return ConvolutionPostProcess;
  23157. })(BABYLON.PostProcess);
  23158. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23159. })(BABYLON || (BABYLON = {}));
  23160. var BABYLON;
  23161. (function (BABYLON) {
  23162. var FilterPostProcess = (function (_super) {
  23163. __extends(FilterPostProcess, _super);
  23164. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23165. var _this = this;
  23166. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23167. this.kernelMatrix = kernelMatrix;
  23168. this.onApply = function (effect) {
  23169. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23170. };
  23171. }
  23172. return FilterPostProcess;
  23173. })(BABYLON.PostProcess);
  23174. BABYLON.FilterPostProcess = FilterPostProcess;
  23175. })(BABYLON || (BABYLON = {}));
  23176. var BABYLON;
  23177. (function (BABYLON) {
  23178. var FxaaPostProcess = (function (_super) {
  23179. __extends(FxaaPostProcess, _super);
  23180. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23181. var _this = this;
  23182. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23183. this.onSizeChanged = function () {
  23184. _this.texelWidth = 1.0 / _this.width;
  23185. _this.texelHeight = 1.0 / _this.height;
  23186. };
  23187. this.onApply = function (effect) {
  23188. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23189. };
  23190. }
  23191. return FxaaPostProcess;
  23192. })(BABYLON.PostProcess);
  23193. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23194. })(BABYLON || (BABYLON = {}));
  23195. var BABYLON;
  23196. (function (BABYLON) {
  23197. var StereoscopicInterlacePostProcess = (function (_super) {
  23198. __extends(StereoscopicInterlacePostProcess, _super);
  23199. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23200. var _this = this;
  23201. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23202. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23203. this.onSizeChanged = function () {
  23204. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23205. };
  23206. this.onApply = function (effect) {
  23207. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23208. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23209. };
  23210. }
  23211. return StereoscopicInterlacePostProcess;
  23212. })(BABYLON.PostProcess);
  23213. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23214. })(BABYLON || (BABYLON = {}));
  23215. var BABYLON;
  23216. (function (BABYLON) {
  23217. var LensFlare = (function () {
  23218. function LensFlare(size, position, color, imgUrl, system) {
  23219. this.size = size;
  23220. this.position = position;
  23221. this.dispose = function () {
  23222. if (this.texture) {
  23223. this.texture.dispose();
  23224. }
  23225. // Remove from scene
  23226. var index = this._system.lensFlares.indexOf(this);
  23227. this._system.lensFlares.splice(index, 1);
  23228. };
  23229. this.color = color || new BABYLON.Color3(1, 1, 1);
  23230. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23231. this._system = system;
  23232. system.lensFlares.push(this);
  23233. }
  23234. return LensFlare;
  23235. })();
  23236. BABYLON.LensFlare = LensFlare;
  23237. })(BABYLON || (BABYLON = {}));
  23238. var BABYLON;
  23239. (function (BABYLON) {
  23240. var LensFlareSystem = (function () {
  23241. function LensFlareSystem(name, emitter, scene) {
  23242. this.name = name;
  23243. this.lensFlares = new Array();
  23244. this.borderLimit = 300;
  23245. this.layerMask = 0x0FFFFFFF;
  23246. this._vertexDeclaration = [2];
  23247. this._vertexStrideSize = 2 * 4;
  23248. this._isEnabled = true;
  23249. this._scene = scene;
  23250. this._emitter = emitter;
  23251. scene.lensFlareSystems.push(this);
  23252. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23253. // VBO
  23254. var vertices = [];
  23255. vertices.push(1, 1);
  23256. vertices.push(-1, 1);
  23257. vertices.push(-1, -1);
  23258. vertices.push(1, -1);
  23259. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23260. // Indices
  23261. var indices = [];
  23262. indices.push(0);
  23263. indices.push(1);
  23264. indices.push(2);
  23265. indices.push(0);
  23266. indices.push(2);
  23267. indices.push(3);
  23268. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23269. // Effects
  23270. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23271. }
  23272. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23273. get: function () {
  23274. return this._isEnabled;
  23275. },
  23276. set: function (value) {
  23277. this._isEnabled = value;
  23278. },
  23279. enumerable: true,
  23280. configurable: true
  23281. });
  23282. LensFlareSystem.prototype.getScene = function () {
  23283. return this._scene;
  23284. };
  23285. LensFlareSystem.prototype.getEmitter = function () {
  23286. return this._emitter;
  23287. };
  23288. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23289. this._emitter = newEmitter;
  23290. };
  23291. LensFlareSystem.prototype.getEmitterPosition = function () {
  23292. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23293. };
  23294. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23295. var position = this.getEmitterPosition();
  23296. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23297. this._positionX = position.x;
  23298. this._positionY = position.y;
  23299. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23300. if (position.z > 0) {
  23301. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23302. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23303. return true;
  23304. }
  23305. }
  23306. return false;
  23307. };
  23308. LensFlareSystem.prototype._isVisible = function () {
  23309. if (!this._isEnabled) {
  23310. return false;
  23311. }
  23312. var emitterPosition = this.getEmitterPosition();
  23313. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23314. var distance = direction.length();
  23315. direction.normalize();
  23316. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23317. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23318. return !pickInfo.hit || pickInfo.distance > distance;
  23319. };
  23320. LensFlareSystem.prototype.render = function () {
  23321. if (!this._effect.isReady())
  23322. return false;
  23323. var engine = this._scene.getEngine();
  23324. var viewport = this._scene.activeCamera.viewport;
  23325. var globalViewport = viewport.toGlobal(engine);
  23326. // Position
  23327. if (!this.computeEffectivePosition(globalViewport)) {
  23328. return false;
  23329. }
  23330. // Visibility
  23331. if (!this._isVisible()) {
  23332. return false;
  23333. }
  23334. // Intensity
  23335. var awayX;
  23336. var awayY;
  23337. if (this._positionX < this.borderLimit + globalViewport.x) {
  23338. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23339. }
  23340. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23341. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23342. }
  23343. else {
  23344. awayX = 0;
  23345. }
  23346. if (this._positionY < this.borderLimit + globalViewport.y) {
  23347. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23348. }
  23349. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23350. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23351. }
  23352. else {
  23353. awayY = 0;
  23354. }
  23355. var away = (awayX > awayY) ? awayX : awayY;
  23356. if (away > this.borderLimit) {
  23357. away = this.borderLimit;
  23358. }
  23359. var intensity = 1.0 - (away / this.borderLimit);
  23360. if (intensity < 0) {
  23361. return false;
  23362. }
  23363. if (intensity > 1.0) {
  23364. intensity = 1.0;
  23365. }
  23366. // Position
  23367. var centerX = globalViewport.x + globalViewport.width / 2;
  23368. var centerY = globalViewport.y + globalViewport.height / 2;
  23369. var distX = centerX - this._positionX;
  23370. var distY = centerY - this._positionY;
  23371. // Effects
  23372. engine.enableEffect(this._effect);
  23373. engine.setState(false);
  23374. engine.setDepthBuffer(false);
  23375. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23376. // VBOs
  23377. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23378. // Flares
  23379. for (var index = 0; index < this.lensFlares.length; index++) {
  23380. var flare = this.lensFlares[index];
  23381. var x = centerX - (distX * flare.position);
  23382. var y = centerY - (distY * flare.position);
  23383. var cw = flare.size;
  23384. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23385. var cx = 2 * (x / globalViewport.width) - 1.0;
  23386. var cy = 1.0 - 2 * (y / globalViewport.height);
  23387. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23388. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23389. // Texture
  23390. this._effect.setTexture("textureSampler", flare.texture);
  23391. // Color
  23392. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23393. // Draw order
  23394. engine.draw(true, 0, 6);
  23395. }
  23396. engine.setDepthBuffer(true);
  23397. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23398. return true;
  23399. };
  23400. LensFlareSystem.prototype.dispose = function () {
  23401. if (this._vertexBuffer) {
  23402. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23403. this._vertexBuffer = null;
  23404. }
  23405. if (this._indexBuffer) {
  23406. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23407. this._indexBuffer = null;
  23408. }
  23409. while (this.lensFlares.length) {
  23410. this.lensFlares[0].dispose();
  23411. }
  23412. // Remove from scene
  23413. var index = this._scene.lensFlareSystems.indexOf(this);
  23414. this._scene.lensFlareSystems.splice(index, 1);
  23415. };
  23416. return LensFlareSystem;
  23417. })();
  23418. BABYLON.LensFlareSystem = LensFlareSystem;
  23419. })(BABYLON || (BABYLON = {}));
  23420. var BABYLON;
  23421. (function (BABYLON) {
  23422. var CannonJSPlugin = (function () {
  23423. function CannonJSPlugin() {
  23424. this._registeredMeshes = [];
  23425. this._physicsMaterials = [];
  23426. this.updateBodyPosition = function (mesh) {
  23427. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23428. var registeredMesh = this._registeredMeshes[index];
  23429. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23430. var body = registeredMesh.body;
  23431. var center = mesh.getBoundingInfo().boundingBox.center;
  23432. body.position.set(center.x, center.z, center.y);
  23433. body.quaternion.x = mesh.rotationQuaternion.x;
  23434. body.quaternion.z = mesh.rotationQuaternion.y;
  23435. body.quaternion.y = mesh.rotationQuaternion.z;
  23436. body.quaternion.w = -mesh.rotationQuaternion.w;
  23437. return;
  23438. }
  23439. }
  23440. };
  23441. }
  23442. CannonJSPlugin.prototype.initialize = function (iterations) {
  23443. if (iterations === void 0) { iterations = 10; }
  23444. this._world = new CANNON.World();
  23445. this._world.broadphase = new CANNON.NaiveBroadphase();
  23446. this._world.solver.iterations = iterations;
  23447. };
  23448. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23449. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23450. };
  23451. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23452. this._world.step(delta);
  23453. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23454. var registeredMesh = this._registeredMeshes[index];
  23455. if (registeredMesh.isChild) {
  23456. continue;
  23457. }
  23458. // Body position
  23459. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23460. var deltaPos = registeredMesh.delta;
  23461. if (deltaPos) {
  23462. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23463. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23464. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23465. }
  23466. else {
  23467. registeredMesh.mesh.position.x = bodyX;
  23468. registeredMesh.mesh.position.y = bodyZ;
  23469. registeredMesh.mesh.position.z = bodyY;
  23470. }
  23471. if (!registeredMesh.mesh.rotationQuaternion) {
  23472. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23473. }
  23474. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23475. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23476. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23477. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23478. }
  23479. };
  23480. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23481. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23482. };
  23483. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23484. this.unregisterMesh(mesh);
  23485. mesh.computeWorldMatrix(true);
  23486. switch (impostor) {
  23487. case BABYLON.PhysicsEngine.SphereImpostor:
  23488. var bbox = mesh.getBoundingInfo().boundingBox;
  23489. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23490. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23491. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23492. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23493. case BABYLON.PhysicsEngine.BoxImpostor:
  23494. bbox = mesh.getBoundingInfo().boundingBox;
  23495. var min = bbox.minimumWorld;
  23496. var max = bbox.maximumWorld;
  23497. var box = max.subtract(min).scale(0.5);
  23498. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23499. case BABYLON.PhysicsEngine.PlaneImpostor:
  23500. return this._createPlane(mesh, options);
  23501. case BABYLON.PhysicsEngine.MeshImpostor:
  23502. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23503. var rawFaces = mesh.getIndices();
  23504. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23505. }
  23506. return null;
  23507. };
  23508. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23509. var shape = new CANNON.Sphere(radius);
  23510. if (!options) {
  23511. return shape;
  23512. }
  23513. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23514. };
  23515. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23516. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23517. if (!options) {
  23518. return shape;
  23519. }
  23520. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23521. };
  23522. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23523. var shape = new CANNON.Plane();
  23524. if (!options) {
  23525. return shape;
  23526. }
  23527. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23528. };
  23529. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23530. var verts = [], faces = [];
  23531. mesh.computeWorldMatrix(true);
  23532. // Get vertices
  23533. for (var i = 0; i < rawVerts.length; i += 3) {
  23534. var transformed = BABYLON.Vector3.Zero();
  23535. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23536. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23537. }
  23538. // Get faces
  23539. for (var j = 0; j < rawFaces.length; j += 3) {
  23540. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23541. }
  23542. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23543. if (!options) {
  23544. return shape;
  23545. }
  23546. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23547. };
  23548. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23549. var index;
  23550. var mat;
  23551. for (index = 0; index < this._physicsMaterials.length; index++) {
  23552. mat = this._physicsMaterials[index];
  23553. if (mat.friction === friction && mat.restitution === restitution) {
  23554. return mat;
  23555. }
  23556. }
  23557. var currentMat = new CANNON.Material();
  23558. currentMat.friction = friction;
  23559. currentMat.restitution = restitution;
  23560. this._physicsMaterials.push(currentMat);
  23561. for (index = 0; index < this._physicsMaterials.length; index++) {
  23562. mat = this._physicsMaterials[index];
  23563. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23564. contactMaterial.contactEquationStiffness = 1e10;
  23565. contactMaterial.contactEquationRegularizationTime = 10;
  23566. this._world.addContactMaterial(contactMaterial);
  23567. }
  23568. return currentMat;
  23569. };
  23570. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23571. var initialRotation = null;
  23572. if (mesh.rotationQuaternion) {
  23573. initialRotation = mesh.rotationQuaternion.clone();
  23574. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23575. }
  23576. // The delta between the mesh position and the mesh bounding box center
  23577. var bbox = mesh.getBoundingInfo().boundingBox;
  23578. var deltaPosition = mesh.position.subtract(bbox.center);
  23579. var material = this._addMaterial(friction, restitution);
  23580. var body = new CANNON.RigidBody(mass, shape, material);
  23581. if (initialRotation) {
  23582. body.quaternion.x = initialRotation.x;
  23583. body.quaternion.z = initialRotation.y;
  23584. body.quaternion.y = initialRotation.z;
  23585. body.quaternion.w = -initialRotation.w;
  23586. }
  23587. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23588. this._world.add(body);
  23589. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23590. return body;
  23591. };
  23592. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23593. var compoundShape = new CANNON.Compound();
  23594. for (var index = 0; index < parts.length; index++) {
  23595. var mesh = parts[index].mesh;
  23596. var shape = this.registerMesh(mesh, parts[index].impostor);
  23597. if (index == 0) {
  23598. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23599. }
  23600. else {
  23601. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23602. }
  23603. }
  23604. var initialMesh = parts[0].mesh;
  23605. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23606. body.parts = parts;
  23607. return body;
  23608. };
  23609. CannonJSPlugin.prototype._unbindBody = function (body) {
  23610. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23611. var registeredMesh = this._registeredMeshes[index];
  23612. if (registeredMesh.body === body) {
  23613. registeredMesh.body = null;
  23614. registeredMesh.delta = 0;
  23615. }
  23616. }
  23617. };
  23618. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23619. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23620. var registeredMesh = this._registeredMeshes[index];
  23621. if (registeredMesh.mesh === mesh) {
  23622. // Remove body
  23623. if (registeredMesh.body) {
  23624. this._world.remove(registeredMesh.body);
  23625. this._unbindBody(registeredMesh.body);
  23626. }
  23627. this._registeredMeshes.splice(index, 1);
  23628. return;
  23629. }
  23630. }
  23631. };
  23632. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23633. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23634. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23635. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23636. var registeredMesh = this._registeredMeshes[index];
  23637. if (registeredMesh.mesh === mesh) {
  23638. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23639. return;
  23640. }
  23641. }
  23642. };
  23643. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23644. var body1 = null, body2 = null;
  23645. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23646. var registeredMesh = this._registeredMeshes[index];
  23647. if (registeredMesh.mesh === mesh1) {
  23648. body1 = registeredMesh.body;
  23649. }
  23650. else if (registeredMesh.mesh === mesh2) {
  23651. body2 = registeredMesh.body;
  23652. }
  23653. }
  23654. if (!body1 || !body2) {
  23655. return false;
  23656. }
  23657. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  23658. this._world.addConstraint(constraint);
  23659. return true;
  23660. };
  23661. CannonJSPlugin.prototype.dispose = function () {
  23662. while (this._registeredMeshes.length) {
  23663. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23664. }
  23665. };
  23666. CannonJSPlugin.prototype.isSupported = function () {
  23667. return window.CANNON !== undefined;
  23668. };
  23669. return CannonJSPlugin;
  23670. })();
  23671. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23672. })(BABYLON || (BABYLON = {}));
  23673. var BABYLON;
  23674. (function (BABYLON) {
  23675. var OimoJSPlugin = (function () {
  23676. function OimoJSPlugin() {
  23677. this._registeredMeshes = [];
  23678. /**
  23679. * Update the body position according to the mesh position
  23680. * @param mesh
  23681. */
  23682. this.updateBodyPosition = function (mesh) {
  23683. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23684. var registeredMesh = this._registeredMeshes[index];
  23685. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23686. var body = registeredMesh.body.body;
  23687. mesh.computeWorldMatrix(true);
  23688. var center = mesh.getBoundingInfo().boundingBox.center;
  23689. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23690. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23691. body.sleeping = false;
  23692. return;
  23693. }
  23694. // Case where the parent has been updated
  23695. if (registeredMesh.mesh.parent === mesh) {
  23696. mesh.computeWorldMatrix(true);
  23697. registeredMesh.mesh.computeWorldMatrix(true);
  23698. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23699. var absoluteRotation = mesh.rotation;
  23700. body = registeredMesh.body.body;
  23701. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23702. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23703. body.sleeping = false;
  23704. return;
  23705. }
  23706. }
  23707. };
  23708. }
  23709. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23710. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23711. };
  23712. OimoJSPlugin.prototype.initialize = function (iterations) {
  23713. this._world = new OIMO.World();
  23714. this._world.clear();
  23715. };
  23716. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23717. this._world.gravity = gravity;
  23718. };
  23719. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23720. var body = null;
  23721. this.unregisterMesh(mesh);
  23722. mesh.computeWorldMatrix(true);
  23723. var initialRotation = null;
  23724. if (mesh.rotationQuaternion) {
  23725. initialRotation = mesh.rotationQuaternion.clone();
  23726. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23727. mesh.computeWorldMatrix(true);
  23728. }
  23729. var bbox = mesh.getBoundingInfo().boundingBox;
  23730. // The delta between the mesh position and the mesh bounding box center
  23731. var deltaPosition = mesh.position.subtract(bbox.center);
  23732. // Transform delta position with the rotation
  23733. if (initialRotation) {
  23734. var m = new BABYLON.Matrix();
  23735. initialRotation.toRotationMatrix(m);
  23736. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23737. }
  23738. // register mesh
  23739. switch (impostor) {
  23740. case BABYLON.PhysicsEngine.SphereImpostor:
  23741. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23742. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23743. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23744. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23745. body = new OIMO.Body({
  23746. type: 'sphere',
  23747. size: [size],
  23748. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23749. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23750. move: options.mass != 0,
  23751. config: [options.mass, options.friction, options.restitution],
  23752. world: this._world
  23753. });
  23754. break;
  23755. case BABYLON.PhysicsEngine.PlaneImpostor:
  23756. //Oimo "fakes" a cylinder as a box, so why don't we!
  23757. case BABYLON.PhysicsEngine.CylinderImpostor:
  23758. case BABYLON.PhysicsEngine.BoxImpostor:
  23759. var min = bbox.minimumWorld;
  23760. var max = bbox.maximumWorld;
  23761. var box = max.subtract(min);
  23762. var sizeX = this._checkWithEpsilon(box.x);
  23763. var sizeY = this._checkWithEpsilon(box.y);
  23764. var sizeZ = this._checkWithEpsilon(box.z);
  23765. body = new OIMO.Body({
  23766. type: 'box',
  23767. size: [sizeX, sizeY, sizeZ],
  23768. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23769. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23770. move: options.mass != 0,
  23771. config: [options.mass, options.friction, options.restitution],
  23772. world: this._world
  23773. });
  23774. break;
  23775. }
  23776. //If quaternion was set as the rotation of the object
  23777. if (initialRotation) {
  23778. //We have to access the rigid body's properties to set the quaternion.
  23779. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23780. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23781. //update the internal rotation matrix
  23782. body.body.syncShapes();
  23783. }
  23784. this._registeredMeshes.push({
  23785. mesh: mesh,
  23786. body: body,
  23787. delta: deltaPosition
  23788. });
  23789. return body;
  23790. };
  23791. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23792. var types = [], sizes = [], positions = [], rotations = [];
  23793. var initialMesh = parts[0].mesh;
  23794. for (var index = 0; index < parts.length; index++) {
  23795. var part = parts[index];
  23796. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23797. types.push(bodyParameters.type);
  23798. sizes.push.apply(sizes, bodyParameters.size);
  23799. positions.push.apply(positions, bodyParameters.pos);
  23800. rotations.push.apply(rotations, bodyParameters.rot);
  23801. }
  23802. var body = new OIMO.Body({
  23803. type: types,
  23804. size: sizes,
  23805. pos: positions,
  23806. rot: rotations,
  23807. move: options.mass != 0,
  23808. config: [options.mass, options.friction, options.restitution],
  23809. world: this._world
  23810. });
  23811. this._registeredMeshes.push({
  23812. mesh: initialMesh,
  23813. body: body
  23814. });
  23815. return body;
  23816. };
  23817. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23818. var bodyParameters = null;
  23819. var mesh = part.mesh;
  23820. // We need the bounding box/sphere info to compute the physics body
  23821. mesh.computeWorldMatrix();
  23822. switch (part.impostor) {
  23823. case BABYLON.PhysicsEngine.SphereImpostor:
  23824. var bbox = mesh.getBoundingInfo().boundingBox;
  23825. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23826. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23827. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23828. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23829. bodyParameters = {
  23830. type: 'sphere',
  23831. /* bug with oimo : sphere needs 3 sizes in this case */
  23832. size: [size, -1, -1],
  23833. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23834. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23835. };
  23836. break;
  23837. case BABYLON.PhysicsEngine.PlaneImpostor:
  23838. case BABYLON.PhysicsEngine.BoxImpostor:
  23839. bbox = mesh.getBoundingInfo().boundingBox;
  23840. var min = bbox.minimumWorld;
  23841. var max = bbox.maximumWorld;
  23842. var box = max.subtract(min);
  23843. var sizeX = this._checkWithEpsilon(box.x);
  23844. var sizeY = this._checkWithEpsilon(box.y);
  23845. var sizeZ = this._checkWithEpsilon(box.z);
  23846. var relativePosition = mesh.position;
  23847. bodyParameters = {
  23848. type: 'box',
  23849. size: [sizeX, sizeY, sizeZ],
  23850. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23851. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23852. };
  23853. break;
  23854. }
  23855. return bodyParameters;
  23856. };
  23857. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23858. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23859. var registeredMesh = this._registeredMeshes[index];
  23860. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23861. if (registeredMesh.body) {
  23862. this._world.removeRigidBody(registeredMesh.body.body);
  23863. this._unbindBody(registeredMesh.body);
  23864. }
  23865. this._registeredMeshes.splice(index, 1);
  23866. return;
  23867. }
  23868. }
  23869. };
  23870. OimoJSPlugin.prototype._unbindBody = function (body) {
  23871. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23872. var registeredMesh = this._registeredMeshes[index];
  23873. if (registeredMesh.body === body) {
  23874. registeredMesh.body = null;
  23875. }
  23876. }
  23877. };
  23878. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23879. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23880. var registeredMesh = this._registeredMeshes[index];
  23881. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23882. // Get object mass to have a behaviour similar to cannon.js
  23883. var mass = registeredMesh.body.body.massInfo.mass;
  23884. // The force is scaled with the mass of object
  23885. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23886. return;
  23887. }
  23888. }
  23889. };
  23890. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23891. var body1 = null, body2 = null;
  23892. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23893. var registeredMesh = this._registeredMeshes[index];
  23894. if (registeredMesh.mesh === mesh1) {
  23895. body1 = registeredMesh.body.body;
  23896. }
  23897. else if (registeredMesh.mesh === mesh2) {
  23898. body2 = registeredMesh.body.body;
  23899. }
  23900. }
  23901. if (!body1 || !body2) {
  23902. return false;
  23903. }
  23904. if (!options) {
  23905. options = {};
  23906. }
  23907. new OIMO.Link({
  23908. type: options.type,
  23909. body1: body1,
  23910. body2: body2,
  23911. min: options.min,
  23912. max: options.max,
  23913. axe1: options.axe1,
  23914. axe2: options.axe2,
  23915. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23916. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23917. collision: options.collision,
  23918. spring: options.spring,
  23919. world: this._world
  23920. });
  23921. return true;
  23922. };
  23923. OimoJSPlugin.prototype.dispose = function () {
  23924. this._world.clear();
  23925. while (this._registeredMeshes.length) {
  23926. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23927. }
  23928. };
  23929. OimoJSPlugin.prototype.isSupported = function () {
  23930. return OIMO !== undefined;
  23931. };
  23932. OimoJSPlugin.prototype._getLastShape = function (body) {
  23933. var lastShape = body.shapes;
  23934. while (lastShape.next) {
  23935. lastShape = lastShape.next;
  23936. }
  23937. return lastShape;
  23938. };
  23939. OimoJSPlugin.prototype.runOneStep = function (time) {
  23940. this._world.step();
  23941. // Update the position of all registered meshes
  23942. var i = this._registeredMeshes.length;
  23943. var m;
  23944. while (i--) {
  23945. var body = this._registeredMeshes[i].body.body;
  23946. var mesh = this._registeredMeshes[i].mesh;
  23947. var delta = this._registeredMeshes[i].delta;
  23948. if (!body.sleeping) {
  23949. if (body.shapes.next) {
  23950. var parentShape = this._getLastShape(body);
  23951. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23952. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23953. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23954. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23955. if (!mesh.rotationQuaternion) {
  23956. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23957. }
  23958. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23959. mesh.computeWorldMatrix();
  23960. }
  23961. else {
  23962. m = body.getMatrix();
  23963. mtx = BABYLON.Matrix.FromArray(m);
  23964. // Body position
  23965. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23966. if (!delta) {
  23967. mesh.position.x = bodyX;
  23968. mesh.position.y = bodyY;
  23969. mesh.position.z = bodyZ;
  23970. }
  23971. else {
  23972. mesh.position.x = bodyX + delta.x;
  23973. mesh.position.y = bodyY + delta.y;
  23974. mesh.position.z = bodyZ + delta.z;
  23975. }
  23976. if (!mesh.rotationQuaternion) {
  23977. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23978. }
  23979. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23980. mesh.computeWorldMatrix();
  23981. }
  23982. }
  23983. }
  23984. };
  23985. return OimoJSPlugin;
  23986. })();
  23987. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23988. })(BABYLON || (BABYLON = {}));
  23989. var BABYLON;
  23990. (function (BABYLON) {
  23991. var PhysicsEngine = (function () {
  23992. function PhysicsEngine(plugin) {
  23993. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23994. }
  23995. PhysicsEngine.prototype._initialize = function (gravity) {
  23996. this._currentPlugin.initialize();
  23997. this._setGravity(gravity);
  23998. };
  23999. PhysicsEngine.prototype._runOneStep = function (delta) {
  24000. if (delta > 0.1) {
  24001. delta = 0.1;
  24002. }
  24003. else if (delta <= 0) {
  24004. delta = 1.0 / 60.0;
  24005. }
  24006. this._currentPlugin.runOneStep(delta);
  24007. };
  24008. PhysicsEngine.prototype._setGravity = function (gravity) {
  24009. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24010. this._currentPlugin.setGravity(this.gravity);
  24011. };
  24012. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  24013. return this._currentPlugin.registerMesh(mesh, impostor, options);
  24014. };
  24015. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  24016. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  24017. };
  24018. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  24019. this._currentPlugin.unregisterMesh(mesh);
  24020. };
  24021. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  24022. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  24023. };
  24024. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24025. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  24026. };
  24027. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  24028. this._currentPlugin.updateBodyPosition(mesh);
  24029. };
  24030. PhysicsEngine.prototype.dispose = function () {
  24031. this._currentPlugin.dispose();
  24032. };
  24033. PhysicsEngine.prototype.isSupported = function () {
  24034. return this._currentPlugin.isSupported();
  24035. };
  24036. // Statics
  24037. PhysicsEngine.NoImpostor = 0;
  24038. PhysicsEngine.SphereImpostor = 1;
  24039. PhysicsEngine.BoxImpostor = 2;
  24040. PhysicsEngine.PlaneImpostor = 3;
  24041. PhysicsEngine.MeshImpostor = 4;
  24042. PhysicsEngine.CapsuleImpostor = 5;
  24043. PhysicsEngine.ConeImpostor = 6;
  24044. PhysicsEngine.CylinderImpostor = 7;
  24045. PhysicsEngine.ConvexHullImpostor = 8;
  24046. PhysicsEngine.Epsilon = 0.001;
  24047. return PhysicsEngine;
  24048. })();
  24049. BABYLON.PhysicsEngine = PhysicsEngine;
  24050. })(BABYLON || (BABYLON = {}));
  24051. var BABYLON;
  24052. (function (BABYLON) {
  24053. var serializeLight = function (light) {
  24054. var serializationObject = {};
  24055. serializationObject.name = light.name;
  24056. serializationObject.id = light.id;
  24057. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24058. if (light instanceof BABYLON.PointLight) {
  24059. serializationObject.type = 0;
  24060. serializationObject.position = (light).position.asArray();
  24061. }
  24062. else if (light instanceof BABYLON.DirectionalLight) {
  24063. serializationObject.type = 1;
  24064. var directionalLight = light;
  24065. serializationObject.position = directionalLight.position.asArray();
  24066. serializationObject.direction = directionalLight.direction.asArray();
  24067. }
  24068. else if (light instanceof BABYLON.SpotLight) {
  24069. serializationObject.type = 2;
  24070. var spotLight = light;
  24071. serializationObject.position = spotLight.position.asArray();
  24072. serializationObject.direction = spotLight.position.asArray();
  24073. serializationObject.angle = spotLight.angle;
  24074. serializationObject.exponent = spotLight.exponent;
  24075. }
  24076. else if (light instanceof BABYLON.HemisphericLight) {
  24077. serializationObject.type = 3;
  24078. var hemisphericLight = light;
  24079. serializationObject.direction = hemisphericLight.direction.asArray();
  24080. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24081. }
  24082. if (light.intensity) {
  24083. serializationObject.intensity = light.intensity;
  24084. }
  24085. serializationObject.range = light.range;
  24086. serializationObject.diffuse = light.diffuse.asArray();
  24087. serializationObject.specular = light.specular.asArray();
  24088. return serializationObject;
  24089. };
  24090. var serializeFresnelParameter = function (fresnelParameter) {
  24091. var serializationObject = {};
  24092. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24093. serializationObject.leftColor = fresnelParameter.leftColor;
  24094. serializationObject.rightColor = fresnelParameter.rightColor;
  24095. serializationObject.bias = fresnelParameter.bias;
  24096. serializationObject.power = fresnelParameter.power;
  24097. return serializationObject;
  24098. };
  24099. var serializeAnimation;
  24100. var appendAnimations = function (source, destination) {
  24101. if (source.animations) {
  24102. destination.animations = [];
  24103. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24104. var animation = source.animations[animationIndex];
  24105. destination.animations.push(serializeAnimation(animation));
  24106. }
  24107. }
  24108. };
  24109. var serializeCamera = function (camera) {
  24110. var serializationObject = {};
  24111. serializationObject.name = camera.name;
  24112. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24113. serializationObject.id = camera.id;
  24114. serializationObject.position = camera.position.asArray();
  24115. // Parent
  24116. if (camera.parent) {
  24117. serializationObject.parentId = camera.parent.id;
  24118. }
  24119. serializationObject.fov = camera.fov;
  24120. serializationObject.minZ = camera.minZ;
  24121. serializationObject.maxZ = camera.maxZ;
  24122. serializationObject.inertia = camera.inertia;
  24123. //setting the type
  24124. if (camera instanceof BABYLON.FreeCamera) {
  24125. serializationObject.type = "FreeCamera";
  24126. }
  24127. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24128. serializationObject.type = "ArcRotateCamera";
  24129. }
  24130. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24131. serializationObject.type = "AnaglyphArcRotateCamera";
  24132. }
  24133. else if (camera instanceof BABYLON.GamepadCamera) {
  24134. serializationObject.type = "GamepadCamera";
  24135. }
  24136. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24137. serializationObject.type = "AnaglyphFreeCamera";
  24138. }
  24139. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24140. serializationObject.type = "DeviceOrientationCamera";
  24141. }
  24142. else if (camera instanceof BABYLON.FollowCamera) {
  24143. serializationObject.type = "FollowCamera";
  24144. }
  24145. else if (camera instanceof BABYLON.TouchCamera) {
  24146. serializationObject.type = "TouchCamera";
  24147. }
  24148. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24149. serializationObject.type = "VirtualJoysticksCamera";
  24150. }
  24151. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24152. serializationObject.type = "WebVRFreeCamera";
  24153. }
  24154. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24155. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24156. }
  24157. //special properties of specific cameras
  24158. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24159. var arcCamera = camera;
  24160. serializationObject.alpha = arcCamera.alpha;
  24161. serializationObject.beta = arcCamera.beta;
  24162. serializationObject.radius = arcCamera.radius;
  24163. if (arcCamera.target && arcCamera.target.id) {
  24164. serializationObject.lockedTargetId = arcCamera.target.id;
  24165. }
  24166. }
  24167. else if (camera instanceof BABYLON.FollowCamera) {
  24168. var followCam = camera;
  24169. serializationObject.radius = followCam.radius;
  24170. serializationObject.heightOffset = followCam.heightOffset;
  24171. serializationObject.rotationOffset = followCam.rotationOffset;
  24172. }
  24173. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24174. //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.
  24175. if (camera['_interaxialDistance'] !== undefined) {
  24176. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24177. }
  24178. }
  24179. //general properties that not all cameras have. The [] is due to typescript's type safety
  24180. if (camera['speed'] !== undefined) {
  24181. serializationObject.speed = camera['speed'];
  24182. }
  24183. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24184. serializationObject.target = camera['target'].asArray();
  24185. }
  24186. // Target
  24187. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24188. serializationObject.rotation = camera['rotation'].asArray();
  24189. }
  24190. // Locked target
  24191. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24192. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24193. }
  24194. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24195. serializationObject.applyGravity = camera['applyGravity'] || false;
  24196. if (camera['ellipsoid']) {
  24197. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24198. }
  24199. // Animations
  24200. appendAnimations(camera, serializationObject);
  24201. // Layer mask
  24202. serializationObject.layerMask = camera.layerMask;
  24203. return serializationObject;
  24204. };
  24205. serializeAnimation = function (animation) {
  24206. var serializationObject = {};
  24207. serializationObject.name = animation.name;
  24208. serializationObject.property = animation.targetProperty;
  24209. serializationObject.framePerSecond = animation.framePerSecond;
  24210. serializationObject.dataType = animation.dataType;
  24211. serializationObject.loopBehavior = animation.loopMode;
  24212. var dataType = animation.dataType;
  24213. serializationObject.keys = [];
  24214. var keys = animation.getKeys();
  24215. for (var index = 0; index < keys.length; index++) {
  24216. var animationKey = keys[index];
  24217. var key = {};
  24218. key.frame = animationKey.frame;
  24219. switch (dataType) {
  24220. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24221. key.values = [animationKey.value];
  24222. break;
  24223. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24224. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24225. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24226. key.values = animationKey.value.asArray();
  24227. break;
  24228. }
  24229. serializationObject.keys.push(key);
  24230. }
  24231. return serializationObject;
  24232. };
  24233. var serializeMultiMaterial = function (material) {
  24234. var serializationObject = {};
  24235. serializationObject.name = material.name;
  24236. serializationObject.id = material.id;
  24237. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24238. serializationObject.materials = [];
  24239. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24240. var subMat = material.subMaterials[matIndex];
  24241. if (subMat) {
  24242. serializationObject.materials.push(subMat.id);
  24243. }
  24244. else {
  24245. serializationObject.materials.push(null);
  24246. }
  24247. }
  24248. return serializationObject;
  24249. };
  24250. var serializeTexture;
  24251. var serializeMaterial = function (material) {
  24252. var serializationObject = {};
  24253. serializationObject.name = material.name;
  24254. serializationObject.ambient = material.ambientColor.asArray();
  24255. serializationObject.diffuse = material.diffuseColor.asArray();
  24256. serializationObject.specular = material.specularColor.asArray();
  24257. serializationObject.specularPower = material.specularPower;
  24258. serializationObject.emissive = material.emissiveColor.asArray();
  24259. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24260. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24261. serializationObject.alpha = material.alpha;
  24262. serializationObject.id = material.id;
  24263. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24264. serializationObject.backFaceCulling = material.backFaceCulling;
  24265. if (material.diffuseTexture) {
  24266. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24267. }
  24268. if (material.diffuseFresnelParameters) {
  24269. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24270. }
  24271. if (material.ambientTexture) {
  24272. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24273. }
  24274. if (material.opacityTexture) {
  24275. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24276. }
  24277. if (material.opacityFresnelParameters) {
  24278. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24279. }
  24280. if (material.reflectionTexture) {
  24281. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24282. }
  24283. if (material.reflectionFresnelParameters) {
  24284. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24285. }
  24286. if (material.emissiveTexture) {
  24287. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24288. }
  24289. if (material.lightmapTexture) {
  24290. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24291. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24292. }
  24293. if (material.emissiveFresnelParameters) {
  24294. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24295. }
  24296. if (material.specularTexture) {
  24297. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24298. }
  24299. if (material.bumpTexture) {
  24300. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24301. }
  24302. return serializationObject;
  24303. };
  24304. serializeTexture = function (texture) {
  24305. var serializationObject = {};
  24306. if (!texture.name) {
  24307. return null;
  24308. }
  24309. if (texture instanceof BABYLON.CubeTexture) {
  24310. serializationObject.name = texture.name;
  24311. serializationObject.hasAlpha = texture.hasAlpha;
  24312. serializationObject.isCube = true;
  24313. serializationObject.level = texture.level;
  24314. serializationObject.coordinatesMode = texture.coordinatesMode;
  24315. return serializationObject;
  24316. }
  24317. var index;
  24318. if (texture instanceof BABYLON.MirrorTexture) {
  24319. var mirrorTexture = texture;
  24320. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24321. serializationObject.renderList = [];
  24322. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24323. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24324. }
  24325. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24326. }
  24327. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24328. var renderTargetTexture = texture;
  24329. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24330. serializationObject.renderList = [];
  24331. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24332. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24333. }
  24334. }
  24335. var regularTexture = texture;
  24336. serializationObject.name = texture.name;
  24337. serializationObject.hasAlpha = texture.hasAlpha;
  24338. serializationObject.level = texture.level;
  24339. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24340. serializationObject.coordinatesMode = texture.coordinatesMode;
  24341. serializationObject.uOffset = regularTexture.uOffset;
  24342. serializationObject.vOffset = regularTexture.vOffset;
  24343. serializationObject.uScale = regularTexture.uScale;
  24344. serializationObject.vScale = regularTexture.vScale;
  24345. serializationObject.uAng = regularTexture.uAng;
  24346. serializationObject.vAng = regularTexture.vAng;
  24347. serializationObject.wAng = regularTexture.wAng;
  24348. serializationObject.wrapU = texture.wrapU;
  24349. serializationObject.wrapV = texture.wrapV;
  24350. // Animations
  24351. appendAnimations(texture, serializationObject);
  24352. return serializationObject;
  24353. };
  24354. var serializeSkeleton = function (skeleton) {
  24355. var serializationObject = {};
  24356. serializationObject.name = skeleton.name;
  24357. serializationObject.id = skeleton.id;
  24358. serializationObject.bones = [];
  24359. for (var index = 0; index < skeleton.bones.length; index++) {
  24360. var bone = skeleton.bones[index];
  24361. var serializedBone = {
  24362. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24363. name: bone.name,
  24364. matrix: bone.getLocalMatrix().toArray()
  24365. };
  24366. serializationObject.bones.push(serializedBone);
  24367. if (bone.animations && bone.animations.length > 0) {
  24368. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24369. }
  24370. }
  24371. return serializationObject;
  24372. };
  24373. var serializeParticleSystem = function (particleSystem) {
  24374. var serializationObject = {};
  24375. serializationObject.emitterId = particleSystem.emitter.id;
  24376. serializationObject.capacity = particleSystem.getCapacity();
  24377. if (particleSystem.particleTexture) {
  24378. serializationObject.textureName = particleSystem.particleTexture.name;
  24379. }
  24380. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24381. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24382. serializationObject.minSize = particleSystem.minSize;
  24383. serializationObject.maxSize = particleSystem.maxSize;
  24384. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24385. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24386. serializationObject.emitRate = particleSystem.emitRate;
  24387. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24388. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24389. serializationObject.gravity = particleSystem.gravity.asArray();
  24390. serializationObject.direction1 = particleSystem.direction1.asArray();
  24391. serializationObject.direction2 = particleSystem.direction2.asArray();
  24392. serializationObject.color1 = particleSystem.color1.asArray();
  24393. serializationObject.color2 = particleSystem.color2.asArray();
  24394. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24395. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24396. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24397. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24398. serializationObject.blendMode = particleSystem.blendMode;
  24399. return serializationObject;
  24400. };
  24401. var serializeLensFlareSystem = function (lensFlareSystem) {
  24402. var serializationObject = {};
  24403. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24404. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24405. serializationObject.flares = [];
  24406. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24407. var flare = lensFlareSystem.lensFlares[index];
  24408. serializationObject.flares.push({
  24409. size: flare.size,
  24410. position: flare.position,
  24411. color: flare.color.asArray(),
  24412. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24413. });
  24414. }
  24415. return serializationObject;
  24416. };
  24417. var serializeShadowGenerator = function (light) {
  24418. var serializationObject = {};
  24419. var shadowGenerator = light.getShadowGenerator();
  24420. serializationObject.lightId = light.id;
  24421. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24422. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24423. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24424. serializationObject.renderList = [];
  24425. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24426. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24427. serializationObject.renderList.push(mesh.id);
  24428. }
  24429. return serializationObject;
  24430. };
  24431. var serializedGeometries = [];
  24432. var serializeVertexData;
  24433. var serializeTorusKnot;
  24434. var serializePlane;
  24435. var serializeGround;
  24436. var serializeTorus;
  24437. var serializeCylinder;
  24438. var serializeSphere;
  24439. var serializeBox;
  24440. var serializeGeometry = function (geometry, serializationGeometries) {
  24441. if (serializedGeometries[geometry.id]) {
  24442. return;
  24443. }
  24444. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24445. serializationGeometries.boxes.push(serializeBox(geometry));
  24446. }
  24447. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24448. serializationGeometries.spheres.push(serializeSphere(geometry));
  24449. }
  24450. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24451. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24452. }
  24453. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24454. serializationGeometries.toruses.push(serializeTorus(geometry));
  24455. }
  24456. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24457. serializationGeometries.grounds.push(serializeGround(geometry));
  24458. }
  24459. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24460. serializationGeometries.planes.push(serializePlane(geometry));
  24461. }
  24462. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24463. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24464. }
  24465. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24466. throw new Error("Unknown primitive type");
  24467. }
  24468. else {
  24469. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24470. }
  24471. serializedGeometries[geometry.id] = true;
  24472. };
  24473. var serializeGeometryBase = function (geometry) {
  24474. var serializationObject = {};
  24475. serializationObject.id = geometry.id;
  24476. if (BABYLON.Tags.HasTags(geometry)) {
  24477. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24478. }
  24479. return serializationObject;
  24480. };
  24481. serializeVertexData = function (vertexData) {
  24482. var serializationObject = serializeGeometryBase(vertexData);
  24483. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24484. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24485. }
  24486. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24487. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24488. }
  24489. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24490. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24491. }
  24492. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24493. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24494. }
  24495. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24496. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24497. }
  24498. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24499. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24500. }
  24501. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24502. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24503. }
  24504. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24505. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24506. }
  24507. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24508. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24509. }
  24510. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24511. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24512. serializationObject.matricesIndices._isExpanded = true;
  24513. }
  24514. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24515. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24516. }
  24517. serializationObject.indices = vertexData.getIndices();
  24518. return serializationObject;
  24519. };
  24520. var serializePrimitive = function (primitive) {
  24521. var serializationObject = serializeGeometryBase(primitive);
  24522. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24523. return serializationObject;
  24524. };
  24525. serializeBox = function (box) {
  24526. var serializationObject = serializePrimitive(box);
  24527. serializationObject.size = box.size;
  24528. return serializationObject;
  24529. };
  24530. serializeSphere = function (sphere) {
  24531. var serializationObject = serializePrimitive(sphere);
  24532. serializationObject.segments = sphere.segments;
  24533. serializationObject.diameter = sphere.diameter;
  24534. return serializationObject;
  24535. };
  24536. serializeCylinder = function (cylinder) {
  24537. var serializationObject = serializePrimitive(cylinder);
  24538. serializationObject.height = cylinder.height;
  24539. serializationObject.diameterTop = cylinder.diameterTop;
  24540. serializationObject.diameterBottom = cylinder.diameterBottom;
  24541. serializationObject.tessellation = cylinder.tessellation;
  24542. return serializationObject;
  24543. };
  24544. serializeTorus = function (torus) {
  24545. var serializationObject = serializePrimitive(torus);
  24546. serializationObject.diameter = torus.diameter;
  24547. serializationObject.thickness = torus.thickness;
  24548. serializationObject.tessellation = torus.tessellation;
  24549. return serializationObject;
  24550. };
  24551. serializeGround = function (ground) {
  24552. var serializationObject = serializePrimitive(ground);
  24553. serializationObject.width = ground.width;
  24554. serializationObject.height = ground.height;
  24555. serializationObject.subdivisions = ground.subdivisions;
  24556. return serializationObject;
  24557. };
  24558. serializePlane = function (plane) {
  24559. var serializationObject = serializePrimitive(plane);
  24560. serializationObject.size = plane.size;
  24561. return serializationObject;
  24562. };
  24563. serializeTorusKnot = function (torusKnot) {
  24564. var serializationObject = serializePrimitive(torusKnot);
  24565. serializationObject.radius = torusKnot.radius;
  24566. serializationObject.tube = torusKnot.tube;
  24567. serializationObject.radialSegments = torusKnot.radialSegments;
  24568. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24569. serializationObject.p = torusKnot.p;
  24570. serializationObject.q = torusKnot.q;
  24571. return serializationObject;
  24572. };
  24573. var serializeMesh = function (mesh, serializationScene) {
  24574. var serializationObject = {};
  24575. serializationObject.name = mesh.name;
  24576. serializationObject.id = mesh.id;
  24577. if (BABYLON.Tags.HasTags(mesh)) {
  24578. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24579. }
  24580. serializationObject.position = mesh.position.asArray();
  24581. if (mesh.rotationQuaternion) {
  24582. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24583. }
  24584. else if (mesh.rotation) {
  24585. serializationObject.rotation = mesh.rotation.asArray();
  24586. }
  24587. serializationObject.scaling = mesh.scaling.asArray();
  24588. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24589. serializationObject.isEnabled = mesh.isEnabled();
  24590. serializationObject.isVisible = mesh.isVisible;
  24591. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24592. serializationObject.pickable = mesh.isPickable;
  24593. serializationObject.receiveShadows = mesh.receiveShadows;
  24594. serializationObject.billboardMode = mesh.billboardMode;
  24595. serializationObject.visibility = mesh.visibility;
  24596. serializationObject.checkCollisions = mesh.checkCollisions;
  24597. // Parent
  24598. if (mesh.parent) {
  24599. serializationObject.parentId = mesh.parent.id;
  24600. }
  24601. // Geometry
  24602. var geometry = mesh._geometry;
  24603. if (geometry) {
  24604. var geometryId = geometry.id;
  24605. serializationObject.geometryId = geometryId;
  24606. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24607. // 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
  24608. serializeGeometry(geometry, serializationScene.geometries);
  24609. }
  24610. // SubMeshes
  24611. serializationObject.subMeshes = [];
  24612. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24613. var subMesh = mesh.subMeshes[subIndex];
  24614. serializationObject.subMeshes.push({
  24615. materialIndex: subMesh.materialIndex,
  24616. verticesStart: subMesh.verticesStart,
  24617. verticesCount: subMesh.verticesCount,
  24618. indexStart: subMesh.indexStart,
  24619. indexCount: subMesh.indexCount
  24620. });
  24621. }
  24622. }
  24623. // Material
  24624. if (mesh.material) {
  24625. serializationObject.materialId = mesh.material.id;
  24626. }
  24627. else {
  24628. mesh.material = null;
  24629. }
  24630. // Skeleton
  24631. if (mesh.skeleton) {
  24632. serializationObject.skeletonId = mesh.skeleton.id;
  24633. }
  24634. // Physics
  24635. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24636. serializationObject.physicsMass = mesh.getPhysicsMass();
  24637. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24638. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24639. switch (mesh.getPhysicsImpostor()) {
  24640. case BABYLON.PhysicsEngine.BoxImpostor:
  24641. serializationObject.physicsImpostor = 1;
  24642. break;
  24643. case BABYLON.PhysicsEngine.SphereImpostor:
  24644. serializationObject.physicsImpostor = 2;
  24645. break;
  24646. }
  24647. }
  24648. // Instances
  24649. serializationObject.instances = [];
  24650. for (var index = 0; index < mesh.instances.length; index++) {
  24651. var instance = mesh.instances[index];
  24652. var serializationInstance = {
  24653. name: instance.name,
  24654. position: instance.position,
  24655. rotation: instance.rotation,
  24656. rotationQuaternion: instance.rotationQuaternion,
  24657. scaling: instance.scaling
  24658. };
  24659. serializationObject.instances.push(serializationInstance);
  24660. // Animations
  24661. appendAnimations(instance, serializationInstance);
  24662. }
  24663. // Animations
  24664. appendAnimations(mesh, serializationObject);
  24665. // Layer mask
  24666. serializationObject.layerMask = mesh.layerMask;
  24667. return serializationObject;
  24668. };
  24669. var finalizeSingleMesh = function (mesh, serializationObject) {
  24670. //only works if the mesh is already loaded
  24671. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24672. //serialize material
  24673. if (mesh.material) {
  24674. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24675. serializationObject.materials = serializationObject.materials || [];
  24676. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24677. serializationObject.materials.push(serializeMaterial(mesh.material));
  24678. }
  24679. }
  24680. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24681. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24682. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  24683. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24684. }
  24685. }
  24686. }
  24687. //serialize geometry
  24688. var geometry = mesh._geometry;
  24689. if (geometry) {
  24690. if (!serializationObject.geometries) {
  24691. serializationObject.geometries = {};
  24692. serializationObject.geometries.boxes = [];
  24693. serializationObject.geometries.spheres = [];
  24694. serializationObject.geometries.cylinders = [];
  24695. serializationObject.geometries.toruses = [];
  24696. serializationObject.geometries.grounds = [];
  24697. serializationObject.geometries.planes = [];
  24698. serializationObject.geometries.torusKnots = [];
  24699. serializationObject.geometries.vertexData = [];
  24700. }
  24701. serializeGeometry(geometry, serializationObject.geometries);
  24702. }
  24703. // Skeletons
  24704. if (mesh.skeleton) {
  24705. serializationObject.skeletons = serializationObject.skeletons || [];
  24706. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24707. }
  24708. //serialize the actual mesh
  24709. serializationObject.meshes = serializationObject.meshes || [];
  24710. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24711. }
  24712. };
  24713. var SceneSerializer = (function () {
  24714. function SceneSerializer() {
  24715. }
  24716. SceneSerializer.Serialize = function (scene) {
  24717. var serializationObject = {};
  24718. // Scene
  24719. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24720. serializationObject.autoClear = scene.autoClear;
  24721. serializationObject.clearColor = scene.clearColor.asArray();
  24722. serializationObject.ambientColor = scene.ambientColor.asArray();
  24723. serializationObject.gravity = scene.gravity.asArray();
  24724. // Fog
  24725. if (scene.fogMode && scene.fogMode !== 0) {
  24726. serializationObject.fogMode = scene.fogMode;
  24727. serializationObject.fogColor = scene.fogColor.asArray();
  24728. serializationObject.fogStart = scene.fogStart;
  24729. serializationObject.fogEnd = scene.fogEnd;
  24730. serializationObject.fogDensity = scene.fogDensity;
  24731. }
  24732. // Lights
  24733. serializationObject.lights = [];
  24734. var index;
  24735. var light;
  24736. for (index = 0; index < scene.lights.length; index++) {
  24737. light = scene.lights[index];
  24738. serializationObject.lights.push(serializeLight(light));
  24739. }
  24740. // Cameras
  24741. serializationObject.cameras = [];
  24742. for (index = 0; index < scene.cameras.length; index++) {
  24743. var camera = scene.cameras[index];
  24744. serializationObject.cameras.push(serializeCamera(camera));
  24745. }
  24746. if (scene.activeCamera) {
  24747. serializationObject.activeCameraID = scene.activeCamera.id;
  24748. }
  24749. // Materials
  24750. serializationObject.materials = [];
  24751. serializationObject.multiMaterials = [];
  24752. var material;
  24753. for (index = 0; index < scene.materials.length; index++) {
  24754. material = scene.materials[index];
  24755. serializationObject.materials.push(serializeMaterial(material));
  24756. }
  24757. // MultiMaterials
  24758. serializationObject.multiMaterials = [];
  24759. for (index = 0; index < scene.multiMaterials.length; index++) {
  24760. var multiMaterial = scene.multiMaterials[index];
  24761. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  24762. }
  24763. for (index = 0; index < scene.materials.length; index++) {
  24764. material = scene.materials[index];
  24765. if (material instanceof BABYLON.StandardMaterial) {
  24766. serializationObject.materials.push(serializeMaterial(material));
  24767. }
  24768. else if (material instanceof BABYLON.MultiMaterial) {
  24769. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24770. }
  24771. }
  24772. // Skeletons
  24773. serializationObject.skeletons = [];
  24774. for (index = 0; index < scene.skeletons.length; index++) {
  24775. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24776. }
  24777. // Geometries
  24778. serializationObject.geometries = {};
  24779. serializationObject.geometries.boxes = [];
  24780. serializationObject.geometries.spheres = [];
  24781. serializationObject.geometries.cylinders = [];
  24782. serializationObject.geometries.toruses = [];
  24783. serializationObject.geometries.grounds = [];
  24784. serializationObject.geometries.planes = [];
  24785. serializationObject.geometries.torusKnots = [];
  24786. serializationObject.geometries.vertexData = [];
  24787. serializedGeometries = [];
  24788. var geometries = scene.getGeometries();
  24789. for (index = 0; index < geometries.length; index++) {
  24790. var geometry = geometries[index];
  24791. if (geometry.isReady()) {
  24792. serializeGeometry(geometry, serializationObject.geometries);
  24793. }
  24794. }
  24795. // Meshes
  24796. serializationObject.meshes = [];
  24797. for (index = 0; index < scene.meshes.length; index++) {
  24798. var abstractMesh = scene.meshes[index];
  24799. if (abstractMesh instanceof BABYLON.Mesh) {
  24800. var mesh = abstractMesh;
  24801. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24802. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24803. }
  24804. }
  24805. }
  24806. // Particles Systems
  24807. serializationObject.particleSystems = [];
  24808. for (index = 0; index < scene.particleSystems.length; index++) {
  24809. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24810. }
  24811. // Lens flares
  24812. serializationObject.lensFlareSystems = [];
  24813. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24814. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24815. }
  24816. // Shadows
  24817. serializationObject.shadowGenerators = [];
  24818. for (index = 0; index < scene.lights.length; index++) {
  24819. light = scene.lights[index];
  24820. if (light.getShadowGenerator()) {
  24821. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24822. }
  24823. }
  24824. return serializationObject;
  24825. };
  24826. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24827. if (withParents === void 0) { withParents = false; }
  24828. if (withChildren === void 0) { withChildren = false; }
  24829. var serializationObject = {};
  24830. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24831. if (withParents || withChildren) {
  24832. //deliberate for loop! not for each, appended should be processed as well.
  24833. for (var i = 0; i < toSerialize.length; ++i) {
  24834. if (withChildren) {
  24835. toSerialize[i].getDescendants().forEach(function (node) {
  24836. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24837. toSerialize.push(node);
  24838. }
  24839. });
  24840. }
  24841. //make sure the array doesn't contain the object already
  24842. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24843. toSerialize.push(toSerialize[i].parent);
  24844. }
  24845. }
  24846. }
  24847. toSerialize.forEach(function (mesh) {
  24848. finalizeSingleMesh(mesh, serializationObject);
  24849. });
  24850. return serializationObject;
  24851. };
  24852. return SceneSerializer;
  24853. })();
  24854. BABYLON.SceneSerializer = SceneSerializer;
  24855. })(BABYLON || (BABYLON = {}));
  24856. var BABYLON;
  24857. (function (BABYLON) {
  24858. // Unique ID when we import meshes from Babylon to CSG
  24859. var currentCSGMeshId = 0;
  24860. // # class Vertex
  24861. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24862. // one to provide additional features like texture coordinates and vertex
  24863. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24864. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24865. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24866. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24867. // is not used anywhere else.
  24868. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24869. var Vertex = (function () {
  24870. function Vertex(pos, normal, uv) {
  24871. this.pos = pos;
  24872. this.normal = normal;
  24873. this.uv = uv;
  24874. }
  24875. Vertex.prototype.clone = function () {
  24876. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24877. };
  24878. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24879. // orientation of a polygon is flipped.
  24880. Vertex.prototype.flip = function () {
  24881. this.normal = this.normal.scale(-1);
  24882. };
  24883. // Create a new vertex between this vertex and `other` by linearly
  24884. // interpolating all properties using a parameter of `t`. Subclasses should
  24885. // override this to interpolate additional properties.
  24886. Vertex.prototype.interpolate = function (other, t) {
  24887. 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));
  24888. };
  24889. return Vertex;
  24890. })();
  24891. // # class Plane
  24892. // Represents a plane in 3D space.
  24893. var Plane = (function () {
  24894. function Plane(normal, w) {
  24895. this.normal = normal;
  24896. this.w = w;
  24897. }
  24898. Plane.FromPoints = function (a, b, c) {
  24899. var v0 = c.subtract(a);
  24900. var v1 = b.subtract(a);
  24901. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24902. return null;
  24903. }
  24904. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24905. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24906. };
  24907. Plane.prototype.clone = function () {
  24908. return new Plane(this.normal.clone(), this.w);
  24909. };
  24910. Plane.prototype.flip = function () {
  24911. this.normal.scaleInPlace(-1);
  24912. this.w = -this.w;
  24913. };
  24914. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24915. // fragments in the appropriate lists. Coplanar polygons go into either
  24916. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24917. // respect to this plane. Polygons in front or in back of this plane go into
  24918. // either `front` or `back`.
  24919. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24920. var COPLANAR = 0;
  24921. var FRONT = 1;
  24922. var BACK = 2;
  24923. var SPANNING = 3;
  24924. // Classify each point as well as the entire polygon into one of the above
  24925. // four classes.
  24926. var polygonType = 0;
  24927. var types = [];
  24928. for (var i = 0; i < polygon.vertices.length; i++) {
  24929. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24930. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24931. polygonType |= type;
  24932. types.push(type);
  24933. }
  24934. // Put the polygon in the correct list, splitting it when necessary.
  24935. switch (polygonType) {
  24936. case COPLANAR:
  24937. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24938. break;
  24939. case FRONT:
  24940. front.push(polygon);
  24941. break;
  24942. case BACK:
  24943. back.push(polygon);
  24944. break;
  24945. case SPANNING:
  24946. var f = [], b = [];
  24947. for (i = 0; i < polygon.vertices.length; i++) {
  24948. var j = (i + 1) % polygon.vertices.length;
  24949. var ti = types[i], tj = types[j];
  24950. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24951. if (ti != BACK)
  24952. f.push(vi);
  24953. if (ti != FRONT)
  24954. b.push(ti != BACK ? vi.clone() : vi);
  24955. if ((ti | tj) == SPANNING) {
  24956. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24957. var v = vi.interpolate(vj, t);
  24958. f.push(v);
  24959. b.push(v.clone());
  24960. }
  24961. }
  24962. if (f.length >= 3) {
  24963. var poly = new Polygon(f, polygon.shared);
  24964. if (poly.plane)
  24965. front.push(poly);
  24966. }
  24967. if (b.length >= 3) {
  24968. poly = new Polygon(b, polygon.shared);
  24969. if (poly.plane)
  24970. back.push(poly);
  24971. }
  24972. break;
  24973. }
  24974. };
  24975. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24976. // point is on the plane.
  24977. Plane.EPSILON = 1e-5;
  24978. return Plane;
  24979. })();
  24980. // # class Polygon
  24981. // Represents a convex polygon. The vertices used to initialize a polygon must
  24982. // be coplanar and form a convex loop.
  24983. //
  24984. // Each convex polygon has a `shared` property, which is shared between all
  24985. // polygons that are clones of each other or were split from the same polygon.
  24986. // This can be used to define per-polygon properties (such as surface color).
  24987. var Polygon = (function () {
  24988. function Polygon(vertices, shared) {
  24989. this.vertices = vertices;
  24990. this.shared = shared;
  24991. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24992. }
  24993. Polygon.prototype.clone = function () {
  24994. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24995. return new Polygon(vertices, this.shared);
  24996. };
  24997. Polygon.prototype.flip = function () {
  24998. this.vertices.reverse().map(function (v) { v.flip(); });
  24999. this.plane.flip();
  25000. };
  25001. return Polygon;
  25002. })();
  25003. // # class Node
  25004. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  25005. // by picking a polygon to split along. That polygon (and all other coplanar
  25006. // polygons) are added directly to that node and the other polygons are added to
  25007. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  25008. // no distinction between internal and leaf nodes.
  25009. var Node = (function () {
  25010. function Node(polygons) {
  25011. this.plane = null;
  25012. this.front = null;
  25013. this.back = null;
  25014. this.polygons = [];
  25015. if (polygons) {
  25016. this.build(polygons);
  25017. }
  25018. }
  25019. Node.prototype.clone = function () {
  25020. var node = new Node();
  25021. node.plane = this.plane && this.plane.clone();
  25022. node.front = this.front && this.front.clone();
  25023. node.back = this.back && this.back.clone();
  25024. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  25025. return node;
  25026. };
  25027. // Convert solid space to empty space and empty space to solid space.
  25028. Node.prototype.invert = function () {
  25029. for (var i = 0; i < this.polygons.length; i++) {
  25030. this.polygons[i].flip();
  25031. }
  25032. if (this.plane) {
  25033. this.plane.flip();
  25034. }
  25035. if (this.front) {
  25036. this.front.invert();
  25037. }
  25038. if (this.back) {
  25039. this.back.invert();
  25040. }
  25041. var temp = this.front;
  25042. this.front = this.back;
  25043. this.back = temp;
  25044. };
  25045. // Recursively remove all polygons in `polygons` that are inside this BSP
  25046. // tree.
  25047. Node.prototype.clipPolygons = function (polygons) {
  25048. if (!this.plane)
  25049. return polygons.slice();
  25050. var front = [], back = [];
  25051. for (var i = 0; i < polygons.length; i++) {
  25052. this.plane.splitPolygon(polygons[i], front, back, front, back);
  25053. }
  25054. if (this.front) {
  25055. front = this.front.clipPolygons(front);
  25056. }
  25057. if (this.back) {
  25058. back = this.back.clipPolygons(back);
  25059. }
  25060. else {
  25061. back = [];
  25062. }
  25063. return front.concat(back);
  25064. };
  25065. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25066. // `bsp`.
  25067. Node.prototype.clipTo = function (bsp) {
  25068. this.polygons = bsp.clipPolygons(this.polygons);
  25069. if (this.front)
  25070. this.front.clipTo(bsp);
  25071. if (this.back)
  25072. this.back.clipTo(bsp);
  25073. };
  25074. // Return a list of all polygons in this BSP tree.
  25075. Node.prototype.allPolygons = function () {
  25076. var polygons = this.polygons.slice();
  25077. if (this.front)
  25078. polygons = polygons.concat(this.front.allPolygons());
  25079. if (this.back)
  25080. polygons = polygons.concat(this.back.allPolygons());
  25081. return polygons;
  25082. };
  25083. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25084. // new polygons are filtered down to the bottom of the tree and become new
  25085. // nodes there. Each set of polygons is partitioned using the first polygon
  25086. // (no heuristic is used to pick a good split).
  25087. Node.prototype.build = function (polygons) {
  25088. if (!polygons.length)
  25089. return;
  25090. if (!this.plane)
  25091. this.plane = polygons[0].plane.clone();
  25092. var front = [], back = [];
  25093. for (var i = 0; i < polygons.length; i++) {
  25094. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25095. }
  25096. if (front.length) {
  25097. if (!this.front)
  25098. this.front = new Node();
  25099. this.front.build(front);
  25100. }
  25101. if (back.length) {
  25102. if (!this.back)
  25103. this.back = new Node();
  25104. this.back.build(back);
  25105. }
  25106. };
  25107. return Node;
  25108. })();
  25109. var CSG = (function () {
  25110. function CSG() {
  25111. this.polygons = new Array();
  25112. }
  25113. // Convert BABYLON.Mesh to BABYLON.CSG
  25114. CSG.FromMesh = function (mesh) {
  25115. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25116. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25117. if (mesh instanceof BABYLON.Mesh) {
  25118. mesh.computeWorldMatrix(true);
  25119. matrix = mesh.getWorldMatrix();
  25120. meshPosition = mesh.position.clone();
  25121. meshRotation = mesh.rotation.clone();
  25122. if (mesh.rotationQuaternion) {
  25123. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25124. }
  25125. meshScaling = mesh.scaling.clone();
  25126. }
  25127. else {
  25128. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25129. }
  25130. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25131. var subMeshes = mesh.subMeshes;
  25132. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25133. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25134. vertices = [];
  25135. for (var j = 0; j < 3; j++) {
  25136. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25137. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25138. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25139. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25140. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25141. vertex = new Vertex(position, normal, uv);
  25142. vertices.push(vertex);
  25143. }
  25144. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25145. // To handle the case of degenerated triangle
  25146. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25147. if (polygon.plane)
  25148. polygons.push(polygon);
  25149. }
  25150. }
  25151. var csg = CSG.FromPolygons(polygons);
  25152. csg.matrix = matrix;
  25153. csg.position = meshPosition;
  25154. csg.rotation = meshRotation;
  25155. csg.scaling = meshScaling;
  25156. csg.rotationQuaternion = meshRotationQuaternion;
  25157. currentCSGMeshId++;
  25158. return csg;
  25159. };
  25160. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25161. CSG.FromPolygons = function (polygons) {
  25162. var csg = new CSG();
  25163. csg.polygons = polygons;
  25164. return csg;
  25165. };
  25166. CSG.prototype.clone = function () {
  25167. var csg = new CSG();
  25168. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25169. csg.copyTransformAttributes(this);
  25170. return csg;
  25171. };
  25172. CSG.prototype.toPolygons = function () {
  25173. return this.polygons;
  25174. };
  25175. CSG.prototype.union = function (csg) {
  25176. var a = new Node(this.clone().polygons);
  25177. var b = new Node(csg.clone().polygons);
  25178. a.clipTo(b);
  25179. b.clipTo(a);
  25180. b.invert();
  25181. b.clipTo(a);
  25182. b.invert();
  25183. a.build(b.allPolygons());
  25184. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25185. };
  25186. CSG.prototype.unionInPlace = function (csg) {
  25187. var a = new Node(this.polygons);
  25188. var b = new Node(csg.polygons);
  25189. a.clipTo(b);
  25190. b.clipTo(a);
  25191. b.invert();
  25192. b.clipTo(a);
  25193. b.invert();
  25194. a.build(b.allPolygons());
  25195. this.polygons = a.allPolygons();
  25196. };
  25197. CSG.prototype.subtract = function (csg) {
  25198. var a = new Node(this.clone().polygons);
  25199. var b = new Node(csg.clone().polygons);
  25200. a.invert();
  25201. a.clipTo(b);
  25202. b.clipTo(a);
  25203. b.invert();
  25204. b.clipTo(a);
  25205. b.invert();
  25206. a.build(b.allPolygons());
  25207. a.invert();
  25208. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25209. };
  25210. CSG.prototype.subtractInPlace = function (csg) {
  25211. var a = new Node(this.polygons);
  25212. var b = new Node(csg.polygons);
  25213. a.invert();
  25214. a.clipTo(b);
  25215. b.clipTo(a);
  25216. b.invert();
  25217. b.clipTo(a);
  25218. b.invert();
  25219. a.build(b.allPolygons());
  25220. a.invert();
  25221. this.polygons = a.allPolygons();
  25222. };
  25223. CSG.prototype.intersect = function (csg) {
  25224. var a = new Node(this.clone().polygons);
  25225. var b = new Node(csg.clone().polygons);
  25226. a.invert();
  25227. b.clipTo(a);
  25228. b.invert();
  25229. a.clipTo(b);
  25230. b.clipTo(a);
  25231. a.build(b.allPolygons());
  25232. a.invert();
  25233. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25234. };
  25235. CSG.prototype.intersectInPlace = function (csg) {
  25236. var a = new Node(this.polygons);
  25237. var b = new Node(csg.polygons);
  25238. a.invert();
  25239. b.clipTo(a);
  25240. b.invert();
  25241. a.clipTo(b);
  25242. b.clipTo(a);
  25243. a.build(b.allPolygons());
  25244. a.invert();
  25245. this.polygons = a.allPolygons();
  25246. };
  25247. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25248. // not modified.
  25249. CSG.prototype.inverse = function () {
  25250. var csg = this.clone();
  25251. csg.inverseInPlace();
  25252. return csg;
  25253. };
  25254. CSG.prototype.inverseInPlace = function () {
  25255. this.polygons.map(function (p) { p.flip(); });
  25256. };
  25257. // This is used to keep meshes transformations so they can be restored
  25258. // when we build back a Babylon Mesh
  25259. // NB : All CSG operations are performed in world coordinates
  25260. CSG.prototype.copyTransformAttributes = function (csg) {
  25261. this.matrix = csg.matrix;
  25262. this.position = csg.position;
  25263. this.rotation = csg.rotation;
  25264. this.scaling = csg.scaling;
  25265. this.rotationQuaternion = csg.rotationQuaternion;
  25266. return this;
  25267. };
  25268. // Build Raw mesh from CSG
  25269. // Coordinates here are in world space
  25270. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25271. var matrix = this.matrix.clone();
  25272. matrix.invert();
  25273. 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;
  25274. if (keepSubMeshes) {
  25275. // Sort Polygons, since subMeshes are indices range
  25276. polygons.sort(function (a, b) {
  25277. if (a.shared.meshId === b.shared.meshId) {
  25278. return a.shared.subMeshId - b.shared.subMeshId;
  25279. }
  25280. else {
  25281. return a.shared.meshId - b.shared.meshId;
  25282. }
  25283. });
  25284. }
  25285. for (var i = 0, il = polygons.length; i < il; i++) {
  25286. polygon = polygons[i];
  25287. // Building SubMeshes
  25288. if (!subMesh_dict[polygon.shared.meshId]) {
  25289. subMesh_dict[polygon.shared.meshId] = {};
  25290. }
  25291. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25292. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25293. indexStart: +Infinity,
  25294. indexEnd: -Infinity,
  25295. materialIndex: polygon.shared.materialIndex
  25296. };
  25297. }
  25298. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25299. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25300. polygonIndices[0] = 0;
  25301. polygonIndices[1] = j - 1;
  25302. polygonIndices[2] = j;
  25303. for (var k = 0; k < 3; k++) {
  25304. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25305. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25306. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25307. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25308. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25309. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25310. // Check if 2 points can be merged
  25311. if (!(typeof vertex_idx !== 'undefined' &&
  25312. normals[vertex_idx * 3] === localNormal.x &&
  25313. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25314. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25315. uvs[vertex_idx * 2] === uv.x &&
  25316. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25317. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25318. uvs.push(uv.x, uv.y);
  25319. normals.push(normal.x, normal.y, normal.z);
  25320. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25321. }
  25322. indices.push(vertex_idx);
  25323. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25324. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25325. currentIndex++;
  25326. }
  25327. }
  25328. }
  25329. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25330. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25331. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25332. mesh.setIndices(indices);
  25333. if (keepSubMeshes) {
  25334. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25335. var materialIndexOffset = 0, materialMaxIndex;
  25336. mesh.subMeshes.length = 0;
  25337. for (var m in subMesh_dict) {
  25338. materialMaxIndex = -1;
  25339. for (var sm in subMesh_dict[m]) {
  25340. subMesh_obj = subMesh_dict[m][sm];
  25341. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25342. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25343. }
  25344. materialIndexOffset += ++materialMaxIndex;
  25345. }
  25346. }
  25347. return mesh;
  25348. };
  25349. // Build Mesh from CSG taking material and transforms into account
  25350. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25351. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25352. mesh.material = material;
  25353. mesh.position.copyFrom(this.position);
  25354. mesh.rotation.copyFrom(this.rotation);
  25355. if (this.rotationQuaternion) {
  25356. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25357. }
  25358. mesh.scaling.copyFrom(this.scaling);
  25359. mesh.computeWorldMatrix(true);
  25360. return mesh;
  25361. };
  25362. return CSG;
  25363. })();
  25364. BABYLON.CSG = CSG;
  25365. })(BABYLON || (BABYLON = {}));
  25366. var BABYLON;
  25367. (function (BABYLON) {
  25368. var VRDistortionCorrectionPostProcess = (function (_super) {
  25369. __extends(VRDistortionCorrectionPostProcess, _super);
  25370. //ANY
  25371. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25372. var _this = this;
  25373. _super.call(this, name, "vrDistortionCorrection", [
  25374. 'LensCenter',
  25375. 'Scale',
  25376. 'ScaleIn',
  25377. 'HmdWarpParam'
  25378. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25379. this._isRightEye = isRightEye;
  25380. this._distortionFactors = vrMetrics.distortionK;
  25381. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25382. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25383. this.onSizeChanged = function () {
  25384. _this.aspectRatio = _this.width * .5 / _this.height;
  25385. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25386. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25387. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25388. };
  25389. this.onApply = function (effect) {
  25390. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25391. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25392. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25393. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25394. };
  25395. }
  25396. return VRDistortionCorrectionPostProcess;
  25397. })(BABYLON.PostProcess);
  25398. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25399. })(BABYLON || (BABYLON = {}));
  25400. // Mainly based on these 2 articles :
  25401. // 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
  25402. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25403. var BABYLON;
  25404. (function (BABYLON) {
  25405. (function (JoystickAxis) {
  25406. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25407. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25408. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25409. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25410. var JoystickAxis = BABYLON.JoystickAxis;
  25411. var VirtualJoystick = (function () {
  25412. function VirtualJoystick(leftJoystick) {
  25413. var _this = this;
  25414. if (leftJoystick) {
  25415. this._leftJoystick = true;
  25416. }
  25417. else {
  25418. this._leftJoystick = false;
  25419. }
  25420. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25421. VirtualJoystick._globalJoystickIndex++;
  25422. // By default left & right arrow keys are moving the X
  25423. // and up & down keys are moving the Y
  25424. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25425. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25426. this.reverseLeftRight = false;
  25427. this.reverseUpDown = false;
  25428. // collections of pointers
  25429. this._touches = new BABYLON.SmartCollection();
  25430. this.deltaPosition = BABYLON.Vector3.Zero();
  25431. this._joystickSensibility = 25;
  25432. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25433. this._rotationSpeed = 25;
  25434. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25435. this._rotateOnAxisRelativeToMesh = false;
  25436. this._onResize = function (evt) {
  25437. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25438. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25439. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25440. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25441. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25442. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25443. };
  25444. // injecting a canvas element on top of the canvas 3D game
  25445. if (!VirtualJoystick.vjCanvas) {
  25446. window.addEventListener("resize", this._onResize, false);
  25447. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25448. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25449. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25450. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25451. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25452. VirtualJoystick.vjCanvas.style.width = "100%";
  25453. VirtualJoystick.vjCanvas.style.height = "100%";
  25454. VirtualJoystick.vjCanvas.style.position = "absolute";
  25455. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25456. VirtualJoystick.vjCanvas.style.top = "0px";
  25457. VirtualJoystick.vjCanvas.style.left = "0px";
  25458. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25459. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25460. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25461. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25462. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25463. document.body.appendChild(VirtualJoystick.vjCanvas);
  25464. }
  25465. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25466. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25467. this.pressed = false;
  25468. // default joystick color
  25469. this._joystickColor = "cyan";
  25470. this._joystickPointerID = -1;
  25471. // current joystick position
  25472. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25473. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25474. // origin joystick position
  25475. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25476. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25477. this._onPointerDownHandlerRef = function (evt) {
  25478. _this._onPointerDown(evt);
  25479. };
  25480. this._onPointerMoveHandlerRef = function (evt) {
  25481. _this._onPointerMove(evt);
  25482. };
  25483. this._onPointerOutHandlerRef = function (evt) {
  25484. _this._onPointerUp(evt);
  25485. };
  25486. this._onPointerUpHandlerRef = function (evt) {
  25487. _this._onPointerUp(evt);
  25488. };
  25489. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25490. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25491. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25492. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25493. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25494. evt.preventDefault(); // Disables system menu
  25495. }, false);
  25496. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25497. }
  25498. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25499. this._joystickSensibility = newJoystickSensibility;
  25500. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25501. };
  25502. VirtualJoystick.prototype._onPointerDown = function (e) {
  25503. var positionOnScreenCondition;
  25504. e.preventDefault();
  25505. if (this._leftJoystick === true) {
  25506. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25507. }
  25508. else {
  25509. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25510. }
  25511. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25512. // First contact will be dedicated to the virtual joystick
  25513. this._joystickPointerID = e.pointerId;
  25514. this._joystickPointerStartPos.x = e.clientX;
  25515. this._joystickPointerStartPos.y = e.clientY;
  25516. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25517. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25518. this._deltaJoystickVector.x = 0;
  25519. this._deltaJoystickVector.y = 0;
  25520. this.pressed = true;
  25521. this._touches.add(e.pointerId.toString(), e);
  25522. }
  25523. else {
  25524. // You can only trigger the action buttons with a joystick declared
  25525. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25526. this._action();
  25527. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25528. }
  25529. }
  25530. };
  25531. VirtualJoystick.prototype._onPointerMove = function (e) {
  25532. // If the current pointer is the one associated to the joystick (first touch contact)
  25533. if (this._joystickPointerID == e.pointerId) {
  25534. this._joystickPointerPos.x = e.clientX;
  25535. this._joystickPointerPos.y = e.clientY;
  25536. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25537. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25538. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25539. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25540. switch (this._axisTargetedByLeftAndRight) {
  25541. case JoystickAxis.X:
  25542. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25543. break;
  25544. case JoystickAxis.Y:
  25545. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25546. break;
  25547. case JoystickAxis.Z:
  25548. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25549. break;
  25550. }
  25551. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25552. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25553. switch (this._axisTargetedByUpAndDown) {
  25554. case JoystickAxis.X:
  25555. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25556. break;
  25557. case JoystickAxis.Y:
  25558. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25559. break;
  25560. case JoystickAxis.Z:
  25561. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25562. break;
  25563. }
  25564. }
  25565. else {
  25566. if (this._touches.item(e.pointerId.toString())) {
  25567. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25568. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25569. }
  25570. }
  25571. };
  25572. VirtualJoystick.prototype._onPointerUp = function (e) {
  25573. if (this._joystickPointerID == e.pointerId) {
  25574. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25575. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25576. this._joystickPointerID = -1;
  25577. this.pressed = false;
  25578. }
  25579. else {
  25580. var touch = this._touches.item(e.pointerId.toString());
  25581. if (touch) {
  25582. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25583. }
  25584. }
  25585. this._deltaJoystickVector.x = 0;
  25586. this._deltaJoystickVector.y = 0;
  25587. this._touches.remove(e.pointerId.toString());
  25588. };
  25589. /**
  25590. * Change the color of the virtual joystick
  25591. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25592. */
  25593. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25594. this._joystickColor = newColor;
  25595. };
  25596. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25597. this._action = action;
  25598. };
  25599. // Define which axis you'd like to control for left & right
  25600. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25601. switch (axis) {
  25602. case JoystickAxis.X:
  25603. case JoystickAxis.Y:
  25604. case JoystickAxis.Z:
  25605. this._axisTargetedByLeftAndRight = axis;
  25606. break;
  25607. default:
  25608. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25609. break;
  25610. }
  25611. };
  25612. // Define which axis you'd like to control for up & down
  25613. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25614. switch (axis) {
  25615. case JoystickAxis.X:
  25616. case JoystickAxis.Y:
  25617. case JoystickAxis.Z:
  25618. this._axisTargetedByUpAndDown = axis;
  25619. break;
  25620. default:
  25621. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25622. break;
  25623. }
  25624. };
  25625. VirtualJoystick.prototype._clearCanvas = function () {
  25626. if (this._leftJoystick) {
  25627. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25628. }
  25629. else {
  25630. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25631. }
  25632. };
  25633. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25634. var _this = this;
  25635. if (this.pressed) {
  25636. this._touches.forEach(function (touch) {
  25637. if (touch.pointerId === _this._joystickPointerID) {
  25638. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25639. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25640. VirtualJoystick.vjCanvasContext.beginPath();
  25641. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25642. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25643. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25644. VirtualJoystick.vjCanvasContext.stroke();
  25645. VirtualJoystick.vjCanvasContext.closePath();
  25646. VirtualJoystick.vjCanvasContext.beginPath();
  25647. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25648. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25649. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25650. VirtualJoystick.vjCanvasContext.stroke();
  25651. VirtualJoystick.vjCanvasContext.closePath();
  25652. VirtualJoystick.vjCanvasContext.beginPath();
  25653. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25654. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25655. VirtualJoystick.vjCanvasContext.stroke();
  25656. VirtualJoystick.vjCanvasContext.closePath();
  25657. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25658. }
  25659. else {
  25660. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25661. VirtualJoystick.vjCanvasContext.beginPath();
  25662. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25663. VirtualJoystick.vjCanvasContext.beginPath();
  25664. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25665. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25666. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25667. VirtualJoystick.vjCanvasContext.stroke();
  25668. VirtualJoystick.vjCanvasContext.closePath();
  25669. touch.prevX = touch.x;
  25670. touch.prevY = touch.y;
  25671. }
  25672. ;
  25673. });
  25674. }
  25675. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25676. };
  25677. VirtualJoystick.prototype.releaseCanvas = function () {
  25678. if (VirtualJoystick.vjCanvas) {
  25679. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25680. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25681. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25682. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25683. window.removeEventListener("resize", this._onResize);
  25684. document.body.removeChild(VirtualJoystick.vjCanvas);
  25685. VirtualJoystick.vjCanvas = null;
  25686. }
  25687. };
  25688. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25689. VirtualJoystick._globalJoystickIndex = 0;
  25690. return VirtualJoystick;
  25691. })();
  25692. BABYLON.VirtualJoystick = VirtualJoystick;
  25693. })(BABYLON || (BABYLON = {}));
  25694. var BABYLON;
  25695. (function (BABYLON) {
  25696. // We're mainly based on the logic defined into the FreeCamera code
  25697. var VirtualJoysticksCamera = (function (_super) {
  25698. __extends(VirtualJoysticksCamera, _super);
  25699. function VirtualJoysticksCamera(name, position, scene) {
  25700. _super.call(this, name, position, scene);
  25701. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25702. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25703. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25704. this._leftjoystick.setJoystickSensibility(0.15);
  25705. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25706. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25707. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25708. this._rightjoystick.reverseUpDown = true;
  25709. this._rightjoystick.setJoystickSensibility(0.05);
  25710. this._rightjoystick.setJoystickColor("yellow");
  25711. }
  25712. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25713. return this._leftjoystick;
  25714. };
  25715. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25716. return this._rightjoystick;
  25717. };
  25718. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25719. var speed = this._computeLocalCameraSpeed() * 50;
  25720. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25721. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25722. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25723. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25724. if (!this._leftjoystick.pressed) {
  25725. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25726. }
  25727. if (!this._rightjoystick.pressed) {
  25728. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25729. }
  25730. _super.prototype._checkInputs.call(this);
  25731. };
  25732. VirtualJoysticksCamera.prototype.dispose = function () {
  25733. this._leftjoystick.releaseCanvas();
  25734. _super.prototype.dispose.call(this);
  25735. };
  25736. return VirtualJoysticksCamera;
  25737. })(BABYLON.FreeCamera);
  25738. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25739. })(BABYLON || (BABYLON = {}));
  25740. var BABYLON;
  25741. (function (BABYLON) {
  25742. var ShaderMaterial = (function (_super) {
  25743. __extends(ShaderMaterial, _super);
  25744. function ShaderMaterial(name, scene, shaderPath, options) {
  25745. _super.call(this, name, scene);
  25746. this._textures = new Array();
  25747. this._floats = new Array();
  25748. this._floatsArrays = {};
  25749. this._colors3 = new Array();
  25750. this._colors4 = new Array();
  25751. this._vectors2 = new Array();
  25752. this._vectors3 = new Array();
  25753. this._vectors4 = new Array();
  25754. this._matrices = new Array();
  25755. this._matrices3x3 = new Array();
  25756. this._matrices2x2 = new Array();
  25757. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25758. this._shaderPath = shaderPath;
  25759. options.needAlphaBlending = options.needAlphaBlending || false;
  25760. options.needAlphaTesting = options.needAlphaTesting || false;
  25761. options.attributes = options.attributes || ["position", "normal", "uv"];
  25762. options.uniforms = options.uniforms || ["worldViewProjection"];
  25763. options.samplers = options.samplers || [];
  25764. options.defines = options.defines || [];
  25765. this._options = options;
  25766. }
  25767. ShaderMaterial.prototype.needAlphaBlending = function () {
  25768. return this._options.needAlphaBlending;
  25769. };
  25770. ShaderMaterial.prototype.needAlphaTesting = function () {
  25771. return this._options.needAlphaTesting;
  25772. };
  25773. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25774. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25775. this._options.uniforms.push(uniformName);
  25776. }
  25777. };
  25778. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25779. if (this._options.samplers.indexOf(name) === -1) {
  25780. this._options.samplers.push(name);
  25781. }
  25782. this._textures[name] = texture;
  25783. return this;
  25784. };
  25785. ShaderMaterial.prototype.setFloat = function (name, value) {
  25786. this._checkUniform(name);
  25787. this._floats[name] = value;
  25788. return this;
  25789. };
  25790. ShaderMaterial.prototype.setFloats = function (name, value) {
  25791. this._checkUniform(name);
  25792. this._floatsArrays[name] = value;
  25793. return this;
  25794. };
  25795. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25796. this._checkUniform(name);
  25797. this._colors3[name] = value;
  25798. return this;
  25799. };
  25800. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25801. this._checkUniform(name);
  25802. this._colors4[name] = value;
  25803. return this;
  25804. };
  25805. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25806. this._checkUniform(name);
  25807. this._vectors2[name] = value;
  25808. return this;
  25809. };
  25810. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25811. this._checkUniform(name);
  25812. this._vectors3[name] = value;
  25813. return this;
  25814. };
  25815. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25816. this._checkUniform(name);
  25817. this._vectors4[name] = value;
  25818. return this;
  25819. };
  25820. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25821. this._checkUniform(name);
  25822. this._matrices[name] = value;
  25823. return this;
  25824. };
  25825. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25826. this._checkUniform(name);
  25827. this._matrices3x3[name] = value;
  25828. return this;
  25829. };
  25830. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25831. this._checkUniform(name);
  25832. this._matrices2x2[name] = value;
  25833. return this;
  25834. };
  25835. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25836. var scene = this.getScene();
  25837. var engine = scene.getEngine();
  25838. if (!this.checkReadyOnEveryCall) {
  25839. if (this._renderId === scene.getRenderId()) {
  25840. return true;
  25841. }
  25842. }
  25843. // Instances
  25844. var defines = [];
  25845. var fallbacks = new BABYLON.EffectFallbacks();
  25846. if (useInstances) {
  25847. defines.push("#define INSTANCES");
  25848. }
  25849. for (var index = 0; index < this._options.defines.length; index++) {
  25850. defines.push(this._options.defines[index]);
  25851. }
  25852. // Bones
  25853. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25854. defines.push("#define BONES");
  25855. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25856. defines.push("#define BONES4");
  25857. fallbacks.addFallback(0, "BONES4");
  25858. }
  25859. // Alpha test
  25860. if (engine.getAlphaTesting()) {
  25861. defines.push("#define ALPHATEST");
  25862. }
  25863. var previousEffect = this._effect;
  25864. var join = defines.join("\n");
  25865. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25866. if (!this._effect.isReady()) {
  25867. return false;
  25868. }
  25869. if (previousEffect !== this._effect) {
  25870. scene.resetCachedMaterial();
  25871. }
  25872. this._renderId = scene.getRenderId();
  25873. return true;
  25874. };
  25875. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25876. var scene = this.getScene();
  25877. if (this._options.uniforms.indexOf("world") !== -1) {
  25878. this._effect.setMatrix("world", world);
  25879. }
  25880. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25881. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25882. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25883. }
  25884. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25885. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25886. }
  25887. };
  25888. ShaderMaterial.prototype.bind = function (world, mesh) {
  25889. // Std values
  25890. this.bindOnlyWorldMatrix(world);
  25891. if (this.getScene().getCachedMaterial() !== this) {
  25892. if (this._options.uniforms.indexOf("view") !== -1) {
  25893. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25894. }
  25895. if (this._options.uniforms.indexOf("projection") !== -1) {
  25896. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25897. }
  25898. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25899. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25900. }
  25901. // Bones
  25902. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25903. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25904. }
  25905. // Texture
  25906. for (var name in this._textures) {
  25907. this._effect.setTexture(name, this._textures[name]);
  25908. }
  25909. // Float
  25910. for (name in this._floats) {
  25911. this._effect.setFloat(name, this._floats[name]);
  25912. }
  25913. // Float s
  25914. for (name in this._floatsArrays) {
  25915. this._effect.setArray(name, this._floatsArrays[name]);
  25916. }
  25917. // Color3
  25918. for (name in this._colors3) {
  25919. this._effect.setColor3(name, this._colors3[name]);
  25920. }
  25921. // Color4
  25922. for (name in this._colors4) {
  25923. var color = this._colors4[name];
  25924. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25925. }
  25926. // Vector2
  25927. for (name in this._vectors2) {
  25928. this._effect.setVector2(name, this._vectors2[name]);
  25929. }
  25930. // Vector3
  25931. for (name in this._vectors3) {
  25932. this._effect.setVector3(name, this._vectors3[name]);
  25933. }
  25934. // Vector4
  25935. for (name in this._vectors4) {
  25936. this._effect.setVector4(name, this._vectors4[name]);
  25937. }
  25938. // Matrix
  25939. for (name in this._matrices) {
  25940. this._effect.setMatrix(name, this._matrices[name]);
  25941. }
  25942. // Matrix 3x3
  25943. for (name in this._matrices3x3) {
  25944. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25945. }
  25946. // Matrix 2x2
  25947. for (name in this._matrices2x2) {
  25948. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25949. }
  25950. }
  25951. _super.prototype.bind.call(this, world, mesh);
  25952. };
  25953. ShaderMaterial.prototype.clone = function (name) {
  25954. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25955. return newShaderMaterial;
  25956. };
  25957. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25958. for (var name in this._textures) {
  25959. this._textures[name].dispose();
  25960. }
  25961. this._textures = [];
  25962. _super.prototype.dispose.call(this, forceDisposeEffect);
  25963. };
  25964. return ShaderMaterial;
  25965. })(BABYLON.Material);
  25966. BABYLON.ShaderMaterial = ShaderMaterial;
  25967. })(BABYLON || (BABYLON = {}));
  25968. var BABYLON;
  25969. (function (BABYLON) {
  25970. var VertexData = (function () {
  25971. function VertexData() {
  25972. }
  25973. VertexData.prototype.set = function (data, kind) {
  25974. switch (kind) {
  25975. case BABYLON.VertexBuffer.PositionKind:
  25976. this.positions = data;
  25977. break;
  25978. case BABYLON.VertexBuffer.NormalKind:
  25979. this.normals = data;
  25980. break;
  25981. case BABYLON.VertexBuffer.UVKind:
  25982. this.uvs = data;
  25983. break;
  25984. case BABYLON.VertexBuffer.UV2Kind:
  25985. this.uvs2 = data;
  25986. break;
  25987. case BABYLON.VertexBuffer.UV3Kind:
  25988. this.uvs3 = data;
  25989. break;
  25990. case BABYLON.VertexBuffer.UV4Kind:
  25991. this.uvs4 = data;
  25992. break;
  25993. case BABYLON.VertexBuffer.UV5Kind:
  25994. this.uvs5 = data;
  25995. break;
  25996. case BABYLON.VertexBuffer.UV6Kind:
  25997. this.uvs6 = data;
  25998. break;
  25999. case BABYLON.VertexBuffer.ColorKind:
  26000. this.colors = data;
  26001. break;
  26002. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26003. this.matricesIndices = data;
  26004. break;
  26005. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26006. this.matricesWeights = data;
  26007. break;
  26008. }
  26009. };
  26010. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26011. this._applyTo(mesh, updatable);
  26012. };
  26013. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26014. this._applyTo(geometry, updatable);
  26015. };
  26016. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26017. this._update(mesh);
  26018. };
  26019. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26020. this._update(geometry);
  26021. };
  26022. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26023. if (this.positions) {
  26024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26025. }
  26026. if (this.normals) {
  26027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26028. }
  26029. if (this.uvs) {
  26030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26031. }
  26032. if (this.uvs2) {
  26033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26034. }
  26035. if (this.uvs3) {
  26036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26037. }
  26038. if (this.uvs4) {
  26039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26040. }
  26041. if (this.uvs5) {
  26042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26043. }
  26044. if (this.uvs6) {
  26045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26046. }
  26047. if (this.colors) {
  26048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26049. }
  26050. if (this.matricesIndices) {
  26051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26052. }
  26053. if (this.matricesWeights) {
  26054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26055. }
  26056. if (this.indices) {
  26057. meshOrGeometry.setIndices(this.indices);
  26058. }
  26059. };
  26060. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26061. if (this.positions) {
  26062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26063. }
  26064. if (this.normals) {
  26065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26066. }
  26067. if (this.uvs) {
  26068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26069. }
  26070. if (this.uvs2) {
  26071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26072. }
  26073. if (this.uvs3) {
  26074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26075. }
  26076. if (this.uvs4) {
  26077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26078. }
  26079. if (this.uvs5) {
  26080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26081. }
  26082. if (this.uvs6) {
  26083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26084. }
  26085. if (this.colors) {
  26086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26087. }
  26088. if (this.matricesIndices) {
  26089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26090. }
  26091. if (this.matricesWeights) {
  26092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26093. }
  26094. if (this.indices) {
  26095. meshOrGeometry.setIndices(this.indices);
  26096. }
  26097. };
  26098. VertexData.prototype.transform = function (matrix) {
  26099. var transformed = BABYLON.Vector3.Zero();
  26100. var index;
  26101. if (this.positions) {
  26102. var position = BABYLON.Vector3.Zero();
  26103. for (index = 0; index < this.positions.length; index += 3) {
  26104. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26105. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26106. this.positions[index] = transformed.x;
  26107. this.positions[index + 1] = transformed.y;
  26108. this.positions[index + 2] = transformed.z;
  26109. }
  26110. }
  26111. if (this.normals) {
  26112. var normal = BABYLON.Vector3.Zero();
  26113. for (index = 0; index < this.normals.length; index += 3) {
  26114. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26115. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26116. this.normals[index] = transformed.x;
  26117. this.normals[index + 1] = transformed.y;
  26118. this.normals[index + 2] = transformed.z;
  26119. }
  26120. }
  26121. };
  26122. VertexData.prototype.merge = function (other) {
  26123. var index;
  26124. if (other.indices) {
  26125. if (!this.indices) {
  26126. this.indices = [];
  26127. }
  26128. var offset = this.positions ? this.positions.length / 3 : 0;
  26129. for (index = 0; index < other.indices.length; index++) {
  26130. this.indices.push(other.indices[index] + offset);
  26131. }
  26132. }
  26133. if (other.positions) {
  26134. if (!this.positions) {
  26135. this.positions = [];
  26136. }
  26137. for (index = 0; index < other.positions.length; index++) {
  26138. this.positions.push(other.positions[index]);
  26139. }
  26140. }
  26141. if (other.normals) {
  26142. if (!this.normals) {
  26143. this.normals = [];
  26144. }
  26145. for (index = 0; index < other.normals.length; index++) {
  26146. this.normals.push(other.normals[index]);
  26147. }
  26148. }
  26149. if (other.uvs) {
  26150. if (!this.uvs) {
  26151. this.uvs = [];
  26152. }
  26153. for (index = 0; index < other.uvs.length; index++) {
  26154. this.uvs.push(other.uvs[index]);
  26155. }
  26156. }
  26157. if (other.uvs2) {
  26158. if (!this.uvs2) {
  26159. this.uvs2 = [];
  26160. }
  26161. for (index = 0; index < other.uvs2.length; index++) {
  26162. this.uvs2.push(other.uvs2[index]);
  26163. }
  26164. }
  26165. if (other.uvs3) {
  26166. if (!this.uvs3) {
  26167. this.uvs3 = [];
  26168. }
  26169. for (index = 0; index < other.uvs3.length; index++) {
  26170. this.uvs3.push(other.uvs3[index]);
  26171. }
  26172. }
  26173. if (other.uvs4) {
  26174. if (!this.uvs4) {
  26175. this.uvs4 = [];
  26176. }
  26177. for (index = 0; index < other.uvs4.length; index++) {
  26178. this.uvs4.push(other.uvs4[index]);
  26179. }
  26180. }
  26181. if (other.uvs5) {
  26182. if (!this.uvs5) {
  26183. this.uvs5 = [];
  26184. }
  26185. for (index = 0; index < other.uvs5.length; index++) {
  26186. this.uvs5.push(other.uvs5[index]);
  26187. }
  26188. }
  26189. if (other.uvs6) {
  26190. if (!this.uvs6) {
  26191. this.uvs6 = [];
  26192. }
  26193. for (index = 0; index < other.uvs6.length; index++) {
  26194. this.uvs6.push(other.uvs6[index]);
  26195. }
  26196. }
  26197. if (other.matricesIndices) {
  26198. if (!this.matricesIndices) {
  26199. this.matricesIndices = [];
  26200. }
  26201. for (index = 0; index < other.matricesIndices.length; index++) {
  26202. this.matricesIndices.push(other.matricesIndices[index]);
  26203. }
  26204. }
  26205. if (other.matricesWeights) {
  26206. if (!this.matricesWeights) {
  26207. this.matricesWeights = [];
  26208. }
  26209. for (index = 0; index < other.matricesWeights.length; index++) {
  26210. this.matricesWeights.push(other.matricesWeights[index]);
  26211. }
  26212. }
  26213. if (other.colors) {
  26214. if (!this.colors) {
  26215. this.colors = [];
  26216. }
  26217. for (index = 0; index < other.colors.length; index++) {
  26218. this.colors.push(other.colors[index]);
  26219. }
  26220. }
  26221. };
  26222. // Statics
  26223. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26224. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26225. };
  26226. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26227. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26228. };
  26229. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26230. var result = new VertexData();
  26231. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26232. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26233. }
  26234. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26235. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26236. }
  26237. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26238. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26239. }
  26240. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26241. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26242. }
  26243. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26244. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26245. }
  26246. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26247. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26248. }
  26249. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26250. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26251. }
  26252. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26253. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26254. }
  26255. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26256. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26257. }
  26258. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26259. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26260. }
  26261. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26262. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26263. }
  26264. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26265. return result;
  26266. };
  26267. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26268. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26269. closeArray = closeArray || false;
  26270. closePath = closePath || false;
  26271. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26272. offset = offset || defaultOffset;
  26273. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26274. var positions = [];
  26275. var indices = [];
  26276. var normals = [];
  26277. var uvs = [];
  26278. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26279. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26280. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26281. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26282. var minlg; // minimal length among all paths from pathArray
  26283. var lg = []; // array of path lengths : nb of vertex per path
  26284. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26285. var p; // path iterator
  26286. var i; // point iterator
  26287. var j; // point iterator
  26288. // if single path in pathArray
  26289. if (pathArray.length < 2) {
  26290. var ar1 = [];
  26291. var ar2 = [];
  26292. for (i = 0; i < pathArray[0].length - offset; i++) {
  26293. ar1.push(pathArray[0][i]);
  26294. ar2.push(pathArray[0][i + offset]);
  26295. }
  26296. pathArray = [ar1, ar2];
  26297. }
  26298. // positions and horizontal distances (u)
  26299. var idc = 0;
  26300. var closePathCorr = (closePath) ? 1 : 0;
  26301. var path;
  26302. var l;
  26303. minlg = pathArray[0].length;
  26304. var vectlg;
  26305. var dist;
  26306. for (p = 0; p < pathArray.length; p++) {
  26307. uTotalDistance[p] = 0;
  26308. us[p] = [0];
  26309. path = pathArray[p];
  26310. l = path.length;
  26311. minlg = (minlg < l) ? minlg : l;
  26312. j = 0;
  26313. while (j < l) {
  26314. positions.push(path[j].x, path[j].y, path[j].z);
  26315. if (j > 0) {
  26316. vectlg = path[j].subtract(path[j - 1]).length();
  26317. dist = vectlg + uTotalDistance[p];
  26318. us[p].push(dist);
  26319. uTotalDistance[p] = dist;
  26320. }
  26321. j++;
  26322. }
  26323. if (closePath) {
  26324. j--;
  26325. positions.push(path[0].x, path[0].y, path[0].z);
  26326. vectlg = path[j].subtract(path[0]).length();
  26327. dist = vectlg + uTotalDistance[p];
  26328. us[p].push(dist);
  26329. uTotalDistance[p] = dist;
  26330. }
  26331. lg[p] = l + closePathCorr;
  26332. idx[p] = idc;
  26333. idc += (l + closePathCorr);
  26334. }
  26335. // vertical distances (v)
  26336. var path1;
  26337. var path2;
  26338. var vertex1;
  26339. var vertex2;
  26340. for (i = 0; i < minlg + closePathCorr; i++) {
  26341. vTotalDistance[i] = 0;
  26342. vs[i] = [0];
  26343. for (p = 0; p < pathArray.length - 1; p++) {
  26344. path1 = pathArray[p];
  26345. path2 = pathArray[p + 1];
  26346. if (i === minlg) {
  26347. vertex1 = path1[0];
  26348. vertex2 = path2[0];
  26349. }
  26350. else {
  26351. vertex1 = path1[i];
  26352. vertex2 = path2[i];
  26353. }
  26354. vectlg = vertex2.subtract(vertex1).length();
  26355. dist = vectlg + vTotalDistance[i];
  26356. vs[i].push(dist);
  26357. vTotalDistance[i] = dist;
  26358. }
  26359. if (closeArray) {
  26360. path1 = pathArray[p];
  26361. path2 = pathArray[0];
  26362. vectlg = path2[i].subtract(path1[i]).length();
  26363. dist = vectlg + vTotalDistance[i];
  26364. vTotalDistance[i] = dist;
  26365. }
  26366. }
  26367. // uvs
  26368. var u;
  26369. var v;
  26370. for (p = 0; p < pathArray.length; p++) {
  26371. for (i = 0; i < minlg + closePathCorr; i++) {
  26372. u = us[p][i] / uTotalDistance[p];
  26373. v = vs[i][p] / vTotalDistance[i];
  26374. uvs.push(u, v);
  26375. }
  26376. }
  26377. // indices
  26378. p = 0; // path index
  26379. var pi = 0; // positions array index
  26380. var l1 = lg[p] - 1; // path1 length
  26381. var l2 = lg[p + 1] - 1; // path2 length
  26382. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26383. var shft = idx[1] - idx[0]; // shift
  26384. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26385. while (pi <= min && p < path1nb) {
  26386. // 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
  26387. indices.push(pi, pi + shft, pi + 1);
  26388. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26389. pi += 1;
  26390. if (pi === min) {
  26391. p++;
  26392. if (p === lg.length - 1) {
  26393. shft = idx[0] - idx[p];
  26394. l1 = lg[p] - 1;
  26395. l2 = lg[0] - 1;
  26396. }
  26397. else {
  26398. shft = idx[p + 1] - idx[p];
  26399. l1 = lg[p] - 1;
  26400. l2 = lg[p + 1] - 1;
  26401. }
  26402. pi = idx[p];
  26403. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26404. }
  26405. }
  26406. // normals
  26407. VertexData.ComputeNormals(positions, indices, normals);
  26408. if (closePath) {
  26409. var indexFirst = 0;
  26410. var indexLast = 0;
  26411. for (p = 0; p < pathArray.length; p++) {
  26412. indexFirst = idx[p] * 3;
  26413. if (p + 1 < pathArray.length) {
  26414. indexLast = (idx[p + 1] - 1) * 3;
  26415. }
  26416. else {
  26417. indexLast = normals.length - 3;
  26418. }
  26419. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26420. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26421. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26422. normals[indexLast] = normals[indexFirst];
  26423. normals[indexLast + 1] = normals[indexFirst + 1];
  26424. normals[indexLast + 2] = normals[indexFirst + 2];
  26425. }
  26426. }
  26427. // sides
  26428. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26429. // Result
  26430. var vertexData = new VertexData();
  26431. vertexData.indices = indices;
  26432. vertexData.positions = positions;
  26433. vertexData.normals = normals;
  26434. vertexData.uvs = uvs;
  26435. if (closePath) {
  26436. vertexData._idx = idx;
  26437. }
  26438. return vertexData;
  26439. };
  26440. VertexData.CreateBox = function (options, sideOrientation) {
  26441. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26442. var normalsSource = [
  26443. new BABYLON.Vector3(0, 0, 1),
  26444. new BABYLON.Vector3(0, 0, -1),
  26445. new BABYLON.Vector3(1, 0, 0),
  26446. new BABYLON.Vector3(-1, 0, 0),
  26447. new BABYLON.Vector3(0, 1, 0),
  26448. new BABYLON.Vector3(0, -1, 0)
  26449. ];
  26450. var indices = [];
  26451. var positions = [];
  26452. var normals = [];
  26453. var uvs = [];
  26454. var width = 1;
  26455. var height = 1;
  26456. var depth = 1;
  26457. var faceUV = options.faceUV || new Array(6);
  26458. var faceColors;
  26459. var colors = [];
  26460. if (options.faceColors) {
  26461. faceColors = options.faceColors;
  26462. }
  26463. if (options.width !== undefined) {
  26464. width = options.width || 1;
  26465. height = options.height || 1;
  26466. depth = options.depth || 1;
  26467. }
  26468. else {
  26469. width = options || 1;
  26470. height = options || 1;
  26471. depth = options || 1;
  26472. }
  26473. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26474. for (var f = 0; f < 6; f++) {
  26475. if (faceUV[f] === undefined) {
  26476. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26477. }
  26478. if (faceColors && faceColors[f] === undefined) {
  26479. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26480. }
  26481. }
  26482. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26483. // Create each face in turn.
  26484. for (var index = 0; index < normalsSource.length; index++) {
  26485. var normal = normalsSource[index];
  26486. // Get two vectors perpendicular to the face normal and to each other.
  26487. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26488. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26489. // Six indices (two triangles) per face.
  26490. var verticesLength = positions.length / 3;
  26491. indices.push(verticesLength);
  26492. indices.push(verticesLength + 1);
  26493. indices.push(verticesLength + 2);
  26494. indices.push(verticesLength);
  26495. indices.push(verticesLength + 2);
  26496. indices.push(verticesLength + 3);
  26497. // Four vertices per face.
  26498. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26499. positions.push(vertex.x, vertex.y, vertex.z);
  26500. normals.push(normal.x, normal.y, normal.z);
  26501. uvs.push(faceUV[index].z, faceUV[index].w);
  26502. if (faceColors) {
  26503. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26504. }
  26505. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26506. positions.push(vertex.x, vertex.y, vertex.z);
  26507. normals.push(normal.x, normal.y, normal.z);
  26508. uvs.push(faceUV[index].x, faceUV[index].w);
  26509. if (faceColors) {
  26510. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26511. }
  26512. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26513. positions.push(vertex.x, vertex.y, vertex.z);
  26514. normals.push(normal.x, normal.y, normal.z);
  26515. uvs.push(faceUV[index].x, faceUV[index].y);
  26516. if (faceColors) {
  26517. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26518. }
  26519. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26520. positions.push(vertex.x, vertex.y, vertex.z);
  26521. normals.push(normal.x, normal.y, normal.z);
  26522. uvs.push(faceUV[index].z, faceUV[index].y);
  26523. if (faceColors) {
  26524. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26525. }
  26526. }
  26527. // sides
  26528. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26529. // Result
  26530. var vertexData = new VertexData();
  26531. vertexData.indices = indices;
  26532. vertexData.positions = positions;
  26533. vertexData.normals = normals;
  26534. vertexData.uvs = uvs;
  26535. if (faceColors) {
  26536. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26537. vertexData.colors = totalColors;
  26538. }
  26539. return vertexData;
  26540. };
  26541. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26542. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26543. var segments;
  26544. var diameterX;
  26545. var diameterY;
  26546. var diameterZ;
  26547. if (options.segments) {
  26548. segments = options.segments || 32;
  26549. diameterX = options.diameterX || 1;
  26550. diameterY = options.diameterY || 1;
  26551. diameterZ = options.diameterZ || 1;
  26552. }
  26553. else {
  26554. segments = options || 32;
  26555. diameterX = diameter || 1;
  26556. diameterY = diameterX;
  26557. diameterZ = diameterX;
  26558. }
  26559. sideOrientation = sideOrientation || options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26560. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26561. var totalZRotationSteps = 2 + segments;
  26562. var totalYRotationSteps = 2 * totalZRotationSteps;
  26563. var indices = [];
  26564. var positions = [];
  26565. var normals = [];
  26566. var uvs = [];
  26567. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26568. var normalizedZ = zRotationStep / totalZRotationSteps;
  26569. var angleZ = (normalizedZ * Math.PI);
  26570. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26571. var normalizedY = yRotationStep / totalYRotationSteps;
  26572. var angleY = normalizedY * Math.PI * 2;
  26573. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26574. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26575. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26576. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26577. var vertex = complete.multiply(radius);
  26578. var normal = BABYLON.Vector3.Normalize(vertex);
  26579. positions.push(vertex.x, vertex.y, vertex.z);
  26580. normals.push(normal.x, normal.y, normal.z);
  26581. uvs.push(normalizedY, normalizedZ);
  26582. }
  26583. if (zRotationStep > 0) {
  26584. var verticesCount = positions.length / 3;
  26585. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26586. indices.push((firstIndex));
  26587. indices.push((firstIndex + 1));
  26588. indices.push(firstIndex + totalYRotationSteps + 1);
  26589. indices.push((firstIndex + totalYRotationSteps + 1));
  26590. indices.push((firstIndex + 1));
  26591. indices.push((firstIndex + totalYRotationSteps + 2));
  26592. }
  26593. }
  26594. }
  26595. // Sides
  26596. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26597. // Result
  26598. var vertexData = new VertexData();
  26599. vertexData.indices = indices;
  26600. vertexData.positions = positions;
  26601. vertexData.normals = normals;
  26602. vertexData.uvs = uvs;
  26603. return vertexData;
  26604. };
  26605. // Cylinder and cone (made using ribbons)
  26606. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26607. if (subdivisions === void 0) { subdivisions = 1; }
  26608. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26609. var indices = [];
  26610. var positions = [];
  26611. var normals = [];
  26612. var uvs = [];
  26613. var angle_step = Math.PI * 2 / tessellation;
  26614. var angle;
  26615. var h;
  26616. var radius;
  26617. var tan = (diameterBottom - diameterTop) / 2 / height;
  26618. var ringVertex = BABYLON.Vector3.Zero();
  26619. var ringNormal = BABYLON.Vector3.Zero();
  26620. // positions, normals, uvs
  26621. var i;
  26622. var j;
  26623. for (i = 0; i <= subdivisions; i++) {
  26624. h = i / subdivisions;
  26625. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26626. for (j = 0; j <= tessellation; j++) {
  26627. angle = j * angle_step;
  26628. ringVertex.x = Math.cos(-angle) * radius;
  26629. ringVertex.y = -height / 2 + h * height;
  26630. ringVertex.z = Math.sin(-angle) * radius;
  26631. if (diameterTop === 0 && i === subdivisions) {
  26632. // if no top cap, reuse former normals
  26633. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26634. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26635. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26636. }
  26637. else {
  26638. ringNormal.x = ringVertex.x;
  26639. ringNormal.z = ringVertex.z;
  26640. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26641. ringNormal.normalize();
  26642. }
  26643. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26644. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26645. uvs.push(j / tessellation, 1 - h);
  26646. }
  26647. }
  26648. // indices
  26649. for (i = 0; i < subdivisions; i++) {
  26650. for (j = 0; j < tessellation; j++) {
  26651. var i0 = i * (tessellation + 1) + j;
  26652. var i1 = (i + 1) * (tessellation + 1) + j;
  26653. var i2 = i * (tessellation + 1) + (j + 1);
  26654. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26655. indices.push(i0, i1, i2);
  26656. indices.push(i3, i2, i1);
  26657. }
  26658. }
  26659. // Caps
  26660. var createCylinderCap = function (isTop) {
  26661. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26662. if (radius === 0) {
  26663. return;
  26664. }
  26665. var vbase = positions.length / 3;
  26666. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26667. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26668. // Cap positions, normals & uvs
  26669. var angle;
  26670. var circleVector;
  26671. var i;
  26672. for (i = 0; i < tessellation; i++) {
  26673. angle = Math.PI * 2 * i / tessellation;
  26674. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26675. var position = circleVector.scale(radius).add(offset);
  26676. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26677. positions.push(position.x, position.y, position.z);
  26678. normals.push(0, isTop ? 1 : -1, 0);
  26679. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26680. }
  26681. // Cap indices
  26682. for (i = 0; i < tessellation - 2; i++) {
  26683. if (!isTop) {
  26684. indices.push(vbase);
  26685. indices.push(vbase + (i + 1) % tessellation);
  26686. indices.push(vbase + (i + 2) % tessellation);
  26687. }
  26688. else {
  26689. indices.push(vbase);
  26690. indices.push(vbase + (i + 2) % tessellation);
  26691. indices.push(vbase + (i + 1) % tessellation);
  26692. }
  26693. }
  26694. };
  26695. // add caps to geometry
  26696. createCylinderCap(true);
  26697. createCylinderCap(false);
  26698. // Sides
  26699. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26700. var vertexData = new VertexData();
  26701. vertexData.indices = indices;
  26702. vertexData.positions = positions;
  26703. vertexData.normals = normals;
  26704. vertexData.uvs = uvs;
  26705. return vertexData;
  26706. };
  26707. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26708. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26709. var indices = [];
  26710. var positions = [];
  26711. var normals = [];
  26712. var uvs = [];
  26713. diameter = diameter || 1;
  26714. thickness = thickness || 0.5;
  26715. tessellation = tessellation || 16;
  26716. var stride = tessellation + 1;
  26717. for (var i = 0; i <= tessellation; i++) {
  26718. var u = i / tessellation;
  26719. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26720. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26721. for (var j = 0; j <= tessellation; j++) {
  26722. var v = 1 - j / tessellation;
  26723. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26724. var dx = Math.cos(innerAngle);
  26725. var dy = Math.sin(innerAngle);
  26726. // Create a vertex.
  26727. var normal = new BABYLON.Vector3(dx, dy, 0);
  26728. var position = normal.scale(thickness / 2);
  26729. var textureCoordinate = new BABYLON.Vector2(u, v);
  26730. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26731. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26732. positions.push(position.x, position.y, position.z);
  26733. normals.push(normal.x, normal.y, normal.z);
  26734. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26735. // And create indices for two triangles.
  26736. var nextI = (i + 1) % stride;
  26737. var nextJ = (j + 1) % stride;
  26738. indices.push(i * stride + j);
  26739. indices.push(i * stride + nextJ);
  26740. indices.push(nextI * stride + j);
  26741. indices.push(i * stride + nextJ);
  26742. indices.push(nextI * stride + nextJ);
  26743. indices.push(nextI * stride + j);
  26744. }
  26745. }
  26746. // Sides
  26747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26748. // Result
  26749. var vertexData = new VertexData();
  26750. vertexData.indices = indices;
  26751. vertexData.positions = positions;
  26752. vertexData.normals = normals;
  26753. vertexData.uvs = uvs;
  26754. return vertexData;
  26755. };
  26756. VertexData.CreateLines = function (points) {
  26757. var indices = [];
  26758. var positions = [];
  26759. for (var index = 0; index < points.length; index++) {
  26760. positions.push(points[index].x, points[index].y, points[index].z);
  26761. if (index > 0) {
  26762. indices.push(index - 1);
  26763. indices.push(index);
  26764. }
  26765. }
  26766. // Result
  26767. var vertexData = new VertexData();
  26768. vertexData.indices = indices;
  26769. vertexData.positions = positions;
  26770. return vertexData;
  26771. };
  26772. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26773. dashSize = dashSize || 3;
  26774. gapSize = gapSize || 1;
  26775. dashNb = dashNb || 200;
  26776. var positions = new Array();
  26777. var indices = new Array();
  26778. var curvect = BABYLON.Vector3.Zero();
  26779. var lg = 0;
  26780. var nb = 0;
  26781. var shft = 0;
  26782. var dashshft = 0;
  26783. var curshft = 0;
  26784. var idx = 0;
  26785. var i = 0;
  26786. for (i = 0; i < points.length - 1; i++) {
  26787. points[i + 1].subtractToRef(points[i], curvect);
  26788. lg += curvect.length();
  26789. }
  26790. shft = lg / dashNb;
  26791. dashshft = dashSize * shft / (dashSize + gapSize);
  26792. for (i = 0; i < points.length - 1; i++) {
  26793. points[i + 1].subtractToRef(points[i], curvect);
  26794. nb = Math.floor(curvect.length() / shft);
  26795. curvect.normalize();
  26796. for (var j = 0; j < nb; j++) {
  26797. curshft = shft * j;
  26798. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26799. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26800. indices.push(idx, idx + 1);
  26801. idx += 2;
  26802. }
  26803. }
  26804. // Result
  26805. var vertexData = new VertexData();
  26806. vertexData.positions = positions;
  26807. vertexData.indices = indices;
  26808. return vertexData;
  26809. };
  26810. VertexData.CreateGround = function (options, height, subdivisions) {
  26811. var indices = [];
  26812. var positions = [];
  26813. var normals = [];
  26814. var uvs = [];
  26815. var row, col;
  26816. var width;
  26817. if (options.width) {
  26818. width = options.width || 1;
  26819. height = options.height || 1;
  26820. subdivisions = options.subdivisions || 1;
  26821. }
  26822. else {
  26823. width = options || 1;
  26824. height = height || 1;
  26825. subdivisions = subdivisions || 1;
  26826. }
  26827. for (row = 0; row <= subdivisions; row++) {
  26828. for (col = 0; col <= subdivisions; col++) {
  26829. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26830. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26831. positions.push(position.x, position.y, position.z);
  26832. normals.push(normal.x, normal.y, normal.z);
  26833. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26834. }
  26835. }
  26836. for (row = 0; row < subdivisions; row++) {
  26837. for (col = 0; col < subdivisions; col++) {
  26838. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26839. indices.push(col + 1 + row * (subdivisions + 1));
  26840. indices.push(col + row * (subdivisions + 1));
  26841. indices.push(col + (row + 1) * (subdivisions + 1));
  26842. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26843. indices.push(col + row * (subdivisions + 1));
  26844. }
  26845. }
  26846. // Result
  26847. var vertexData = new VertexData();
  26848. vertexData.indices = indices;
  26849. vertexData.positions = positions;
  26850. vertexData.normals = normals;
  26851. vertexData.uvs = uvs;
  26852. return vertexData;
  26853. };
  26854. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26855. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26856. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26857. var indices = [];
  26858. var positions = [];
  26859. var normals = [];
  26860. var uvs = [];
  26861. var row, col, tileRow, tileCol;
  26862. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26863. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26864. precision.w = (precision.w < 1) ? 1 : precision.w;
  26865. precision.h = (precision.h < 1) ? 1 : precision.h;
  26866. var tileSize = {
  26867. 'w': (xmax - xmin) / subdivisions.w,
  26868. 'h': (zmax - zmin) / subdivisions.h
  26869. };
  26870. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26871. // Indices
  26872. var base = positions.length / 3;
  26873. var rowLength = precision.w + 1;
  26874. for (row = 0; row < precision.h; row++) {
  26875. for (col = 0; col < precision.w; col++) {
  26876. var square = [
  26877. base + col + row * rowLength,
  26878. base + (col + 1) + row * rowLength,
  26879. base + (col + 1) + (row + 1) * rowLength,
  26880. base + col + (row + 1) * rowLength
  26881. ];
  26882. indices.push(square[1]);
  26883. indices.push(square[2]);
  26884. indices.push(square[3]);
  26885. indices.push(square[0]);
  26886. indices.push(square[1]);
  26887. indices.push(square[3]);
  26888. }
  26889. }
  26890. // Position, normals and uvs
  26891. var position = BABYLON.Vector3.Zero();
  26892. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26893. for (row = 0; row <= precision.h; row++) {
  26894. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26895. for (col = 0; col <= precision.w; col++) {
  26896. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26897. position.y = 0;
  26898. positions.push(position.x, position.y, position.z);
  26899. normals.push(normal.x, normal.y, normal.z);
  26900. uvs.push(col / precision.w, row / precision.h);
  26901. }
  26902. }
  26903. }
  26904. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26905. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26906. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26907. }
  26908. }
  26909. // Result
  26910. var vertexData = new VertexData();
  26911. vertexData.indices = indices;
  26912. vertexData.positions = positions;
  26913. vertexData.normals = normals;
  26914. vertexData.uvs = uvs;
  26915. return vertexData;
  26916. };
  26917. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26918. var indices = [];
  26919. var positions = [];
  26920. var normals = [];
  26921. var uvs = [];
  26922. var row, col;
  26923. // Vertices
  26924. for (row = 0; row <= subdivisions; row++) {
  26925. for (col = 0; col <= subdivisions; col++) {
  26926. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26927. // Compute height
  26928. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26929. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26930. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26931. var r = buffer[pos] / 255.0;
  26932. var g = buffer[pos + 1] / 255.0;
  26933. var b = buffer[pos + 2] / 255.0;
  26934. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26935. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26936. // Add vertex
  26937. positions.push(position.x, position.y, position.z);
  26938. normals.push(0, 0, 0);
  26939. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26940. }
  26941. }
  26942. // Indices
  26943. for (row = 0; row < subdivisions; row++) {
  26944. for (col = 0; col < subdivisions; col++) {
  26945. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26946. indices.push(col + 1 + row * (subdivisions + 1));
  26947. indices.push(col + row * (subdivisions + 1));
  26948. indices.push(col + (row + 1) * (subdivisions + 1));
  26949. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26950. indices.push(col + row * (subdivisions + 1));
  26951. }
  26952. }
  26953. // Normals
  26954. VertexData.ComputeNormals(positions, indices, normals);
  26955. // Result
  26956. var vertexData = new VertexData();
  26957. vertexData.indices = indices;
  26958. vertexData.positions = positions;
  26959. vertexData.normals = normals;
  26960. vertexData.uvs = uvs;
  26961. return vertexData;
  26962. };
  26963. VertexData.CreatePlane = function (options, sideOrientation) {
  26964. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26965. var indices = [];
  26966. var positions = [];
  26967. var normals = [];
  26968. var uvs = [];
  26969. var width;
  26970. var height;
  26971. if (options.width) {
  26972. width = options.width || 1;
  26973. height = options.height || 1;
  26974. sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26975. }
  26976. else {
  26977. width = options || 1;
  26978. height = options || 1;
  26979. }
  26980. // Vertices
  26981. var halfWidth = width / 2.0;
  26982. var halfHeight = height / 2.0;
  26983. positions.push(-halfWidth, -halfHeight, 0);
  26984. normals.push(0, 0, -1.0);
  26985. uvs.push(0.0, 0.0);
  26986. positions.push(halfWidth, -halfHeight, 0);
  26987. normals.push(0, 0, -1.0);
  26988. uvs.push(1.0, 0.0);
  26989. positions.push(halfWidth, halfHeight, 0);
  26990. normals.push(0, 0, -1.0);
  26991. uvs.push(1.0, 1.0);
  26992. positions.push(-halfWidth, halfHeight, 0);
  26993. normals.push(0, 0, -1.0);
  26994. uvs.push(0.0, 1.0);
  26995. // Indices
  26996. indices.push(0);
  26997. indices.push(1);
  26998. indices.push(2);
  26999. indices.push(0);
  27000. indices.push(2);
  27001. indices.push(3);
  27002. // Sides
  27003. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27004. // Result
  27005. var vertexData = new VertexData();
  27006. vertexData.indices = indices;
  27007. vertexData.positions = positions;
  27008. vertexData.normals = normals;
  27009. vertexData.uvs = uvs;
  27010. return vertexData;
  27011. };
  27012. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  27013. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  27014. var positions = [];
  27015. var indices = [];
  27016. var normals = [];
  27017. var uvs = [];
  27018. // positions and uvs
  27019. positions.push(0, 0, 0); // disc center first
  27020. uvs.push(0.5, 0.5);
  27021. var step = Math.PI * 2 / tessellation;
  27022. for (var a = 0; a < Math.PI * 2; a += step) {
  27023. var x = Math.cos(a);
  27024. var y = Math.sin(a);
  27025. var u = (x + 1) / 2;
  27026. var v = (1 - y) / 2;
  27027. positions.push(radius * x, radius * y, 0);
  27028. uvs.push(u, v);
  27029. }
  27030. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27031. uvs.push(uvs[2], uvs[3]);
  27032. //indices
  27033. var vertexNb = positions.length / 3;
  27034. for (var i = 1; i < vertexNb - 1; i++) {
  27035. indices.push(i + 1, 0, i);
  27036. }
  27037. // result
  27038. VertexData.ComputeNormals(positions, indices, normals);
  27039. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27040. var vertexData = new VertexData();
  27041. vertexData.indices = indices;
  27042. vertexData.positions = positions;
  27043. vertexData.normals = normals;
  27044. vertexData.uvs = uvs;
  27045. return vertexData;
  27046. };
  27047. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27048. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  27049. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  27050. var indices = [];
  27051. var positions = [];
  27052. var normals = [];
  27053. var uvs = [];
  27054. radius = radius || 2;
  27055. tube = tube || 0.5;
  27056. radialSegments = radialSegments || 32;
  27057. tubularSegments = tubularSegments || 32;
  27058. p = p || 2;
  27059. q = q || 3;
  27060. // Helper
  27061. var getPos = function (angle) {
  27062. var cu = Math.cos(angle);
  27063. var su = Math.sin(angle);
  27064. var quOverP = q / p * angle;
  27065. var cs = Math.cos(quOverP);
  27066. var tx = radius * (2 + cs) * 0.5 * cu;
  27067. var ty = radius * (2 + cs) * su * 0.5;
  27068. var tz = radius * Math.sin(quOverP) * 0.5;
  27069. return new BABYLON.Vector3(tx, ty, tz);
  27070. };
  27071. // Vertices
  27072. var i;
  27073. var j;
  27074. for (i = 0; i <= radialSegments; i++) {
  27075. var modI = i % radialSegments;
  27076. var u = modI / radialSegments * 2 * p * Math.PI;
  27077. var p1 = getPos(u);
  27078. var p2 = getPos(u + 0.01);
  27079. var tang = p2.subtract(p1);
  27080. var n = p2.add(p1);
  27081. var bitan = BABYLON.Vector3.Cross(tang, n);
  27082. n = BABYLON.Vector3.Cross(bitan, tang);
  27083. bitan.normalize();
  27084. n.normalize();
  27085. for (j = 0; j < tubularSegments; j++) {
  27086. var modJ = j % tubularSegments;
  27087. var v = modJ / tubularSegments * 2 * Math.PI;
  27088. var cx = -tube * Math.cos(v);
  27089. var cy = tube * Math.sin(v);
  27090. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27091. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27092. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27093. uvs.push(i / radialSegments);
  27094. uvs.push(j / tubularSegments);
  27095. }
  27096. }
  27097. for (i = 0; i < radialSegments; i++) {
  27098. for (j = 0; j < tubularSegments; j++) {
  27099. var jNext = (j + 1) % tubularSegments;
  27100. var a = i * tubularSegments + j;
  27101. var b = (i + 1) * tubularSegments + j;
  27102. var c = (i + 1) * tubularSegments + jNext;
  27103. var d = i * tubularSegments + jNext;
  27104. indices.push(d);
  27105. indices.push(b);
  27106. indices.push(a);
  27107. indices.push(d);
  27108. indices.push(c);
  27109. indices.push(b);
  27110. }
  27111. }
  27112. // Normals
  27113. VertexData.ComputeNormals(positions, indices, normals);
  27114. // Sides
  27115. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27116. // Result
  27117. var vertexData = new VertexData();
  27118. vertexData.indices = indices;
  27119. vertexData.positions = positions;
  27120. vertexData.normals = normals;
  27121. vertexData.uvs = uvs;
  27122. return vertexData;
  27123. };
  27124. // Tools
  27125. /**
  27126. * @param {any} - positions (number[] or Float32Array)
  27127. * @param {any} - indices (number[] or Uint16Array)
  27128. * @param {any} - normals (number[] or Float32Array)
  27129. */
  27130. VertexData.ComputeNormals = function (positions, indices, normals) {
  27131. var index = 0;
  27132. // temp Vector3
  27133. var p1p2 = BABYLON.Vector3.Zero();
  27134. var p3p2 = BABYLON.Vector3.Zero();
  27135. var faceNormal = BABYLON.Vector3.Zero();
  27136. var vertexNormali1 = BABYLON.Vector3.Zero();
  27137. for (index = 0; index < positions.length; index++) {
  27138. normals[index] = 0.0;
  27139. }
  27140. // indice triplet = 1 face
  27141. var nbFaces = indices.length / 3;
  27142. for (index = 0; index < nbFaces; index++) {
  27143. var i1 = indices[index * 3];
  27144. var i2 = indices[index * 3 + 1];
  27145. var i3 = indices[index * 3 + 2];
  27146. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27147. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27148. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27149. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27150. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27151. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27152. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27153. faceNormal.normalize();
  27154. normals[i1 * 3] += faceNormal.x;
  27155. normals[i1 * 3 + 1] += faceNormal.y;
  27156. normals[i1 * 3 + 2] += faceNormal.z;
  27157. normals[i2 * 3] += faceNormal.x;
  27158. normals[i2 * 3 + 1] += faceNormal.y;
  27159. normals[i2 * 3 + 2] += faceNormal.z;
  27160. normals[i3 * 3] += faceNormal.x;
  27161. normals[i3 * 3 + 1] += faceNormal.y;
  27162. normals[i3 * 3 + 2] += faceNormal.z;
  27163. }
  27164. // last normalization
  27165. for (index = 0; index < normals.length / 3; index++) {
  27166. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27167. vertexNormali1.normalize();
  27168. normals[index * 3] = vertexNormali1.x;
  27169. normals[index * 3 + 1] = vertexNormali1.y;
  27170. normals[index * 3 + 2] = vertexNormali1.z;
  27171. }
  27172. };
  27173. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27174. var li = indices.length;
  27175. var ln = normals.length;
  27176. var i;
  27177. var n;
  27178. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27179. switch (sideOrientation) {
  27180. case BABYLON.Mesh.FRONTSIDE:
  27181. // nothing changed
  27182. break;
  27183. case BABYLON.Mesh.BACKSIDE:
  27184. var tmp;
  27185. // indices
  27186. for (i = 0; i < li; i += 3) {
  27187. tmp = indices[i];
  27188. indices[i] = indices[i + 2];
  27189. indices[i + 2] = tmp;
  27190. }
  27191. // normals
  27192. for (n = 0; n < ln; n++) {
  27193. normals[n] = -normals[n];
  27194. }
  27195. break;
  27196. case BABYLON.Mesh.DOUBLESIDE:
  27197. // positions
  27198. var lp = positions.length;
  27199. var l = lp / 3;
  27200. for (var p = 0; p < lp; p++) {
  27201. positions[lp + p] = positions[p];
  27202. }
  27203. // indices
  27204. for (i = 0; i < li; i += 3) {
  27205. indices[i + li] = indices[i + 2] + l;
  27206. indices[i + 1 + li] = indices[i + 1] + l;
  27207. indices[i + 2 + li] = indices[i] + l;
  27208. }
  27209. // normals
  27210. for (n = 0; n < ln; n++) {
  27211. normals[ln + n] = -normals[n];
  27212. }
  27213. // uvs
  27214. var lu = uvs.length;
  27215. for (var u = 0; u < lu; u++) {
  27216. uvs[u + lu] = uvs[u];
  27217. }
  27218. break;
  27219. }
  27220. };
  27221. return VertexData;
  27222. })();
  27223. BABYLON.VertexData = VertexData;
  27224. })(BABYLON || (BABYLON = {}));
  27225. var BABYLON;
  27226. (function (BABYLON) {
  27227. var AnaglyphPostProcess = (function (_super) {
  27228. __extends(AnaglyphPostProcess, _super);
  27229. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27230. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27231. }
  27232. return AnaglyphPostProcess;
  27233. })(BABYLON.PostProcess);
  27234. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27235. })(BABYLON || (BABYLON = {}));
  27236. var BABYLON;
  27237. (function (BABYLON) {
  27238. var Tags = (function () {
  27239. function Tags() {
  27240. }
  27241. Tags.EnableFor = function (obj) {
  27242. obj._tags = obj._tags || {};
  27243. obj.hasTags = function () {
  27244. return Tags.HasTags(obj);
  27245. };
  27246. obj.addTags = function (tagsString) {
  27247. return Tags.AddTagsTo(obj, tagsString);
  27248. };
  27249. obj.removeTags = function (tagsString) {
  27250. return Tags.RemoveTagsFrom(obj, tagsString);
  27251. };
  27252. obj.matchesTagsQuery = function (tagsQuery) {
  27253. return Tags.MatchesQuery(obj, tagsQuery);
  27254. };
  27255. };
  27256. Tags.DisableFor = function (obj) {
  27257. delete obj._tags;
  27258. delete obj.hasTags;
  27259. delete obj.addTags;
  27260. delete obj.removeTags;
  27261. delete obj.matchesTagsQuery;
  27262. };
  27263. Tags.HasTags = function (obj) {
  27264. if (!obj._tags) {
  27265. return false;
  27266. }
  27267. return !BABYLON.Tools.IsEmpty(obj._tags);
  27268. };
  27269. Tags.GetTags = function (obj) {
  27270. if (!obj._tags) {
  27271. return null;
  27272. }
  27273. return obj._tags;
  27274. };
  27275. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27276. // a tag cannot start with '||', '&&', and '!'
  27277. // it cannot contain whitespaces
  27278. Tags.AddTagsTo = function (obj, tagsString) {
  27279. if (!tagsString) {
  27280. return;
  27281. }
  27282. var tags = tagsString.split(" ");
  27283. for (var t in tags) {
  27284. Tags._AddTagTo(obj, tags[t]);
  27285. }
  27286. };
  27287. Tags._AddTagTo = function (obj, tag) {
  27288. tag = tag.trim();
  27289. if (tag === "" || tag === "true" || tag === "false") {
  27290. return;
  27291. }
  27292. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27293. return;
  27294. }
  27295. Tags.EnableFor(obj);
  27296. obj._tags[tag] = true;
  27297. };
  27298. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27299. if (!Tags.HasTags(obj)) {
  27300. return;
  27301. }
  27302. var tags = tagsString.split(" ");
  27303. for (var t in tags) {
  27304. Tags._RemoveTagFrom(obj, tags[t]);
  27305. }
  27306. };
  27307. Tags._RemoveTagFrom = function (obj, tag) {
  27308. delete obj._tags[tag];
  27309. };
  27310. Tags.MatchesQuery = function (obj, tagsQuery) {
  27311. if (tagsQuery === undefined) {
  27312. return true;
  27313. }
  27314. if (tagsQuery === "") {
  27315. return Tags.HasTags(obj);
  27316. }
  27317. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27318. };
  27319. return Tags;
  27320. })();
  27321. BABYLON.Tags = Tags;
  27322. })(BABYLON || (BABYLON = {}));
  27323. var BABYLON;
  27324. (function (BABYLON) {
  27325. var Internals;
  27326. (function (Internals) {
  27327. var AndOrNotEvaluator = (function () {
  27328. function AndOrNotEvaluator() {
  27329. }
  27330. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27331. if (!query.match(/\([^\(\)]*\)/g)) {
  27332. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27333. }
  27334. else {
  27335. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27336. // remove parenthesis
  27337. r = r.slice(1, r.length - 1);
  27338. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27339. });
  27340. }
  27341. if (query === "true") {
  27342. return true;
  27343. }
  27344. if (query === "false") {
  27345. return false;
  27346. }
  27347. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27348. };
  27349. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27350. evaluateCallback = evaluateCallback || (function (r) {
  27351. return r === "true" ? true : false;
  27352. });
  27353. var result;
  27354. var or = parenthesisContent.split("||");
  27355. for (var i in or) {
  27356. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27357. var and = ori.split("&&");
  27358. if (and.length > 1) {
  27359. for (var j = 0; j < and.length; ++j) {
  27360. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27361. if (andj !== "true" && andj !== "false") {
  27362. if (andj[0] === "!") {
  27363. result = !evaluateCallback(andj.substring(1));
  27364. }
  27365. else {
  27366. result = evaluateCallback(andj);
  27367. }
  27368. }
  27369. else {
  27370. result = andj === "true" ? true : false;
  27371. }
  27372. if (!result) {
  27373. ori = "false";
  27374. break;
  27375. }
  27376. }
  27377. }
  27378. if (result || ori === "true") {
  27379. result = true;
  27380. break;
  27381. }
  27382. // result equals false (or undefined)
  27383. if (ori !== "true" && ori !== "false") {
  27384. if (ori[0] === "!") {
  27385. result = !evaluateCallback(ori.substring(1));
  27386. }
  27387. else {
  27388. result = evaluateCallback(ori);
  27389. }
  27390. }
  27391. else {
  27392. result = ori === "true" ? true : false;
  27393. }
  27394. }
  27395. // the whole parenthesis scope is replaced by 'true' or 'false'
  27396. return result ? "true" : "false";
  27397. };
  27398. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27399. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27400. // remove whitespaces
  27401. r = r.replace(/[\s]/g, function () { return ""; });
  27402. return r.length % 2 ? "!" : "";
  27403. });
  27404. booleanString = booleanString.trim();
  27405. if (booleanString === "!true") {
  27406. booleanString = "false";
  27407. }
  27408. else if (booleanString === "!false") {
  27409. booleanString = "true";
  27410. }
  27411. return booleanString;
  27412. };
  27413. return AndOrNotEvaluator;
  27414. })();
  27415. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27416. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27417. })(BABYLON || (BABYLON = {}));
  27418. var BABYLON;
  27419. (function (BABYLON) {
  27420. var PostProcessRenderPass = (function () {
  27421. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27422. this._enabled = true;
  27423. this._refCount = 0;
  27424. this._name = name;
  27425. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27426. this.setRenderList(renderList);
  27427. this._renderTexture.onBeforeRender = beforeRender;
  27428. this._renderTexture.onAfterRender = afterRender;
  27429. this._scene = scene;
  27430. this._renderList = renderList;
  27431. }
  27432. // private
  27433. PostProcessRenderPass.prototype._incRefCount = function () {
  27434. if (this._refCount === 0) {
  27435. this._scene.customRenderTargets.push(this._renderTexture);
  27436. }
  27437. return ++this._refCount;
  27438. };
  27439. PostProcessRenderPass.prototype._decRefCount = function () {
  27440. this._refCount--;
  27441. if (this._refCount <= 0) {
  27442. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27443. }
  27444. return this._refCount;
  27445. };
  27446. PostProcessRenderPass.prototype._update = function () {
  27447. this.setRenderList(this._renderList);
  27448. };
  27449. // public
  27450. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27451. this._renderTexture.renderList = renderList;
  27452. };
  27453. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27454. return this._renderTexture;
  27455. };
  27456. return PostProcessRenderPass;
  27457. })();
  27458. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27459. })(BABYLON || (BABYLON = {}));
  27460. var BABYLON;
  27461. (function (BABYLON) {
  27462. var PostProcessRenderEffect = (function () {
  27463. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27464. this._engine = engine;
  27465. this._name = name;
  27466. this._singleInstance = singleInstance || true;
  27467. this._getPostProcess = getPostProcess;
  27468. this._cameras = [];
  27469. this._indicesForCamera = [];
  27470. this._postProcesses = {};
  27471. this._renderPasses = {};
  27472. this._renderEffectAsPasses = {};
  27473. }
  27474. PostProcessRenderEffect.prototype._update = function () {
  27475. for (var renderPassName in this._renderPasses) {
  27476. this._renderPasses[renderPassName]._update();
  27477. }
  27478. };
  27479. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27480. this._renderPasses[renderPass._name] = renderPass;
  27481. this._linkParameters();
  27482. };
  27483. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27484. delete this._renderPasses[renderPass._name];
  27485. this._linkParameters();
  27486. };
  27487. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27488. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27489. this._linkParameters();
  27490. };
  27491. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27492. for (var renderPassName in this._renderPasses) {
  27493. if (renderPassName === passName) {
  27494. return this._renderPasses[passName];
  27495. }
  27496. }
  27497. };
  27498. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27499. this._renderPasses = {};
  27500. this._linkParameters();
  27501. };
  27502. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27503. var cameraKey;
  27504. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27505. for (var i = 0; i < _cam.length; i++) {
  27506. var camera = _cam[i];
  27507. var cameraName = camera.name;
  27508. if (this._singleInstance) {
  27509. cameraKey = 0;
  27510. }
  27511. else {
  27512. cameraKey = cameraName;
  27513. }
  27514. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27515. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27516. if (!this._indicesForCamera[cameraName]) {
  27517. this._indicesForCamera[cameraName] = [];
  27518. }
  27519. this._indicesForCamera[cameraName].push(index);
  27520. if (this._cameras.indexOf(camera) === -1) {
  27521. this._cameras[cameraName] = camera;
  27522. }
  27523. for (var passName in this._renderPasses) {
  27524. this._renderPasses[passName]._incRefCount();
  27525. }
  27526. }
  27527. this._linkParameters();
  27528. };
  27529. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27530. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27531. for (var i = 0; i < _cam.length; i++) {
  27532. var camera = _cam[i];
  27533. var cameraName = camera.name;
  27534. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27535. var index = this._cameras.indexOf(cameraName);
  27536. this._indicesForCamera.splice(index, 1);
  27537. this._cameras.splice(index, 1);
  27538. for (var passName in this._renderPasses) {
  27539. this._renderPasses[passName]._decRefCount();
  27540. }
  27541. }
  27542. };
  27543. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27544. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27545. for (var i = 0; i < _cam.length; i++) {
  27546. var camera = _cam[i];
  27547. var cameraName = camera.name;
  27548. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27549. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27550. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27551. }
  27552. }
  27553. for (var passName in this._renderPasses) {
  27554. this._renderPasses[passName]._incRefCount();
  27555. }
  27556. }
  27557. };
  27558. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27559. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27560. for (var i = 0; i < _cam.length; i++) {
  27561. var camera = _cam[i];
  27562. var cameraName = camera.Name;
  27563. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27564. for (var passName in this._renderPasses) {
  27565. this._renderPasses[passName]._decRefCount();
  27566. }
  27567. }
  27568. };
  27569. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27570. if (this._singleInstance) {
  27571. return this._postProcesses[0];
  27572. }
  27573. else {
  27574. return this._postProcesses[camera.name];
  27575. }
  27576. };
  27577. PostProcessRenderEffect.prototype._linkParameters = function () {
  27578. var _this = this;
  27579. for (var index in this._postProcesses) {
  27580. if (this.applyParameters) {
  27581. this.applyParameters(this._postProcesses[index]);
  27582. }
  27583. this._postProcesses[index].onBeforeRender = function (effect) {
  27584. _this._linkTextures(effect);
  27585. };
  27586. }
  27587. };
  27588. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27589. for (var renderPassName in this._renderPasses) {
  27590. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27591. }
  27592. for (var renderEffectName in this._renderEffectAsPasses) {
  27593. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27594. }
  27595. };
  27596. return PostProcessRenderEffect;
  27597. })();
  27598. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27599. })(BABYLON || (BABYLON = {}));
  27600. var BABYLON;
  27601. (function (BABYLON) {
  27602. var PostProcessRenderPipeline = (function () {
  27603. function PostProcessRenderPipeline(engine, name) {
  27604. this._engine = engine;
  27605. this._name = name;
  27606. this._renderEffects = {};
  27607. this._renderEffectsForIsolatedPass = {};
  27608. this._cameras = [];
  27609. }
  27610. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27611. this._renderEffects[renderEffect._name] = renderEffect;
  27612. };
  27613. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27614. var renderEffects = this._renderEffects[renderEffectName];
  27615. if (!renderEffects) {
  27616. return;
  27617. }
  27618. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27619. };
  27620. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27621. var renderEffects = this._renderEffects[renderEffectName];
  27622. if (!renderEffects) {
  27623. return;
  27624. }
  27625. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27626. };
  27627. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27628. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27629. var indicesToDelete = [];
  27630. for (var i = 0; i < _cam.length; i++) {
  27631. var camera = _cam[i];
  27632. var cameraName = camera.name;
  27633. if (this._cameras.indexOf(camera) === -1) {
  27634. this._cameras[cameraName] = camera;
  27635. }
  27636. else if (unique) {
  27637. indicesToDelete.push(i);
  27638. }
  27639. }
  27640. for (var i = 0; i < indicesToDelete.length; i++) {
  27641. cameras.splice(indicesToDelete[i], 1);
  27642. }
  27643. for (var renderEffectName in this._renderEffects) {
  27644. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27645. }
  27646. };
  27647. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27648. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27649. for (var renderEffectName in this._renderEffects) {
  27650. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27651. }
  27652. for (var i = 0; i < _cam.length; i++) {
  27653. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27654. }
  27655. };
  27656. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27657. var _this = this;
  27658. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27659. var pass = null;
  27660. for (var renderEffectName in this._renderEffects) {
  27661. pass = this._renderEffects[renderEffectName].getPass(passName);
  27662. if (pass != null) {
  27663. break;
  27664. }
  27665. }
  27666. if (pass === null) {
  27667. return;
  27668. }
  27669. for (var renderEffectName in this._renderEffects) {
  27670. this._renderEffects[renderEffectName]._disable(_cam);
  27671. }
  27672. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27673. for (var i = 0; i < _cam.length; i++) {
  27674. var camera = _cam[i];
  27675. var cameraName = camera.name;
  27676. 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); });
  27677. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27678. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27679. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27680. }
  27681. };
  27682. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27683. var _this = this;
  27684. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27685. for (var i = 0; i < _cam.length; i++) {
  27686. var camera = _cam[i];
  27687. var cameraName = camera.name;
  27688. 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); });
  27689. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27690. }
  27691. for (var renderEffectName in this._renderEffects) {
  27692. this._renderEffects[renderEffectName]._enable(_cam);
  27693. }
  27694. };
  27695. PostProcessRenderPipeline.prototype._update = function () {
  27696. for (var renderEffectName in this._renderEffects) {
  27697. this._renderEffects[renderEffectName]._update();
  27698. }
  27699. for (var i = 0; i < this._cameras.length; i++) {
  27700. var cameraName = this._cameras[i].name;
  27701. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27702. this._renderEffectsForIsolatedPass[cameraName]._update();
  27703. }
  27704. }
  27705. };
  27706. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27707. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27708. return PostProcessRenderPipeline;
  27709. })();
  27710. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27711. })(BABYLON || (BABYLON = {}));
  27712. var BABYLON;
  27713. (function (BABYLON) {
  27714. var PostProcessRenderPipelineManager = (function () {
  27715. function PostProcessRenderPipelineManager() {
  27716. this._renderPipelines = {};
  27717. }
  27718. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27719. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27720. };
  27721. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27722. var renderPipeline = this._renderPipelines[renderPipelineName];
  27723. if (!renderPipeline) {
  27724. return;
  27725. }
  27726. renderPipeline._attachCameras(cameras, unique);
  27727. };
  27728. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27729. var renderPipeline = this._renderPipelines[renderPipelineName];
  27730. if (!renderPipeline) {
  27731. return;
  27732. }
  27733. renderPipeline._detachCameras(cameras);
  27734. };
  27735. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27736. var renderPipeline = this._renderPipelines[renderPipelineName];
  27737. if (!renderPipeline) {
  27738. return;
  27739. }
  27740. renderPipeline._enableEffect(renderEffectName, cameras);
  27741. };
  27742. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27743. var renderPipeline = this._renderPipelines[renderPipelineName];
  27744. if (!renderPipeline) {
  27745. return;
  27746. }
  27747. renderPipeline._disableEffect(renderEffectName, cameras);
  27748. };
  27749. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27750. var renderPipeline = this._renderPipelines[renderPipelineName];
  27751. if (!renderPipeline) {
  27752. return;
  27753. }
  27754. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27755. };
  27756. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27757. var renderPipeline = this._renderPipelines[renderPipelineName];
  27758. if (!renderPipeline) {
  27759. return;
  27760. }
  27761. renderPipeline._disableDisplayOnlyPass(cameras);
  27762. };
  27763. PostProcessRenderPipelineManager.prototype.update = function () {
  27764. for (var renderPipelineName in this._renderPipelines) {
  27765. this._renderPipelines[renderPipelineName]._update();
  27766. }
  27767. };
  27768. return PostProcessRenderPipelineManager;
  27769. })();
  27770. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27771. })(BABYLON || (BABYLON = {}));
  27772. var BABYLON;
  27773. (function (BABYLON) {
  27774. var DisplayPassPostProcess = (function (_super) {
  27775. __extends(DisplayPassPostProcess, _super);
  27776. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27777. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27778. }
  27779. return DisplayPassPostProcess;
  27780. })(BABYLON.PostProcess);
  27781. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27782. })(BABYLON || (BABYLON = {}));
  27783. var BABYLON;
  27784. (function (BABYLON) {
  27785. var BoundingBoxRenderer = (function () {
  27786. function BoundingBoxRenderer(scene) {
  27787. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27788. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27789. this.showBackLines = true;
  27790. this.renderList = new BABYLON.SmartArray(32);
  27791. this._scene = scene;
  27792. }
  27793. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27794. if (this._colorShader) {
  27795. return;
  27796. }
  27797. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27798. attributes: ["position"],
  27799. uniforms: ["worldViewProjection", "color"]
  27800. });
  27801. var engine = this._scene.getEngine();
  27802. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27803. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27804. 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]);
  27805. };
  27806. BoundingBoxRenderer.prototype.reset = function () {
  27807. this.renderList.reset();
  27808. };
  27809. BoundingBoxRenderer.prototype.render = function () {
  27810. if (this.renderList.length === 0) {
  27811. return;
  27812. }
  27813. this._prepareRessources();
  27814. if (!this._colorShader.isReady()) {
  27815. return;
  27816. }
  27817. var engine = this._scene.getEngine();
  27818. engine.setDepthWrite(false);
  27819. this._colorShader._preBind();
  27820. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27821. var boundingBox = this.renderList.data[boundingBoxIndex];
  27822. var min = boundingBox.minimum;
  27823. var max = boundingBox.maximum;
  27824. var diff = max.subtract(min);
  27825. var median = min.add(diff.scale(0.5));
  27826. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27827. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27828. .multiply(boundingBox.getWorldMatrix());
  27829. // VBOs
  27830. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27831. if (this.showBackLines) {
  27832. // Back
  27833. engine.setDepthFunctionToGreaterOrEqual();
  27834. this._scene.resetCachedMaterial();
  27835. this._colorShader.setColor4("color", this.backColor.toColor4());
  27836. this._colorShader.bind(worldMatrix);
  27837. // Draw order
  27838. engine.draw(false, 0, 24);
  27839. }
  27840. // Front
  27841. engine.setDepthFunctionToLess();
  27842. this._scene.resetCachedMaterial();
  27843. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27844. this._colorShader.bind(worldMatrix);
  27845. // Draw order
  27846. engine.draw(false, 0, 24);
  27847. }
  27848. this._colorShader.unbind();
  27849. engine.setDepthFunctionToLessOrEqual();
  27850. engine.setDepthWrite(true);
  27851. };
  27852. BoundingBoxRenderer.prototype.dispose = function () {
  27853. if (!this._colorShader) {
  27854. return;
  27855. }
  27856. this._colorShader.dispose();
  27857. this._vb.dispose();
  27858. this._scene.getEngine()._releaseBuffer(this._ib);
  27859. };
  27860. return BoundingBoxRenderer;
  27861. })();
  27862. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27863. })(BABYLON || (BABYLON = {}));
  27864. var BABYLON;
  27865. (function (BABYLON) {
  27866. var Condition = (function () {
  27867. function Condition(actionManager) {
  27868. this._actionManager = actionManager;
  27869. }
  27870. Condition.prototype.isValid = function () {
  27871. return true;
  27872. };
  27873. Condition.prototype._getProperty = function (propertyPath) {
  27874. return this._actionManager._getProperty(propertyPath);
  27875. };
  27876. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27877. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27878. };
  27879. return Condition;
  27880. })();
  27881. BABYLON.Condition = Condition;
  27882. var ValueCondition = (function (_super) {
  27883. __extends(ValueCondition, _super);
  27884. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27885. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27886. _super.call(this, actionManager);
  27887. this.propertyPath = propertyPath;
  27888. this.value = value;
  27889. this.operator = operator;
  27890. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27891. this._property = this._getProperty(this.propertyPath);
  27892. }
  27893. Object.defineProperty(ValueCondition, "IsEqual", {
  27894. get: function () {
  27895. return ValueCondition._IsEqual;
  27896. },
  27897. enumerable: true,
  27898. configurable: true
  27899. });
  27900. Object.defineProperty(ValueCondition, "IsDifferent", {
  27901. get: function () {
  27902. return ValueCondition._IsDifferent;
  27903. },
  27904. enumerable: true,
  27905. configurable: true
  27906. });
  27907. Object.defineProperty(ValueCondition, "IsGreater", {
  27908. get: function () {
  27909. return ValueCondition._IsGreater;
  27910. },
  27911. enumerable: true,
  27912. configurable: true
  27913. });
  27914. Object.defineProperty(ValueCondition, "IsLesser", {
  27915. get: function () {
  27916. return ValueCondition._IsLesser;
  27917. },
  27918. enumerable: true,
  27919. configurable: true
  27920. });
  27921. // Methods
  27922. ValueCondition.prototype.isValid = function () {
  27923. switch (this.operator) {
  27924. case ValueCondition.IsGreater:
  27925. return this._target[this._property] > this.value;
  27926. case ValueCondition.IsLesser:
  27927. return this._target[this._property] < this.value;
  27928. case ValueCondition.IsEqual:
  27929. case ValueCondition.IsDifferent:
  27930. var check;
  27931. if (this.value.equals) {
  27932. check = this.value.equals(this._target[this._property]);
  27933. }
  27934. else {
  27935. check = this.value === this._target[this._property];
  27936. }
  27937. return this.operator === ValueCondition.IsEqual ? check : !check;
  27938. }
  27939. return false;
  27940. };
  27941. // Statics
  27942. ValueCondition._IsEqual = 0;
  27943. ValueCondition._IsDifferent = 1;
  27944. ValueCondition._IsGreater = 2;
  27945. ValueCondition._IsLesser = 3;
  27946. return ValueCondition;
  27947. })(Condition);
  27948. BABYLON.ValueCondition = ValueCondition;
  27949. var PredicateCondition = (function (_super) {
  27950. __extends(PredicateCondition, _super);
  27951. function PredicateCondition(actionManager, predicate) {
  27952. _super.call(this, actionManager);
  27953. this.predicate = predicate;
  27954. }
  27955. PredicateCondition.prototype.isValid = function () {
  27956. return this.predicate();
  27957. };
  27958. return PredicateCondition;
  27959. })(Condition);
  27960. BABYLON.PredicateCondition = PredicateCondition;
  27961. var StateCondition = (function (_super) {
  27962. __extends(StateCondition, _super);
  27963. function StateCondition(actionManager, target, value) {
  27964. _super.call(this, actionManager);
  27965. this.value = value;
  27966. this._target = target;
  27967. }
  27968. // Methods
  27969. StateCondition.prototype.isValid = function () {
  27970. return this._target.state === this.value;
  27971. };
  27972. return StateCondition;
  27973. })(Condition);
  27974. BABYLON.StateCondition = StateCondition;
  27975. })(BABYLON || (BABYLON = {}));
  27976. var BABYLON;
  27977. (function (BABYLON) {
  27978. var Action = (function () {
  27979. function Action(triggerOptions, condition) {
  27980. this.triggerOptions = triggerOptions;
  27981. if (triggerOptions.parameter) {
  27982. this.trigger = triggerOptions.trigger;
  27983. this._triggerParameter = triggerOptions.parameter;
  27984. }
  27985. else {
  27986. this.trigger = triggerOptions;
  27987. }
  27988. this._nextActiveAction = this;
  27989. this._condition = condition;
  27990. }
  27991. // Methods
  27992. Action.prototype._prepare = function () {
  27993. };
  27994. Action.prototype.getTriggerParameter = function () {
  27995. return this._triggerParameter;
  27996. };
  27997. Action.prototype._executeCurrent = function (evt) {
  27998. if (this._nextActiveAction._condition) {
  27999. var condition = this._nextActiveAction._condition;
  28000. var currentRenderId = this._actionManager.getScene().getRenderId();
  28001. // We cache the current evaluation for the current frame
  28002. if (condition._evaluationId === currentRenderId) {
  28003. if (!condition._currentResult) {
  28004. return;
  28005. }
  28006. }
  28007. else {
  28008. condition._evaluationId = currentRenderId;
  28009. if (!condition.isValid()) {
  28010. condition._currentResult = false;
  28011. return;
  28012. }
  28013. condition._currentResult = true;
  28014. }
  28015. }
  28016. this._nextActiveAction.execute(evt);
  28017. if (this._nextActiveAction._child) {
  28018. if (!this._nextActiveAction._child._actionManager) {
  28019. this._nextActiveAction._child._actionManager = this._actionManager;
  28020. }
  28021. this._nextActiveAction = this._nextActiveAction._child;
  28022. }
  28023. else {
  28024. this._nextActiveAction = this;
  28025. }
  28026. };
  28027. Action.prototype.execute = function (evt) {
  28028. };
  28029. Action.prototype.then = function (action) {
  28030. this._child = action;
  28031. action._actionManager = this._actionManager;
  28032. action._prepare();
  28033. return action;
  28034. };
  28035. Action.prototype._getProperty = function (propertyPath) {
  28036. return this._actionManager._getProperty(propertyPath);
  28037. };
  28038. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28039. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28040. };
  28041. return Action;
  28042. })();
  28043. BABYLON.Action = Action;
  28044. })(BABYLON || (BABYLON = {}));
  28045. var BABYLON;
  28046. (function (BABYLON) {
  28047. /**
  28048. * ActionEvent is the event beint sent when an action is triggered.
  28049. */
  28050. var ActionEvent = (function () {
  28051. /**
  28052. * @constructor
  28053. * @param source The mesh that triggered the action.
  28054. * @param pointerX the X mouse cursor position at the time of the event
  28055. * @param pointerY the Y mouse cursor position at the time of the event
  28056. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28057. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28058. */
  28059. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28060. this.source = source;
  28061. this.pointerX = pointerX;
  28062. this.pointerY = pointerY;
  28063. this.meshUnderPointer = meshUnderPointer;
  28064. this.sourceEvent = sourceEvent;
  28065. this.additionalData = additionalData;
  28066. }
  28067. /**
  28068. * Helper function to auto-create an ActionEvent from a source mesh.
  28069. * @param source the source mesh that triggered the event
  28070. * @param evt {Event} The original (browser) event
  28071. */
  28072. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28073. var scene = source.getScene();
  28074. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28075. };
  28076. /**
  28077. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28078. * @param scene the scene where the event occurred
  28079. * @param evt {Event} The original (browser) event
  28080. */
  28081. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28082. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28083. };
  28084. return ActionEvent;
  28085. })();
  28086. BABYLON.ActionEvent = ActionEvent;
  28087. /**
  28088. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28089. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28090. */
  28091. var ActionManager = (function () {
  28092. function ActionManager(scene) {
  28093. // Members
  28094. this.actions = new Array();
  28095. this._scene = scene;
  28096. scene._actionManagers.push(this);
  28097. }
  28098. Object.defineProperty(ActionManager, "NothingTrigger", {
  28099. get: function () {
  28100. return ActionManager._NothingTrigger;
  28101. },
  28102. enumerable: true,
  28103. configurable: true
  28104. });
  28105. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28106. get: function () {
  28107. return ActionManager._OnPickTrigger;
  28108. },
  28109. enumerable: true,
  28110. configurable: true
  28111. });
  28112. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28113. get: function () {
  28114. return ActionManager._OnLeftPickTrigger;
  28115. },
  28116. enumerable: true,
  28117. configurable: true
  28118. });
  28119. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28120. get: function () {
  28121. return ActionManager._OnRightPickTrigger;
  28122. },
  28123. enumerable: true,
  28124. configurable: true
  28125. });
  28126. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28127. get: function () {
  28128. return ActionManager._OnCenterPickTrigger;
  28129. },
  28130. enumerable: true,
  28131. configurable: true
  28132. });
  28133. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28134. get: function () {
  28135. return ActionManager._OnPointerOverTrigger;
  28136. },
  28137. enumerable: true,
  28138. configurable: true
  28139. });
  28140. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28141. get: function () {
  28142. return ActionManager._OnPointerOutTrigger;
  28143. },
  28144. enumerable: true,
  28145. configurable: true
  28146. });
  28147. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28148. get: function () {
  28149. return ActionManager._OnEveryFrameTrigger;
  28150. },
  28151. enumerable: true,
  28152. configurable: true
  28153. });
  28154. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28155. get: function () {
  28156. return ActionManager._OnIntersectionEnterTrigger;
  28157. },
  28158. enumerable: true,
  28159. configurable: true
  28160. });
  28161. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28162. get: function () {
  28163. return ActionManager._OnIntersectionExitTrigger;
  28164. },
  28165. enumerable: true,
  28166. configurable: true
  28167. });
  28168. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28169. get: function () {
  28170. return ActionManager._OnKeyDownTrigger;
  28171. },
  28172. enumerable: true,
  28173. configurable: true
  28174. });
  28175. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28176. get: function () {
  28177. return ActionManager._OnKeyUpTrigger;
  28178. },
  28179. enumerable: true,
  28180. configurable: true
  28181. });
  28182. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28183. get: function () {
  28184. return ActionManager._OnPickUpTrigger;
  28185. },
  28186. enumerable: true,
  28187. configurable: true
  28188. });
  28189. // Methods
  28190. ActionManager.prototype.dispose = function () {
  28191. var index = this._scene._actionManagers.indexOf(this);
  28192. if (index > -1) {
  28193. this._scene._actionManagers.splice(index, 1);
  28194. }
  28195. };
  28196. ActionManager.prototype.getScene = function () {
  28197. return this._scene;
  28198. };
  28199. /**
  28200. * Does this action manager handles actions of any of the given triggers
  28201. * @param {number[]} triggers - the triggers to be tested
  28202. * @return {boolean} whether one (or more) of the triggers is handeled
  28203. */
  28204. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28205. for (var index = 0; index < this.actions.length; index++) {
  28206. var action = this.actions[index];
  28207. if (triggers.indexOf(action.trigger) > -1) {
  28208. return true;
  28209. }
  28210. }
  28211. return false;
  28212. };
  28213. /**
  28214. * Does this action manager handles actions of a given trigger
  28215. * @param {number} trigger - the trigger to be tested
  28216. * @return {boolean} whether the trigger is handeled
  28217. */
  28218. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28219. for (var index = 0; index < this.actions.length; index++) {
  28220. var action = this.actions[index];
  28221. if (action.trigger === trigger) {
  28222. return true;
  28223. }
  28224. }
  28225. return false;
  28226. };
  28227. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28228. /**
  28229. * Does this action manager has pointer triggers
  28230. * @return {boolean} whether or not it has pointer triggers
  28231. */
  28232. get: function () {
  28233. for (var index = 0; index < this.actions.length; index++) {
  28234. var action = this.actions[index];
  28235. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28236. return true;
  28237. }
  28238. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28239. return true;
  28240. }
  28241. }
  28242. return false;
  28243. },
  28244. enumerable: true,
  28245. configurable: true
  28246. });
  28247. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28248. /**
  28249. * Does this action manager has pick triggers
  28250. * @return {boolean} whether or not it has pick triggers
  28251. */
  28252. get: function () {
  28253. for (var index = 0; index < this.actions.length; index++) {
  28254. var action = this.actions[index];
  28255. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28256. return true;
  28257. }
  28258. }
  28259. return false;
  28260. },
  28261. enumerable: true,
  28262. configurable: true
  28263. });
  28264. /**
  28265. * Registers an action to this action manager
  28266. * @param {BABYLON.Action} action - the action to be registered
  28267. * @return {BABYLON.Action} the action amended (prepared) after registration
  28268. */
  28269. ActionManager.prototype.registerAction = function (action) {
  28270. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28271. if (this.getScene().actionManager !== this) {
  28272. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28273. return null;
  28274. }
  28275. }
  28276. this.actions.push(action);
  28277. action._actionManager = this;
  28278. action._prepare();
  28279. return action;
  28280. };
  28281. /**
  28282. * Process a specific trigger
  28283. * @param {number} trigger - the trigger to process
  28284. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28285. */
  28286. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28287. for (var index = 0; index < this.actions.length; index++) {
  28288. var action = this.actions[index];
  28289. if (action.trigger === trigger) {
  28290. if (trigger === ActionManager.OnKeyUpTrigger
  28291. || trigger === ActionManager.OnKeyDownTrigger) {
  28292. var parameter = action.getTriggerParameter();
  28293. if (parameter) {
  28294. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28295. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28296. if (actualkey !== parameter.toLowerCase()) {
  28297. continue;
  28298. }
  28299. }
  28300. }
  28301. action._executeCurrent(evt);
  28302. }
  28303. }
  28304. };
  28305. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28306. var properties = propertyPath.split(".");
  28307. for (var index = 0; index < properties.length - 1; index++) {
  28308. target = target[properties[index]];
  28309. }
  28310. return target;
  28311. };
  28312. ActionManager.prototype._getProperty = function (propertyPath) {
  28313. var properties = propertyPath.split(".");
  28314. return properties[properties.length - 1];
  28315. };
  28316. // Statics
  28317. ActionManager._NothingTrigger = 0;
  28318. ActionManager._OnPickTrigger = 1;
  28319. ActionManager._OnLeftPickTrigger = 2;
  28320. ActionManager._OnRightPickTrigger = 3;
  28321. ActionManager._OnCenterPickTrigger = 4;
  28322. ActionManager._OnPointerOverTrigger = 5;
  28323. ActionManager._OnPointerOutTrigger = 6;
  28324. ActionManager._OnEveryFrameTrigger = 7;
  28325. ActionManager._OnIntersectionEnterTrigger = 8;
  28326. ActionManager._OnIntersectionExitTrigger = 9;
  28327. ActionManager._OnKeyDownTrigger = 10;
  28328. ActionManager._OnKeyUpTrigger = 11;
  28329. ActionManager._OnPickUpTrigger = 12;
  28330. return ActionManager;
  28331. })();
  28332. BABYLON.ActionManager = ActionManager;
  28333. })(BABYLON || (BABYLON = {}));
  28334. var BABYLON;
  28335. (function (BABYLON) {
  28336. var InterpolateValueAction = (function (_super) {
  28337. __extends(InterpolateValueAction, _super);
  28338. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28339. if (duration === void 0) { duration = 1000; }
  28340. _super.call(this, triggerOptions, condition);
  28341. this.propertyPath = propertyPath;
  28342. this.value = value;
  28343. this.duration = duration;
  28344. this.stopOtherAnimations = stopOtherAnimations;
  28345. this._target = target;
  28346. }
  28347. InterpolateValueAction.prototype._prepare = function () {
  28348. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28349. this._property = this._getProperty(this.propertyPath);
  28350. };
  28351. InterpolateValueAction.prototype.execute = function () {
  28352. var scene = this._actionManager.getScene();
  28353. var keys = [
  28354. {
  28355. frame: 0,
  28356. value: this._target[this._property]
  28357. }, {
  28358. frame: 100,
  28359. value: this.value
  28360. }
  28361. ];
  28362. var dataType;
  28363. if (typeof this.value === "number") {
  28364. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28365. }
  28366. else if (this.value instanceof BABYLON.Color3) {
  28367. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28368. }
  28369. else if (this.value instanceof BABYLON.Vector3) {
  28370. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28371. }
  28372. else if (this.value instanceof BABYLON.Matrix) {
  28373. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28374. }
  28375. else if (this.value instanceof BABYLON.Quaternion) {
  28376. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28377. }
  28378. else {
  28379. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28380. return;
  28381. }
  28382. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28383. animation.setKeys(keys);
  28384. if (this.stopOtherAnimations) {
  28385. scene.stopAnimation(this._target);
  28386. }
  28387. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28388. };
  28389. return InterpolateValueAction;
  28390. })(BABYLON.Action);
  28391. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28392. })(BABYLON || (BABYLON = {}));
  28393. var BABYLON;
  28394. (function (BABYLON) {
  28395. var SwitchBooleanAction = (function (_super) {
  28396. __extends(SwitchBooleanAction, _super);
  28397. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28398. _super.call(this, triggerOptions, condition);
  28399. this.propertyPath = propertyPath;
  28400. this._target = target;
  28401. }
  28402. SwitchBooleanAction.prototype._prepare = function () {
  28403. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28404. this._property = this._getProperty(this.propertyPath);
  28405. };
  28406. SwitchBooleanAction.prototype.execute = function () {
  28407. this._target[this._property] = !this._target[this._property];
  28408. };
  28409. return SwitchBooleanAction;
  28410. })(BABYLON.Action);
  28411. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28412. var SetStateAction = (function (_super) {
  28413. __extends(SetStateAction, _super);
  28414. function SetStateAction(triggerOptions, target, value, condition) {
  28415. _super.call(this, triggerOptions, condition);
  28416. this.value = value;
  28417. this._target = target;
  28418. }
  28419. SetStateAction.prototype.execute = function () {
  28420. this._target.state = this.value;
  28421. };
  28422. return SetStateAction;
  28423. })(BABYLON.Action);
  28424. BABYLON.SetStateAction = SetStateAction;
  28425. var SetValueAction = (function (_super) {
  28426. __extends(SetValueAction, _super);
  28427. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28428. _super.call(this, triggerOptions, condition);
  28429. this.propertyPath = propertyPath;
  28430. this.value = value;
  28431. this._target = target;
  28432. }
  28433. SetValueAction.prototype._prepare = function () {
  28434. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28435. this._property = this._getProperty(this.propertyPath);
  28436. };
  28437. SetValueAction.prototype.execute = function () {
  28438. this._target[this._property] = this.value;
  28439. };
  28440. return SetValueAction;
  28441. })(BABYLON.Action);
  28442. BABYLON.SetValueAction = SetValueAction;
  28443. var IncrementValueAction = (function (_super) {
  28444. __extends(IncrementValueAction, _super);
  28445. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28446. _super.call(this, triggerOptions, condition);
  28447. this.propertyPath = propertyPath;
  28448. this.value = value;
  28449. this._target = target;
  28450. }
  28451. IncrementValueAction.prototype._prepare = function () {
  28452. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28453. this._property = this._getProperty(this.propertyPath);
  28454. if (typeof this._target[this._property] !== "number") {
  28455. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28456. }
  28457. };
  28458. IncrementValueAction.prototype.execute = function () {
  28459. this._target[this._property] += this.value;
  28460. };
  28461. return IncrementValueAction;
  28462. })(BABYLON.Action);
  28463. BABYLON.IncrementValueAction = IncrementValueAction;
  28464. var PlayAnimationAction = (function (_super) {
  28465. __extends(PlayAnimationAction, _super);
  28466. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28467. _super.call(this, triggerOptions, condition);
  28468. this.from = from;
  28469. this.to = to;
  28470. this.loop = loop;
  28471. this._target = target;
  28472. }
  28473. PlayAnimationAction.prototype._prepare = function () {
  28474. };
  28475. PlayAnimationAction.prototype.execute = function () {
  28476. var scene = this._actionManager.getScene();
  28477. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28478. };
  28479. return PlayAnimationAction;
  28480. })(BABYLON.Action);
  28481. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28482. var StopAnimationAction = (function (_super) {
  28483. __extends(StopAnimationAction, _super);
  28484. function StopAnimationAction(triggerOptions, target, condition) {
  28485. _super.call(this, triggerOptions, condition);
  28486. this._target = target;
  28487. }
  28488. StopAnimationAction.prototype._prepare = function () {
  28489. };
  28490. StopAnimationAction.prototype.execute = function () {
  28491. var scene = this._actionManager.getScene();
  28492. scene.stopAnimation(this._target);
  28493. };
  28494. return StopAnimationAction;
  28495. })(BABYLON.Action);
  28496. BABYLON.StopAnimationAction = StopAnimationAction;
  28497. var DoNothingAction = (function (_super) {
  28498. __extends(DoNothingAction, _super);
  28499. function DoNothingAction(triggerOptions, condition) {
  28500. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28501. _super.call(this, triggerOptions, condition);
  28502. }
  28503. DoNothingAction.prototype.execute = function () {
  28504. };
  28505. return DoNothingAction;
  28506. })(BABYLON.Action);
  28507. BABYLON.DoNothingAction = DoNothingAction;
  28508. var CombineAction = (function (_super) {
  28509. __extends(CombineAction, _super);
  28510. function CombineAction(triggerOptions, children, condition) {
  28511. _super.call(this, triggerOptions, condition);
  28512. this.children = children;
  28513. }
  28514. CombineAction.prototype._prepare = function () {
  28515. for (var index = 0; index < this.children.length; index++) {
  28516. this.children[index]._actionManager = this._actionManager;
  28517. this.children[index]._prepare();
  28518. }
  28519. };
  28520. CombineAction.prototype.execute = function (evt) {
  28521. for (var index = 0; index < this.children.length; index++) {
  28522. this.children[index].execute(evt);
  28523. }
  28524. };
  28525. return CombineAction;
  28526. })(BABYLON.Action);
  28527. BABYLON.CombineAction = CombineAction;
  28528. var ExecuteCodeAction = (function (_super) {
  28529. __extends(ExecuteCodeAction, _super);
  28530. function ExecuteCodeAction(triggerOptions, func, condition) {
  28531. _super.call(this, triggerOptions, condition);
  28532. this.func = func;
  28533. }
  28534. ExecuteCodeAction.prototype.execute = function (evt) {
  28535. this.func(evt);
  28536. };
  28537. return ExecuteCodeAction;
  28538. })(BABYLON.Action);
  28539. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28540. var SetParentAction = (function (_super) {
  28541. __extends(SetParentAction, _super);
  28542. function SetParentAction(triggerOptions, target, parent, condition) {
  28543. _super.call(this, triggerOptions, condition);
  28544. this._target = target;
  28545. this._parent = parent;
  28546. }
  28547. SetParentAction.prototype._prepare = function () {
  28548. };
  28549. SetParentAction.prototype.execute = function () {
  28550. if (this._target.parent === this._parent) {
  28551. return;
  28552. }
  28553. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28554. invertParentWorldMatrix.invert();
  28555. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28556. this._target.parent = this._parent;
  28557. };
  28558. return SetParentAction;
  28559. })(BABYLON.Action);
  28560. BABYLON.SetParentAction = SetParentAction;
  28561. var PlaySoundAction = (function (_super) {
  28562. __extends(PlaySoundAction, _super);
  28563. function PlaySoundAction(triggerOptions, sound, condition) {
  28564. _super.call(this, triggerOptions, condition);
  28565. this._sound = sound;
  28566. }
  28567. PlaySoundAction.prototype._prepare = function () {
  28568. };
  28569. PlaySoundAction.prototype.execute = function () {
  28570. if (this._sound !== undefined)
  28571. this._sound.play();
  28572. };
  28573. return PlaySoundAction;
  28574. })(BABYLON.Action);
  28575. BABYLON.PlaySoundAction = PlaySoundAction;
  28576. var StopSoundAction = (function (_super) {
  28577. __extends(StopSoundAction, _super);
  28578. function StopSoundAction(triggerOptions, sound, condition) {
  28579. _super.call(this, triggerOptions, condition);
  28580. this._sound = sound;
  28581. }
  28582. StopSoundAction.prototype._prepare = function () {
  28583. };
  28584. StopSoundAction.prototype.execute = function () {
  28585. if (this._sound !== undefined)
  28586. this._sound.stop();
  28587. };
  28588. return StopSoundAction;
  28589. })(BABYLON.Action);
  28590. BABYLON.StopSoundAction = StopSoundAction;
  28591. })(BABYLON || (BABYLON = {}));
  28592. var BABYLON;
  28593. (function (BABYLON) {
  28594. var Geometry = (function () {
  28595. function Geometry(id, scene, vertexData, updatable, mesh) {
  28596. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28597. this._totalVertices = 0;
  28598. this._indices = [];
  28599. this._isDisposed = false;
  28600. this.id = id;
  28601. this._engine = scene.getEngine();
  28602. this._meshes = [];
  28603. this._scene = scene;
  28604. // vertexData
  28605. if (vertexData) {
  28606. this.setAllVerticesData(vertexData, updatable);
  28607. }
  28608. else {
  28609. this._totalVertices = 0;
  28610. this._indices = [];
  28611. }
  28612. // applyToMesh
  28613. if (mesh) {
  28614. this.applyToMesh(mesh);
  28615. mesh.computeWorldMatrix(true);
  28616. }
  28617. }
  28618. Geometry.prototype.getScene = function () {
  28619. return this._scene;
  28620. };
  28621. Geometry.prototype.getEngine = function () {
  28622. return this._engine;
  28623. };
  28624. Geometry.prototype.isReady = function () {
  28625. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28626. };
  28627. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28628. vertexData.applyToGeometry(this, updatable);
  28629. this.notifyUpdate();
  28630. };
  28631. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28632. this._vertexBuffers = this._vertexBuffers || {};
  28633. if (this._vertexBuffers[kind]) {
  28634. this._vertexBuffers[kind].dispose();
  28635. }
  28636. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28637. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28638. stride = this._vertexBuffers[kind].getStrideSize();
  28639. this._totalVertices = data.length / stride;
  28640. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28641. var meshes = this._meshes;
  28642. var numOfMeshes = meshes.length;
  28643. for (var index = 0; index < numOfMeshes; index++) {
  28644. var mesh = meshes[index];
  28645. mesh._resetPointsArrayCache();
  28646. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28647. mesh._createGlobalSubMesh();
  28648. mesh.computeWorldMatrix(true);
  28649. }
  28650. }
  28651. this.notifyUpdate(kind);
  28652. };
  28653. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28654. var vertexBuffer = this.getVertexBuffer(kind);
  28655. if (!vertexBuffer) {
  28656. return;
  28657. }
  28658. vertexBuffer.updateDirectly(data, offset);
  28659. this.notifyUpdate(kind);
  28660. };
  28661. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28662. var vertexBuffer = this.getVertexBuffer(kind);
  28663. if (!vertexBuffer) {
  28664. return;
  28665. }
  28666. vertexBuffer.update(data);
  28667. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28668. var extend;
  28669. var stride = vertexBuffer.getStrideSize();
  28670. this._totalVertices = data.length / stride;
  28671. if (updateExtends) {
  28672. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28673. }
  28674. var meshes = this._meshes;
  28675. var numOfMeshes = meshes.length;
  28676. for (var index = 0; index < numOfMeshes; index++) {
  28677. var mesh = meshes[index];
  28678. mesh._resetPointsArrayCache();
  28679. if (updateExtends) {
  28680. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28681. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28682. var subMesh = mesh.subMeshes[subIndex];
  28683. subMesh.refreshBoundingInfo();
  28684. }
  28685. }
  28686. }
  28687. }
  28688. this.notifyUpdate(kind);
  28689. };
  28690. Geometry.prototype.getTotalVertices = function () {
  28691. if (!this.isReady()) {
  28692. return 0;
  28693. }
  28694. return this._totalVertices;
  28695. };
  28696. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28697. var vertexBuffer = this.getVertexBuffer(kind);
  28698. if (!vertexBuffer) {
  28699. return null;
  28700. }
  28701. var orig = vertexBuffer.getData();
  28702. if (!copyWhenShared || this._meshes.length === 1) {
  28703. return orig;
  28704. }
  28705. else {
  28706. var len = orig.length;
  28707. var copy = [];
  28708. for (var i = 0; i < len; i++) {
  28709. copy.push(orig[i]);
  28710. }
  28711. return copy;
  28712. }
  28713. };
  28714. Geometry.prototype.getVertexBuffer = function (kind) {
  28715. if (!this.isReady()) {
  28716. return null;
  28717. }
  28718. return this._vertexBuffers[kind];
  28719. };
  28720. Geometry.prototype.getVertexBuffers = function () {
  28721. if (!this.isReady()) {
  28722. return null;
  28723. }
  28724. return this._vertexBuffers;
  28725. };
  28726. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28727. if (!this._vertexBuffers) {
  28728. if (this._delayInfo) {
  28729. return this._delayInfo.indexOf(kind) !== -1;
  28730. }
  28731. return false;
  28732. }
  28733. return this._vertexBuffers[kind] !== undefined;
  28734. };
  28735. Geometry.prototype.getVerticesDataKinds = function () {
  28736. var result = [];
  28737. if (!this._vertexBuffers && this._delayInfo) {
  28738. for (var kind in this._delayInfo) {
  28739. result.push(kind);
  28740. }
  28741. }
  28742. else {
  28743. for (kind in this._vertexBuffers) {
  28744. result.push(kind);
  28745. }
  28746. }
  28747. return result;
  28748. };
  28749. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28750. if (this._indexBuffer) {
  28751. this._engine._releaseBuffer(this._indexBuffer);
  28752. }
  28753. this._indices = indices;
  28754. if (this._meshes.length !== 0 && this._indices) {
  28755. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28756. }
  28757. if (totalVertices !== undefined) {
  28758. this._totalVertices = totalVertices;
  28759. }
  28760. var meshes = this._meshes;
  28761. var numOfMeshes = meshes.length;
  28762. for (var index = 0; index < numOfMeshes; index++) {
  28763. meshes[index]._createGlobalSubMesh();
  28764. }
  28765. this.notifyUpdate();
  28766. };
  28767. Geometry.prototype.getTotalIndices = function () {
  28768. if (!this.isReady()) {
  28769. return 0;
  28770. }
  28771. return this._indices.length;
  28772. };
  28773. Geometry.prototype.getIndices = function (copyWhenShared) {
  28774. if (!this.isReady()) {
  28775. return null;
  28776. }
  28777. var orig = this._indices;
  28778. if (!copyWhenShared || this._meshes.length === 1) {
  28779. return orig;
  28780. }
  28781. else {
  28782. var len = orig.length;
  28783. var copy = [];
  28784. for (var i = 0; i < len; i++) {
  28785. copy.push(orig[i]);
  28786. }
  28787. return copy;
  28788. }
  28789. };
  28790. Geometry.prototype.getIndexBuffer = function () {
  28791. if (!this.isReady()) {
  28792. return null;
  28793. }
  28794. return this._indexBuffer;
  28795. };
  28796. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28797. var meshes = this._meshes;
  28798. var index = meshes.indexOf(mesh);
  28799. if (index === -1) {
  28800. return;
  28801. }
  28802. for (var kind in this._vertexBuffers) {
  28803. this._vertexBuffers[kind].dispose();
  28804. }
  28805. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28806. this._indexBuffer = null;
  28807. }
  28808. meshes.splice(index, 1);
  28809. mesh._geometry = null;
  28810. if (meshes.length === 0 && shouldDispose) {
  28811. this.dispose();
  28812. }
  28813. };
  28814. Geometry.prototype.applyToMesh = function (mesh) {
  28815. if (mesh._geometry === this) {
  28816. return;
  28817. }
  28818. var previousGeometry = mesh._geometry;
  28819. if (previousGeometry) {
  28820. previousGeometry.releaseForMesh(mesh);
  28821. }
  28822. var meshes = this._meshes;
  28823. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28824. mesh._geometry = this;
  28825. this._scene.pushGeometry(this);
  28826. meshes.push(mesh);
  28827. if (this.isReady()) {
  28828. this._applyToMesh(mesh);
  28829. }
  28830. else {
  28831. mesh._boundingInfo = this._boundingInfo;
  28832. }
  28833. };
  28834. Geometry.prototype._applyToMesh = function (mesh) {
  28835. var numOfMeshes = this._meshes.length;
  28836. // vertexBuffers
  28837. for (var kind in this._vertexBuffers) {
  28838. if (numOfMeshes === 1) {
  28839. this._vertexBuffers[kind].create();
  28840. }
  28841. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28842. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28843. mesh._resetPointsArrayCache();
  28844. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28845. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28846. mesh._createGlobalSubMesh();
  28847. //bounding info was just created again, world matrix should be applied again.
  28848. mesh._updateBoundingInfo();
  28849. }
  28850. }
  28851. // indexBuffer
  28852. if (numOfMeshes === 1 && this._indices) {
  28853. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28854. }
  28855. if (this._indexBuffer) {
  28856. this._indexBuffer.references = numOfMeshes;
  28857. }
  28858. };
  28859. Geometry.prototype.notifyUpdate = function (kind) {
  28860. if (this.onGeometryUpdated) {
  28861. this.onGeometryUpdated(this, kind);
  28862. }
  28863. };
  28864. Geometry.prototype.load = function (scene, onLoaded) {
  28865. var _this = this;
  28866. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28867. return;
  28868. }
  28869. if (this.isReady()) {
  28870. if (onLoaded) {
  28871. onLoaded();
  28872. }
  28873. return;
  28874. }
  28875. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28876. scene._addPendingData(this);
  28877. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28878. _this._delayLoadingFunction(JSON.parse(data), _this);
  28879. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28880. _this._delayInfo = [];
  28881. scene._removePendingData(_this);
  28882. var meshes = _this._meshes;
  28883. var numOfMeshes = meshes.length;
  28884. for (var index = 0; index < numOfMeshes; index++) {
  28885. _this._applyToMesh(meshes[index]);
  28886. }
  28887. if (onLoaded) {
  28888. onLoaded();
  28889. }
  28890. }, function () { }, scene.database);
  28891. };
  28892. Geometry.prototype.isDisposed = function () {
  28893. return this._isDisposed;
  28894. };
  28895. Geometry.prototype.dispose = function () {
  28896. var meshes = this._meshes;
  28897. var numOfMeshes = meshes.length;
  28898. var index;
  28899. for (index = 0; index < numOfMeshes; index++) {
  28900. this.releaseForMesh(meshes[index]);
  28901. }
  28902. this._meshes = [];
  28903. for (var kind in this._vertexBuffers) {
  28904. this._vertexBuffers[kind].dispose();
  28905. }
  28906. this._vertexBuffers = [];
  28907. this._totalVertices = 0;
  28908. if (this._indexBuffer) {
  28909. this._engine._releaseBuffer(this._indexBuffer);
  28910. }
  28911. this._indexBuffer = null;
  28912. this._indices = [];
  28913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28914. this.delayLoadingFile = null;
  28915. this._delayLoadingFunction = null;
  28916. this._delayInfo = [];
  28917. this._boundingInfo = null; // todo: .dispose()
  28918. this._scene.removeGeometry(this);
  28919. this._isDisposed = true;
  28920. };
  28921. Geometry.prototype.copy = function (id) {
  28922. var vertexData = new BABYLON.VertexData();
  28923. vertexData.indices = [];
  28924. var indices = this.getIndices();
  28925. for (var index = 0; index < indices.length; index++) {
  28926. vertexData.indices.push(indices[index]);
  28927. }
  28928. var updatable = false;
  28929. var stopChecking = false;
  28930. for (var kind in this._vertexBuffers) {
  28931. // using slice() to make a copy of the array and not just reference it
  28932. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28933. if (!stopChecking) {
  28934. updatable = this.getVertexBuffer(kind).isUpdatable();
  28935. stopChecking = !updatable;
  28936. }
  28937. }
  28938. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28939. geometry.delayLoadState = this.delayLoadState;
  28940. geometry.delayLoadingFile = this.delayLoadingFile;
  28941. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28942. for (kind in this._delayInfo) {
  28943. geometry._delayInfo = geometry._delayInfo || [];
  28944. geometry._delayInfo.push(kind);
  28945. }
  28946. // Bounding info
  28947. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28948. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28949. return geometry;
  28950. };
  28951. // Statics
  28952. Geometry.ExtractFromMesh = function (mesh, id) {
  28953. var geometry = mesh._geometry;
  28954. if (!geometry) {
  28955. return null;
  28956. }
  28957. return geometry.copy(id);
  28958. };
  28959. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28960. // be aware Math.random() could cause collisions
  28961. Geometry.RandomId = function () {
  28962. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28963. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28964. return v.toString(16);
  28965. });
  28966. };
  28967. return Geometry;
  28968. })();
  28969. BABYLON.Geometry = Geometry;
  28970. /////// Primitives //////////////////////////////////////////////
  28971. var Geometry;
  28972. (function (Geometry) {
  28973. var Primitives;
  28974. (function (Primitives) {
  28975. /// Abstract class
  28976. var _Primitive = (function (_super) {
  28977. __extends(_Primitive, _super);
  28978. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28979. this._beingRegenerated = true;
  28980. this._canBeRegenerated = canBeRegenerated;
  28981. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28982. this._beingRegenerated = false;
  28983. }
  28984. _Primitive.prototype.canBeRegenerated = function () {
  28985. return this._canBeRegenerated;
  28986. };
  28987. _Primitive.prototype.regenerate = function () {
  28988. if (!this._canBeRegenerated) {
  28989. return;
  28990. }
  28991. this._beingRegenerated = true;
  28992. this.setAllVerticesData(this._regenerateVertexData(), false);
  28993. this._beingRegenerated = false;
  28994. };
  28995. _Primitive.prototype.asNewGeometry = function (id) {
  28996. return _super.prototype.copy.call(this, id);
  28997. };
  28998. // overrides
  28999. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29000. if (!this._beingRegenerated) {
  29001. return;
  29002. }
  29003. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29004. };
  29005. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29006. if (!this._beingRegenerated) {
  29007. return;
  29008. }
  29009. _super.prototype.setVerticesData.call(this, kind, data, false);
  29010. };
  29011. // to override
  29012. // protected
  29013. _Primitive.prototype._regenerateVertexData = function () {
  29014. throw new Error("Abstract method");
  29015. };
  29016. _Primitive.prototype.copy = function (id) {
  29017. throw new Error("Must be overriden in sub-classes.");
  29018. };
  29019. return _Primitive;
  29020. })(Geometry);
  29021. Primitives._Primitive = _Primitive;
  29022. var Ribbon = (function (_super) {
  29023. __extends(Ribbon, _super);
  29024. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29025. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29026. this.pathArray = pathArray;
  29027. this.closeArray = closeArray;
  29028. this.closePath = closePath;
  29029. this.offset = offset;
  29030. this.side = side;
  29031. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29032. }
  29033. Ribbon.prototype._regenerateVertexData = function () {
  29034. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  29035. };
  29036. Ribbon.prototype.copy = function (id) {
  29037. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29038. };
  29039. return Ribbon;
  29040. })(_Primitive);
  29041. Primitives.Ribbon = Ribbon;
  29042. var Box = (function (_super) {
  29043. __extends(Box, _super);
  29044. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29045. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29046. this.size = size;
  29047. this.side = side;
  29048. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29049. }
  29050. Box.prototype._regenerateVertexData = function () {
  29051. return BABYLON.VertexData.CreateBox(this.size, this.side);
  29052. };
  29053. Box.prototype.copy = function (id) {
  29054. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29055. };
  29056. return Box;
  29057. })(_Primitive);
  29058. Primitives.Box = Box;
  29059. var Sphere = (function (_super) {
  29060. __extends(Sphere, _super);
  29061. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29062. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29063. this.segments = segments;
  29064. this.diameter = diameter;
  29065. this.side = side;
  29066. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29067. }
  29068. Sphere.prototype._regenerateVertexData = function () {
  29069. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  29070. };
  29071. Sphere.prototype.copy = function (id) {
  29072. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29073. };
  29074. return Sphere;
  29075. })(_Primitive);
  29076. Primitives.Sphere = Sphere;
  29077. var Cylinder = (function (_super) {
  29078. __extends(Cylinder, _super);
  29079. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29080. if (subdivisions === void 0) { subdivisions = 1; }
  29081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29082. this.height = height;
  29083. this.diameterTop = diameterTop;
  29084. this.diameterBottom = diameterBottom;
  29085. this.tessellation = tessellation;
  29086. this.subdivisions = subdivisions;
  29087. this.side = side;
  29088. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29089. }
  29090. Cylinder.prototype._regenerateVertexData = function () {
  29091. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  29092. };
  29093. Cylinder.prototype.copy = function (id) {
  29094. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29095. };
  29096. return Cylinder;
  29097. })(_Primitive);
  29098. Primitives.Cylinder = Cylinder;
  29099. var Torus = (function (_super) {
  29100. __extends(Torus, _super);
  29101. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29102. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29103. this.diameter = diameter;
  29104. this.thickness = thickness;
  29105. this.tessellation = tessellation;
  29106. this.side = side;
  29107. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29108. }
  29109. Torus.prototype._regenerateVertexData = function () {
  29110. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  29111. };
  29112. Torus.prototype.copy = function (id) {
  29113. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29114. };
  29115. return Torus;
  29116. })(_Primitive);
  29117. Primitives.Torus = Torus;
  29118. var Ground = (function (_super) {
  29119. __extends(Ground, _super);
  29120. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29121. this.width = width;
  29122. this.height = height;
  29123. this.subdivisions = subdivisions;
  29124. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29125. }
  29126. Ground.prototype._regenerateVertexData = function () {
  29127. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  29128. };
  29129. Ground.prototype.copy = function (id) {
  29130. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29131. };
  29132. return Ground;
  29133. })(_Primitive);
  29134. Primitives.Ground = Ground;
  29135. var TiledGround = (function (_super) {
  29136. __extends(TiledGround, _super);
  29137. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29138. this.xmin = xmin;
  29139. this.zmin = zmin;
  29140. this.xmax = xmax;
  29141. this.zmax = zmax;
  29142. this.subdivisions = subdivisions;
  29143. this.precision = precision;
  29144. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29145. }
  29146. TiledGround.prototype._regenerateVertexData = function () {
  29147. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  29148. };
  29149. TiledGround.prototype.copy = function (id) {
  29150. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29151. };
  29152. return TiledGround;
  29153. })(_Primitive);
  29154. Primitives.TiledGround = TiledGround;
  29155. var Plane = (function (_super) {
  29156. __extends(Plane, _super);
  29157. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29158. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29159. this.size = size;
  29160. this.side = side;
  29161. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29162. }
  29163. Plane.prototype._regenerateVertexData = function () {
  29164. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  29165. };
  29166. Plane.prototype.copy = function (id) {
  29167. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29168. };
  29169. return Plane;
  29170. })(_Primitive);
  29171. Primitives.Plane = Plane;
  29172. var TorusKnot = (function (_super) {
  29173. __extends(TorusKnot, _super);
  29174. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29175. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29176. this.radius = radius;
  29177. this.tube = tube;
  29178. this.radialSegments = radialSegments;
  29179. this.tubularSegments = tubularSegments;
  29180. this.p = p;
  29181. this.q = q;
  29182. this.side = side;
  29183. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29184. }
  29185. TorusKnot.prototype._regenerateVertexData = function () {
  29186. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  29187. };
  29188. TorusKnot.prototype.copy = function (id) {
  29189. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29190. };
  29191. return TorusKnot;
  29192. })(_Primitive);
  29193. Primitives.TorusKnot = TorusKnot;
  29194. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29195. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29196. })(BABYLON || (BABYLON = {}));
  29197. var BABYLON;
  29198. (function (BABYLON) {
  29199. var GroundMesh = (function (_super) {
  29200. __extends(GroundMesh, _super);
  29201. function GroundMesh(name, scene) {
  29202. _super.call(this, name, scene);
  29203. this.generateOctree = false;
  29204. this._worldInverse = new BABYLON.Matrix();
  29205. }
  29206. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29207. get: function () {
  29208. return this._subdivisions;
  29209. },
  29210. enumerable: true,
  29211. configurable: true
  29212. });
  29213. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29214. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29215. this._subdivisions = chunksCount;
  29216. this.subdivide(this._subdivisions);
  29217. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29218. };
  29219. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29220. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29221. this.getWorldMatrix().invertToRef(this._worldInverse);
  29222. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29223. var pickInfo = this.intersects(ray);
  29224. if (pickInfo.hit) {
  29225. return pickInfo.pickedPoint.y;
  29226. }
  29227. return 0;
  29228. };
  29229. return GroundMesh;
  29230. })(BABYLON.Mesh);
  29231. BABYLON.GroundMesh = GroundMesh;
  29232. })(BABYLON || (BABYLON = {}));
  29233. var BABYLON;
  29234. (function (BABYLON) {
  29235. var LinesMesh = (function (_super) {
  29236. __extends(LinesMesh, _super);
  29237. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29238. if (parent === void 0) { parent = null; }
  29239. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29240. this.color = new BABYLON.Color3(1, 1, 1);
  29241. this.alpha = 1;
  29242. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29243. attributes: ["position"],
  29244. uniforms: ["worldViewProjection", "color"],
  29245. needAlphaBlending: true
  29246. });
  29247. }
  29248. Object.defineProperty(LinesMesh.prototype, "material", {
  29249. get: function () {
  29250. return this._colorShader;
  29251. },
  29252. enumerable: true,
  29253. configurable: true
  29254. });
  29255. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29256. get: function () {
  29257. return false;
  29258. },
  29259. enumerable: true,
  29260. configurable: true
  29261. });
  29262. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29263. get: function () {
  29264. return false;
  29265. },
  29266. enumerable: true,
  29267. configurable: true
  29268. });
  29269. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29270. var engine = this.getScene().getEngine();
  29271. var indexToBind = this._geometry.getIndexBuffer();
  29272. // VBOs
  29273. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29274. // Color
  29275. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29276. };
  29277. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29278. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29279. return;
  29280. }
  29281. var engine = this.getScene().getEngine();
  29282. // Draw order
  29283. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29284. };
  29285. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29286. return null;
  29287. };
  29288. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29289. this._colorShader.dispose();
  29290. _super.prototype.dispose.call(this, doNotRecurse);
  29291. };
  29292. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29293. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29294. };
  29295. return LinesMesh;
  29296. })(BABYLON.Mesh);
  29297. BABYLON.LinesMesh = LinesMesh;
  29298. })(BABYLON || (BABYLON = {}));
  29299. var BABYLON;
  29300. (function (BABYLON) {
  29301. var OutlineRenderer = (function () {
  29302. function OutlineRenderer(scene) {
  29303. this._scene = scene;
  29304. }
  29305. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29306. var _this = this;
  29307. if (useOverlay === void 0) { useOverlay = false; }
  29308. var scene = this._scene;
  29309. var engine = this._scene.getEngine();
  29310. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29311. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29312. return;
  29313. }
  29314. var mesh = subMesh.getRenderingMesh();
  29315. var material = subMesh.getMaterial();
  29316. engine.enableEffect(this._effect);
  29317. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29318. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29319. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29320. // Bones
  29321. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29322. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29323. }
  29324. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29325. // Alpha test
  29326. if (material && material.needAlphaTesting()) {
  29327. var alphaTexture = material.getAlphaTestTexture();
  29328. this._effect.setTexture("diffuseSampler", alphaTexture);
  29329. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29330. }
  29331. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29332. };
  29333. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29334. var defines = [];
  29335. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29336. var mesh = subMesh.getMesh();
  29337. var material = subMesh.getMaterial();
  29338. // Alpha test
  29339. if (material && material.needAlphaTesting()) {
  29340. defines.push("#define ALPHATEST");
  29341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29342. attribs.push(BABYLON.VertexBuffer.UVKind);
  29343. defines.push("#define UV1");
  29344. }
  29345. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29346. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29347. defines.push("#define UV2");
  29348. }
  29349. }
  29350. // Bones
  29351. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29354. defines.push("#define BONES");
  29355. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29356. }
  29357. // Instances
  29358. if (useInstances) {
  29359. defines.push("#define INSTANCES");
  29360. attribs.push("world0");
  29361. attribs.push("world1");
  29362. attribs.push("world2");
  29363. attribs.push("world3");
  29364. }
  29365. // Get correct effect
  29366. var join = defines.join("\n");
  29367. if (this._cachedDefines !== join) {
  29368. this._cachedDefines = join;
  29369. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29370. }
  29371. return this._effect.isReady();
  29372. };
  29373. return OutlineRenderer;
  29374. })();
  29375. BABYLON.OutlineRenderer = OutlineRenderer;
  29376. })(BABYLON || (BABYLON = {}));
  29377. var BABYLON;
  29378. (function (BABYLON) {
  29379. var MeshAssetTask = (function () {
  29380. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29381. this.name = name;
  29382. this.meshesNames = meshesNames;
  29383. this.rootUrl = rootUrl;
  29384. this.sceneFilename = sceneFilename;
  29385. this.isCompleted = false;
  29386. }
  29387. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29388. var _this = this;
  29389. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29390. _this.loadedMeshes = meshes;
  29391. _this.loadedParticleSystems = particleSystems;
  29392. _this.loadedSkeletons = skeletons;
  29393. _this.isCompleted = true;
  29394. if (_this.onSuccess) {
  29395. _this.onSuccess(_this);
  29396. }
  29397. onSuccess();
  29398. }, null, function () {
  29399. if (_this.onError) {
  29400. _this.onError(_this);
  29401. }
  29402. onError();
  29403. });
  29404. };
  29405. return MeshAssetTask;
  29406. })();
  29407. BABYLON.MeshAssetTask = MeshAssetTask;
  29408. var TextFileAssetTask = (function () {
  29409. function TextFileAssetTask(name, url) {
  29410. this.name = name;
  29411. this.url = url;
  29412. this.isCompleted = false;
  29413. }
  29414. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29415. var _this = this;
  29416. BABYLON.Tools.LoadFile(this.url, function (data) {
  29417. _this.text = data;
  29418. _this.isCompleted = true;
  29419. if (_this.onSuccess) {
  29420. _this.onSuccess(_this);
  29421. }
  29422. onSuccess();
  29423. }, null, scene.database, false, function () {
  29424. if (_this.onError) {
  29425. _this.onError(_this);
  29426. }
  29427. onError();
  29428. });
  29429. };
  29430. return TextFileAssetTask;
  29431. })();
  29432. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29433. var BinaryFileAssetTask = (function () {
  29434. function BinaryFileAssetTask(name, url) {
  29435. this.name = name;
  29436. this.url = url;
  29437. this.isCompleted = false;
  29438. }
  29439. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29440. var _this = this;
  29441. BABYLON.Tools.LoadFile(this.url, function (data) {
  29442. _this.data = data;
  29443. _this.isCompleted = true;
  29444. if (_this.onSuccess) {
  29445. _this.onSuccess(_this);
  29446. }
  29447. onSuccess();
  29448. }, null, scene.database, true, function () {
  29449. if (_this.onError) {
  29450. _this.onError(_this);
  29451. }
  29452. onError();
  29453. });
  29454. };
  29455. return BinaryFileAssetTask;
  29456. })();
  29457. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29458. var ImageAssetTask = (function () {
  29459. function ImageAssetTask(name, url) {
  29460. this.name = name;
  29461. this.url = url;
  29462. this.isCompleted = false;
  29463. }
  29464. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29465. var _this = this;
  29466. var img = new Image();
  29467. img.onload = function () {
  29468. _this.image = img;
  29469. _this.isCompleted = true;
  29470. if (_this.onSuccess) {
  29471. _this.onSuccess(_this);
  29472. }
  29473. onSuccess();
  29474. };
  29475. img.onerror = function () {
  29476. if (_this.onError) {
  29477. _this.onError(_this);
  29478. }
  29479. onError();
  29480. };
  29481. img.src = this.url;
  29482. };
  29483. return ImageAssetTask;
  29484. })();
  29485. BABYLON.ImageAssetTask = ImageAssetTask;
  29486. var TextureAssetTask = (function () {
  29487. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29488. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29489. this.name = name;
  29490. this.url = url;
  29491. this.noMipmap = noMipmap;
  29492. this.invertY = invertY;
  29493. this.samplingMode = samplingMode;
  29494. this.isCompleted = false;
  29495. }
  29496. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29497. var _this = this;
  29498. var onload = function () {
  29499. _this.isCompleted = true;
  29500. if (_this.onSuccess) {
  29501. _this.onSuccess(_this);
  29502. }
  29503. onSuccess();
  29504. };
  29505. var onerror = function () {
  29506. if (_this.onError) {
  29507. _this.onError(_this);
  29508. }
  29509. onError();
  29510. };
  29511. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29512. };
  29513. return TextureAssetTask;
  29514. })();
  29515. BABYLON.TextureAssetTask = TextureAssetTask;
  29516. var AssetsManager = (function () {
  29517. function AssetsManager(scene) {
  29518. this._tasks = new Array();
  29519. this._waitingTasksCount = 0;
  29520. this.useDefaultLoadingScreen = true;
  29521. this._scene = scene;
  29522. }
  29523. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29524. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29525. this._tasks.push(task);
  29526. return task;
  29527. };
  29528. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29529. var task = new TextFileAssetTask(taskName, url);
  29530. this._tasks.push(task);
  29531. return task;
  29532. };
  29533. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29534. var task = new BinaryFileAssetTask(taskName, url);
  29535. this._tasks.push(task);
  29536. return task;
  29537. };
  29538. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29539. var task = new ImageAssetTask(taskName, url);
  29540. this._tasks.push(task);
  29541. return task;
  29542. };
  29543. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29545. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29546. this._tasks.push(task);
  29547. return task;
  29548. };
  29549. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29550. this._waitingTasksCount--;
  29551. if (this._waitingTasksCount === 0) {
  29552. if (this.onFinish) {
  29553. this.onFinish(this._tasks);
  29554. }
  29555. this._scene.getEngine().hideLoadingUI();
  29556. }
  29557. };
  29558. AssetsManager.prototype._runTask = function (task) {
  29559. var _this = this;
  29560. task.run(this._scene, function () {
  29561. if (_this.onTaskSuccess) {
  29562. _this.onTaskSuccess(task);
  29563. }
  29564. _this._decreaseWaitingTasksCount();
  29565. }, function () {
  29566. if (_this.onTaskError) {
  29567. _this.onTaskError(task);
  29568. }
  29569. _this._decreaseWaitingTasksCount();
  29570. });
  29571. };
  29572. AssetsManager.prototype.reset = function () {
  29573. this._tasks = new Array();
  29574. return this;
  29575. };
  29576. AssetsManager.prototype.load = function () {
  29577. this._waitingTasksCount = this._tasks.length;
  29578. if (this._waitingTasksCount === 0) {
  29579. if (this.onFinish) {
  29580. this.onFinish(this._tasks);
  29581. }
  29582. return this;
  29583. }
  29584. if (this.useDefaultLoadingScreen) {
  29585. this._scene.getEngine().displayLoadingUI();
  29586. }
  29587. for (var index = 0; index < this._tasks.length; index++) {
  29588. var task = this._tasks[index];
  29589. this._runTask(task);
  29590. }
  29591. return this;
  29592. };
  29593. return AssetsManager;
  29594. })();
  29595. BABYLON.AssetsManager = AssetsManager;
  29596. })(BABYLON || (BABYLON = {}));
  29597. var BABYLON;
  29598. (function (BABYLON) {
  29599. var VRDeviceOrientationFreeCamera = (function (_super) {
  29600. __extends(VRDeviceOrientationFreeCamera, _super);
  29601. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29602. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29603. _super.call(this, name, position, scene);
  29604. this._alpha = 0;
  29605. this._beta = 0;
  29606. this._gamma = 0;
  29607. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29608. metrics.compensateDistorsion = compensateDistorsion;
  29609. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29610. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29611. }
  29612. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29613. this._alpha = +evt.alpha | 0;
  29614. this._beta = +evt.beta | 0;
  29615. this._gamma = +evt.gamma | 0;
  29616. if (this._gamma < 0) {
  29617. this._gamma = 90 + this._gamma;
  29618. }
  29619. else {
  29620. // Incline it in the correct angle.
  29621. this._gamma = 270 - this._gamma;
  29622. }
  29623. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29624. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29625. this.rotation.z = this._beta / 180.0 * Math.PI;
  29626. };
  29627. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29628. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29629. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29630. };
  29631. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29632. _super.prototype.detachControl.call(this, element);
  29633. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29634. };
  29635. return VRDeviceOrientationFreeCamera;
  29636. })(BABYLON.FreeCamera);
  29637. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29638. })(BABYLON || (BABYLON = {}));
  29639. var BABYLON;
  29640. (function (BABYLON) {
  29641. var WebVRFreeCamera = (function (_super) {
  29642. __extends(WebVRFreeCamera, _super);
  29643. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29644. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29645. _super.call(this, name, position, scene);
  29646. this._hmdDevice = null;
  29647. this._sensorDevice = null;
  29648. this._cacheState = null;
  29649. this._cacheQuaternion = new BABYLON.Quaternion();
  29650. this._cacheRotation = BABYLON.Vector3.Zero();
  29651. this._vrEnabled = false;
  29652. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29653. metrics.compensateDistorsion = compensateDistorsion;
  29654. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29655. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29656. }
  29657. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29658. var size = devices.length;
  29659. var i = 0;
  29660. // Reset devices.
  29661. this._sensorDevice = null;
  29662. this._hmdDevice = null;
  29663. // Search for a HmdDevice.
  29664. while (i < size && this._hmdDevice === null) {
  29665. if (devices[i] instanceof HMDVRDevice) {
  29666. this._hmdDevice = devices[i];
  29667. }
  29668. i++;
  29669. }
  29670. i = 0;
  29671. while (i < size && this._sensorDevice === null) {
  29672. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29673. this._sensorDevice = devices[i];
  29674. }
  29675. i++;
  29676. }
  29677. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29678. };
  29679. WebVRFreeCamera.prototype._checkInputs = function () {
  29680. if (this._vrEnabled) {
  29681. this._cacheState = this._sensorDevice.getState();
  29682. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29683. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29684. this.rotation.x = -this._cacheRotation.z;
  29685. this.rotation.y = -this._cacheRotation.y;
  29686. this.rotation.z = this._cacheRotation.x;
  29687. }
  29688. _super.prototype._checkInputs.call(this);
  29689. };
  29690. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29691. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29692. if (navigator.getVRDevices) {
  29693. navigator.getVRDevices().then(this._getWebVRDevices);
  29694. }
  29695. else if (navigator.mozGetVRDevices) {
  29696. navigator.mozGetVRDevices(this._getWebVRDevices);
  29697. }
  29698. };
  29699. WebVRFreeCamera.prototype.detachControl = function (element) {
  29700. _super.prototype.detachControl.call(this, element);
  29701. this._vrEnabled = false;
  29702. };
  29703. return WebVRFreeCamera;
  29704. })(BABYLON.FreeCamera);
  29705. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29706. })(BABYLON || (BABYLON = {}));
  29707. var BABYLON;
  29708. (function (BABYLON) {
  29709. // Standard optimizations
  29710. var SceneOptimization = (function () {
  29711. function SceneOptimization(priority) {
  29712. if (priority === void 0) { priority = 0; }
  29713. this.priority = priority;
  29714. this.apply = function (scene) {
  29715. return true; // Return true if everything that can be done was applied
  29716. };
  29717. }
  29718. return SceneOptimization;
  29719. })();
  29720. BABYLON.SceneOptimization = SceneOptimization;
  29721. var TextureOptimization = (function (_super) {
  29722. __extends(TextureOptimization, _super);
  29723. function TextureOptimization(priority, maximumSize) {
  29724. var _this = this;
  29725. if (priority === void 0) { priority = 0; }
  29726. if (maximumSize === void 0) { maximumSize = 1024; }
  29727. _super.call(this, priority);
  29728. this.priority = priority;
  29729. this.maximumSize = maximumSize;
  29730. this.apply = function (scene) {
  29731. var allDone = true;
  29732. for (var index = 0; index < scene.textures.length; index++) {
  29733. var texture = scene.textures[index];
  29734. if (!texture.canRescale) {
  29735. continue;
  29736. }
  29737. var currentSize = texture.getSize();
  29738. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29739. if (maxDimension > _this.maximumSize) {
  29740. texture.scale(0.5);
  29741. allDone = false;
  29742. }
  29743. }
  29744. return allDone;
  29745. };
  29746. }
  29747. return TextureOptimization;
  29748. })(SceneOptimization);
  29749. BABYLON.TextureOptimization = TextureOptimization;
  29750. var HardwareScalingOptimization = (function (_super) {
  29751. __extends(HardwareScalingOptimization, _super);
  29752. function HardwareScalingOptimization(priority, maximumScale) {
  29753. var _this = this;
  29754. if (priority === void 0) { priority = 0; }
  29755. if (maximumScale === void 0) { maximumScale = 2; }
  29756. _super.call(this, priority);
  29757. this.priority = priority;
  29758. this.maximumScale = maximumScale;
  29759. this._currentScale = 1;
  29760. this.apply = function (scene) {
  29761. _this._currentScale++;
  29762. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29763. return _this._currentScale >= _this.maximumScale;
  29764. };
  29765. }
  29766. return HardwareScalingOptimization;
  29767. })(SceneOptimization);
  29768. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29769. var ShadowsOptimization = (function (_super) {
  29770. __extends(ShadowsOptimization, _super);
  29771. function ShadowsOptimization() {
  29772. _super.apply(this, arguments);
  29773. this.apply = function (scene) {
  29774. scene.shadowsEnabled = false;
  29775. return true;
  29776. };
  29777. }
  29778. return ShadowsOptimization;
  29779. })(SceneOptimization);
  29780. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29781. var PostProcessesOptimization = (function (_super) {
  29782. __extends(PostProcessesOptimization, _super);
  29783. function PostProcessesOptimization() {
  29784. _super.apply(this, arguments);
  29785. this.apply = function (scene) {
  29786. scene.postProcessesEnabled = false;
  29787. return true;
  29788. };
  29789. }
  29790. return PostProcessesOptimization;
  29791. })(SceneOptimization);
  29792. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29793. var LensFlaresOptimization = (function (_super) {
  29794. __extends(LensFlaresOptimization, _super);
  29795. function LensFlaresOptimization() {
  29796. _super.apply(this, arguments);
  29797. this.apply = function (scene) {
  29798. scene.lensFlaresEnabled = false;
  29799. return true;
  29800. };
  29801. }
  29802. return LensFlaresOptimization;
  29803. })(SceneOptimization);
  29804. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29805. var ParticlesOptimization = (function (_super) {
  29806. __extends(ParticlesOptimization, _super);
  29807. function ParticlesOptimization() {
  29808. _super.apply(this, arguments);
  29809. this.apply = function (scene) {
  29810. scene.particlesEnabled = false;
  29811. return true;
  29812. };
  29813. }
  29814. return ParticlesOptimization;
  29815. })(SceneOptimization);
  29816. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29817. var RenderTargetsOptimization = (function (_super) {
  29818. __extends(RenderTargetsOptimization, _super);
  29819. function RenderTargetsOptimization() {
  29820. _super.apply(this, arguments);
  29821. this.apply = function (scene) {
  29822. scene.renderTargetsEnabled = false;
  29823. return true;
  29824. };
  29825. }
  29826. return RenderTargetsOptimization;
  29827. })(SceneOptimization);
  29828. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29829. var MergeMeshesOptimization = (function (_super) {
  29830. __extends(MergeMeshesOptimization, _super);
  29831. function MergeMeshesOptimization() {
  29832. var _this = this;
  29833. _super.apply(this, arguments);
  29834. this._canBeMerged = function (abstractMesh) {
  29835. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29836. return false;
  29837. }
  29838. var mesh = abstractMesh;
  29839. if (!mesh.isVisible || !mesh.isEnabled()) {
  29840. return false;
  29841. }
  29842. if (mesh.instances.length > 0) {
  29843. return false;
  29844. }
  29845. if (mesh.skeleton || mesh.hasLODLevels) {
  29846. return false;
  29847. }
  29848. return true;
  29849. };
  29850. this.apply = function (scene, updateSelectionTree) {
  29851. var globalPool = scene.meshes.slice(0);
  29852. var globalLength = globalPool.length;
  29853. for (var index = 0; index < globalLength; index++) {
  29854. var currentPool = new Array();
  29855. var current = globalPool[index];
  29856. // Checks
  29857. if (!_this._canBeMerged(current)) {
  29858. continue;
  29859. }
  29860. currentPool.push(current);
  29861. // Find compatible meshes
  29862. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29863. var otherMesh = globalPool[subIndex];
  29864. if (!_this._canBeMerged(otherMesh)) {
  29865. continue;
  29866. }
  29867. if (otherMesh.material !== current.material) {
  29868. continue;
  29869. }
  29870. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29871. continue;
  29872. }
  29873. currentPool.push(otherMesh);
  29874. globalLength--;
  29875. globalPool.splice(subIndex, 1);
  29876. subIndex--;
  29877. }
  29878. if (currentPool.length < 2) {
  29879. continue;
  29880. }
  29881. // Merge meshes
  29882. BABYLON.Mesh.MergeMeshes(currentPool);
  29883. }
  29884. if (updateSelectionTree != undefined) {
  29885. if (updateSelectionTree) {
  29886. scene.createOrUpdateSelectionOctree();
  29887. }
  29888. }
  29889. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29890. scene.createOrUpdateSelectionOctree();
  29891. }
  29892. return true;
  29893. };
  29894. }
  29895. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29896. get: function () {
  29897. return MergeMeshesOptimization._UpdateSelectionTree;
  29898. },
  29899. set: function (value) {
  29900. MergeMeshesOptimization._UpdateSelectionTree = value;
  29901. },
  29902. enumerable: true,
  29903. configurable: true
  29904. });
  29905. MergeMeshesOptimization._UpdateSelectionTree = false;
  29906. return MergeMeshesOptimization;
  29907. })(SceneOptimization);
  29908. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29909. // Options
  29910. var SceneOptimizerOptions = (function () {
  29911. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29912. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29913. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29914. this.targetFrameRate = targetFrameRate;
  29915. this.trackerDuration = trackerDuration;
  29916. this.optimizations = new Array();
  29917. }
  29918. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29919. var result = new SceneOptimizerOptions(targetFrameRate);
  29920. var priority = 0;
  29921. result.optimizations.push(new MergeMeshesOptimization(priority));
  29922. result.optimizations.push(new ShadowsOptimization(priority));
  29923. result.optimizations.push(new LensFlaresOptimization(priority));
  29924. // Next priority
  29925. priority++;
  29926. result.optimizations.push(new PostProcessesOptimization(priority));
  29927. result.optimizations.push(new ParticlesOptimization(priority));
  29928. // Next priority
  29929. priority++;
  29930. result.optimizations.push(new TextureOptimization(priority, 1024));
  29931. return result;
  29932. };
  29933. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29934. var result = new SceneOptimizerOptions(targetFrameRate);
  29935. var priority = 0;
  29936. result.optimizations.push(new MergeMeshesOptimization(priority));
  29937. result.optimizations.push(new ShadowsOptimization(priority));
  29938. result.optimizations.push(new LensFlaresOptimization(priority));
  29939. // Next priority
  29940. priority++;
  29941. result.optimizations.push(new PostProcessesOptimization(priority));
  29942. result.optimizations.push(new ParticlesOptimization(priority));
  29943. // Next priority
  29944. priority++;
  29945. result.optimizations.push(new TextureOptimization(priority, 512));
  29946. // Next priority
  29947. priority++;
  29948. result.optimizations.push(new RenderTargetsOptimization(priority));
  29949. // Next priority
  29950. priority++;
  29951. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29952. return result;
  29953. };
  29954. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29955. var result = new SceneOptimizerOptions(targetFrameRate);
  29956. var priority = 0;
  29957. result.optimizations.push(new MergeMeshesOptimization(priority));
  29958. result.optimizations.push(new ShadowsOptimization(priority));
  29959. result.optimizations.push(new LensFlaresOptimization(priority));
  29960. // Next priority
  29961. priority++;
  29962. result.optimizations.push(new PostProcessesOptimization(priority));
  29963. result.optimizations.push(new ParticlesOptimization(priority));
  29964. // Next priority
  29965. priority++;
  29966. result.optimizations.push(new TextureOptimization(priority, 256));
  29967. // Next priority
  29968. priority++;
  29969. result.optimizations.push(new RenderTargetsOptimization(priority));
  29970. // Next priority
  29971. priority++;
  29972. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29973. return result;
  29974. };
  29975. return SceneOptimizerOptions;
  29976. })();
  29977. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29978. // Scene optimizer tool
  29979. var SceneOptimizer = (function () {
  29980. function SceneOptimizer() {
  29981. }
  29982. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29983. // TODO: add an epsilon
  29984. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29985. if (onSuccess) {
  29986. onSuccess();
  29987. }
  29988. return;
  29989. }
  29990. // Apply current level of optimizations
  29991. var allDone = true;
  29992. var noOptimizationApplied = true;
  29993. for (var index = 0; index < options.optimizations.length; index++) {
  29994. var optimization = options.optimizations[index];
  29995. if (optimization.priority === currentPriorityLevel) {
  29996. noOptimizationApplied = false;
  29997. allDone = allDone && optimization.apply(scene);
  29998. }
  29999. }
  30000. // If no optimization was applied, this is a failure :(
  30001. if (noOptimizationApplied) {
  30002. if (onFailure) {
  30003. onFailure();
  30004. }
  30005. return;
  30006. }
  30007. // If all optimizations were done, move to next level
  30008. if (allDone) {
  30009. currentPriorityLevel++;
  30010. }
  30011. // Let's the system running for a specific amount of time before checking FPS
  30012. scene.executeWhenReady(function () {
  30013. setTimeout(function () {
  30014. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  30015. }, options.trackerDuration);
  30016. });
  30017. };
  30018. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  30019. if (!options) {
  30020. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  30021. }
  30022. // Let's the system running for a specific amount of time before checking FPS
  30023. scene.executeWhenReady(function () {
  30024. setTimeout(function () {
  30025. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  30026. }, options.trackerDuration);
  30027. });
  30028. };
  30029. return SceneOptimizer;
  30030. })();
  30031. BABYLON.SceneOptimizer = SceneOptimizer;
  30032. })(BABYLON || (BABYLON = {}));
  30033. var BABYLON;
  30034. (function (BABYLON) {
  30035. var Internals;
  30036. (function (Internals) {
  30037. var MeshLODLevel = (function () {
  30038. function MeshLODLevel(distance, mesh) {
  30039. this.distance = distance;
  30040. this.mesh = mesh;
  30041. }
  30042. return MeshLODLevel;
  30043. })();
  30044. Internals.MeshLODLevel = MeshLODLevel;
  30045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30046. })(BABYLON || (BABYLON = {}));
  30047. var BABYLON;
  30048. (function (BABYLON) {
  30049. var AudioEngine = (function () {
  30050. function AudioEngine() {
  30051. this._audioContext = null;
  30052. this._audioContextInitialized = false;
  30053. this.canUseWebAudio = false;
  30054. this.WarnedWebAudioUnsupported = false;
  30055. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  30056. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  30057. this.canUseWebAudio = true;
  30058. }
  30059. }
  30060. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30061. get: function () {
  30062. if (!this._audioContextInitialized) {
  30063. this._initializeAudioContext();
  30064. }
  30065. return this._audioContext;
  30066. },
  30067. enumerable: true,
  30068. configurable: true
  30069. });
  30070. AudioEngine.prototype._initializeAudioContext = function () {
  30071. try {
  30072. if (this.canUseWebAudio) {
  30073. this._audioContext = new AudioContext();
  30074. // create a global volume gain node
  30075. this.masterGain = this._audioContext.createGain();
  30076. this.masterGain.gain.value = 1;
  30077. this.masterGain.connect(this._audioContext.destination);
  30078. this._audioContextInitialized = true;
  30079. }
  30080. }
  30081. catch (e) {
  30082. this.canUseWebAudio = false;
  30083. BABYLON.Tools.Error("Web Audio: " + e.message);
  30084. }
  30085. };
  30086. AudioEngine.prototype.dispose = function () {
  30087. if (this.canUseWebAudio && this._audioContextInitialized) {
  30088. if (this._connectedAnalyser) {
  30089. this._connectedAnalyser.stopDebugCanvas();
  30090. this._connectedAnalyser.dispose();
  30091. this.masterGain.disconnect();
  30092. this.masterGain.connect(this._audioContext.destination);
  30093. this._connectedAnalyser = null;
  30094. }
  30095. this.masterGain.gain.value = 1;
  30096. }
  30097. this.WarnedWebAudioUnsupported = false;
  30098. };
  30099. AudioEngine.prototype.getGlobalVolume = function () {
  30100. if (this.canUseWebAudio && this._audioContextInitialized) {
  30101. return this.masterGain.gain.value;
  30102. }
  30103. else {
  30104. return -1;
  30105. }
  30106. };
  30107. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30108. if (this.canUseWebAudio && this._audioContextInitialized) {
  30109. this.masterGain.gain.value = newVolume;
  30110. }
  30111. };
  30112. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30113. if (this._connectedAnalyser) {
  30114. this._connectedAnalyser.stopDebugCanvas();
  30115. }
  30116. if (this.canUseWebAudio && this._audioContextInitialized) {
  30117. this._connectedAnalyser = analyser;
  30118. this.masterGain.disconnect();
  30119. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30120. }
  30121. };
  30122. return AudioEngine;
  30123. })();
  30124. BABYLON.AudioEngine = AudioEngine;
  30125. })(BABYLON || (BABYLON = {}));
  30126. var BABYLON;
  30127. (function (BABYLON) {
  30128. var Sound = (function () {
  30129. /**
  30130. * Create a sound and attach it to a scene
  30131. * @param name Name of your sound
  30132. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30133. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30134. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30135. */
  30136. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30137. var _this = this;
  30138. this.autoplay = false;
  30139. this.loop = false;
  30140. this.useCustomAttenuation = false;
  30141. this.spatialSound = false;
  30142. this.refDistance = 1;
  30143. this.rolloffFactor = 1;
  30144. this.maxDistance = 100;
  30145. this.distanceModel = "linear";
  30146. this._panningModel = "equalpower";
  30147. this._playbackRate = 1;
  30148. this._startTime = 0;
  30149. this._startOffset = 0;
  30150. this._position = BABYLON.Vector3.Zero();
  30151. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30152. this._volume = 1;
  30153. this._isLoaded = false;
  30154. this._isReadyToPlay = false;
  30155. this.isPlaying = false;
  30156. this.isPaused = false;
  30157. this._isDirectional = false;
  30158. // Used if you'd like to create a directional sound.
  30159. // If not set, the sound will be omnidirectional
  30160. this._coneInnerAngle = 360;
  30161. this._coneOuterAngle = 360;
  30162. this._coneOuterGain = 0;
  30163. this._isOutputConnected = false;
  30164. this.name = name;
  30165. this._scene = scene;
  30166. this._readyToPlayCallback = readyToPlayCallback;
  30167. // Default custom attenuation function is a linear attenuation
  30168. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30169. if (currentDistance < maxDistance) {
  30170. return currentVolume * (1 - currentDistance / maxDistance);
  30171. }
  30172. else {
  30173. return 0;
  30174. }
  30175. };
  30176. if (options) {
  30177. this.autoplay = options.autoplay || false;
  30178. this.loop = options.loop || false;
  30179. // if volume === 0, we need another way to check this option
  30180. if (options.volume !== undefined) {
  30181. this._volume = options.volume;
  30182. }
  30183. this.spatialSound = options.spatialSound || false;
  30184. this.maxDistance = options.maxDistance || 100;
  30185. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30186. this.rolloffFactor = options.rolloffFactor || 1;
  30187. this.refDistance = options.refDistance || 1;
  30188. this.distanceModel = options.distanceModel || "linear";
  30189. this._playbackRate = options.playbackRate || 1;
  30190. }
  30191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30192. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30193. this._soundGain.gain.value = this._volume;
  30194. this._inputAudioNode = this._soundGain;
  30195. this._ouputAudioNode = this._soundGain;
  30196. if (this.spatialSound) {
  30197. this._createSpatialParameters();
  30198. }
  30199. this._scene.mainSoundTrack.AddSound(this);
  30200. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30201. if (urlOrArrayBuffer) {
  30202. // If it's an URL
  30203. if (typeof (urlOrArrayBuffer) === "string") {
  30204. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30205. }
  30206. else {
  30207. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30208. this._soundLoaded(urlOrArrayBuffer);
  30209. }
  30210. else {
  30211. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30212. }
  30213. }
  30214. }
  30215. }
  30216. else {
  30217. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30218. this._scene.mainSoundTrack.AddSound(this);
  30219. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30220. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30221. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30222. }
  30223. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30224. if (this._readyToPlayCallback) {
  30225. window.setTimeout(function () {
  30226. _this._readyToPlayCallback();
  30227. }, 1000);
  30228. }
  30229. }
  30230. }
  30231. Sound.prototype.dispose = function () {
  30232. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30233. if (this.isPlaying) {
  30234. this.stop();
  30235. }
  30236. this._isReadyToPlay = false;
  30237. if (this.soundTrackId === -1) {
  30238. this._scene.mainSoundTrack.RemoveSound(this);
  30239. }
  30240. else {
  30241. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30242. }
  30243. if (this._soundGain) {
  30244. this._soundGain.disconnect();
  30245. this._soundGain = null;
  30246. }
  30247. if (this._soundPanner) {
  30248. this._soundPanner.disconnect();
  30249. this._soundPanner = null;
  30250. }
  30251. if (this._soundSource) {
  30252. this._soundSource.disconnect();
  30253. this._soundSource = null;
  30254. }
  30255. this._audioBuffer = null;
  30256. if (this._connectedMesh) {
  30257. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30258. this._connectedMesh = null;
  30259. }
  30260. }
  30261. };
  30262. Sound.prototype._soundLoaded = function (audioData) {
  30263. var _this = this;
  30264. this._isLoaded = true;
  30265. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30266. _this._audioBuffer = buffer;
  30267. _this._isReadyToPlay = true;
  30268. if (_this.autoplay) {
  30269. _this.play();
  30270. }
  30271. if (_this._readyToPlayCallback) {
  30272. _this._readyToPlayCallback();
  30273. }
  30274. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30275. };
  30276. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30278. this._audioBuffer = audioBuffer;
  30279. this._isReadyToPlay = true;
  30280. }
  30281. };
  30282. Sound.prototype.updateOptions = function (options) {
  30283. if (options) {
  30284. this.loop = options.loop || this.loop;
  30285. this.maxDistance = options.maxDistance || this.maxDistance;
  30286. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30287. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30288. this.refDistance = options.refDistance || this.refDistance;
  30289. this.distanceModel = options.distanceModel || this.distanceModel;
  30290. this._playbackRate = options.playbackRate || this._playbackRate;
  30291. this._updateSpatialParameters();
  30292. if (this.isPlaying) {
  30293. this._soundSource.playbackRate.value = this._playbackRate;
  30294. }
  30295. }
  30296. };
  30297. Sound.prototype._createSpatialParameters = function () {
  30298. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30299. if (this._scene.headphone) {
  30300. this._panningModel = "HRTF";
  30301. }
  30302. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30303. this._updateSpatialParameters();
  30304. this._soundPanner.connect(this._ouputAudioNode);
  30305. this._inputAudioNode = this._soundPanner;
  30306. }
  30307. };
  30308. Sound.prototype._updateSpatialParameters = function () {
  30309. if (this.spatialSound) {
  30310. if (this.useCustomAttenuation) {
  30311. // Tricks to disable in a way embedded Web Audio attenuation
  30312. this._soundPanner.distanceModel = "linear";
  30313. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30314. this._soundPanner.refDistance = 1;
  30315. this._soundPanner.rolloffFactor = 1;
  30316. this._soundPanner.panningModel = this._panningModel;
  30317. }
  30318. else {
  30319. this._soundPanner.distanceModel = this.distanceModel;
  30320. this._soundPanner.maxDistance = this.maxDistance;
  30321. this._soundPanner.refDistance = this.refDistance;
  30322. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30323. this._soundPanner.panningModel = this._panningModel;
  30324. }
  30325. }
  30326. };
  30327. Sound.prototype.switchPanningModelToHRTF = function () {
  30328. this._panningModel = "HRTF";
  30329. this._switchPanningModel();
  30330. };
  30331. Sound.prototype.switchPanningModelToEqualPower = function () {
  30332. this._panningModel = "equalpower";
  30333. this._switchPanningModel();
  30334. };
  30335. Sound.prototype._switchPanningModel = function () {
  30336. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30337. this._soundPanner.panningModel = this._panningModel;
  30338. }
  30339. };
  30340. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30341. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30342. if (this._isOutputConnected) {
  30343. this._ouputAudioNode.disconnect();
  30344. }
  30345. this._ouputAudioNode.connect(soundTrackAudioNode);
  30346. this._isOutputConnected = true;
  30347. }
  30348. };
  30349. /**
  30350. * Transform this sound into a directional source
  30351. * @param coneInnerAngle Size of the inner cone in degree
  30352. * @param coneOuterAngle Size of the outer cone in degree
  30353. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30354. */
  30355. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30356. if (coneOuterAngle < coneInnerAngle) {
  30357. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30358. return;
  30359. }
  30360. this._coneInnerAngle = coneInnerAngle;
  30361. this._coneOuterAngle = coneOuterAngle;
  30362. this._coneOuterGain = coneOuterGain;
  30363. this._isDirectional = true;
  30364. if (this.isPlaying && this.loop) {
  30365. this.stop();
  30366. this.play();
  30367. }
  30368. };
  30369. Sound.prototype.setPosition = function (newPosition) {
  30370. this._position = newPosition;
  30371. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30372. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30373. }
  30374. };
  30375. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30376. this._localDirection = newLocalDirection;
  30377. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30378. this._updateDirection();
  30379. }
  30380. };
  30381. Sound.prototype._updateDirection = function () {
  30382. var mat = this._connectedMesh.getWorldMatrix();
  30383. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30384. direction.normalize();
  30385. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30386. };
  30387. Sound.prototype.updateDistanceFromListener = function () {
  30388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30389. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30390. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30391. }
  30392. };
  30393. Sound.prototype.setAttenuationFunction = function (callback) {
  30394. this._customAttenuationFunction = callback;
  30395. };
  30396. /**
  30397. * Play the sound
  30398. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30399. */
  30400. Sound.prototype.play = function (time) {
  30401. var _this = this;
  30402. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30403. try {
  30404. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30405. if (!this._soundSource) {
  30406. if (this.spatialSound) {
  30407. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30408. if (this._isDirectional) {
  30409. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30410. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30411. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30412. if (this._connectedMesh) {
  30413. this._updateDirection();
  30414. }
  30415. else {
  30416. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30417. }
  30418. }
  30419. }
  30420. }
  30421. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30422. this._soundSource.buffer = this._audioBuffer;
  30423. this._soundSource.connect(this._inputAudioNode);
  30424. this._soundSource.loop = this.loop;
  30425. this._soundSource.playbackRate.value = this._playbackRate;
  30426. this._startTime = startTime;
  30427. this._soundSource.onended = function () { _this._onended(); };
  30428. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30429. this.isPlaying = true;
  30430. this.isPaused = false;
  30431. }
  30432. catch (ex) {
  30433. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30434. }
  30435. }
  30436. };
  30437. Sound.prototype._onended = function () {
  30438. this.isPlaying = false;
  30439. if (this.onended) {
  30440. this.onended();
  30441. }
  30442. };
  30443. /**
  30444. * Stop the sound
  30445. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30446. */
  30447. Sound.prototype.stop = function (time) {
  30448. if (this.isPlaying) {
  30449. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30450. this._soundSource.stop(stopTime);
  30451. this.isPlaying = false;
  30452. }
  30453. };
  30454. Sound.prototype.pause = function () {
  30455. if (this.isPlaying) {
  30456. this.stop(0);
  30457. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30458. this.isPaused = true;
  30459. }
  30460. };
  30461. Sound.prototype.setVolume = function (newVolume, time) {
  30462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30463. if (time) {
  30464. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30465. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30466. }
  30467. else {
  30468. this._soundGain.gain.value = newVolume;
  30469. }
  30470. }
  30471. this._volume = newVolume;
  30472. };
  30473. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30474. this._playbackRate = newPlaybackRate;
  30475. if (this.isPlaying) {
  30476. this._soundSource.playbackRate.value = this._playbackRate;
  30477. }
  30478. };
  30479. Sound.prototype.getVolume = function () {
  30480. return this._volume;
  30481. };
  30482. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30483. var _this = this;
  30484. this._connectedMesh = meshToConnectTo;
  30485. if (!this.spatialSound) {
  30486. this.spatialSound = true;
  30487. this._createSpatialParameters();
  30488. if (this.isPlaying && this.loop) {
  30489. this.stop();
  30490. this.play();
  30491. }
  30492. }
  30493. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30494. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30495. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30496. };
  30497. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30498. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30500. this._updateDirection();
  30501. }
  30502. };
  30503. return Sound;
  30504. })();
  30505. BABYLON.Sound = Sound;
  30506. })(BABYLON || (BABYLON = {}));
  30507. var BABYLON;
  30508. (function (BABYLON) {
  30509. var SoundTrack = (function () {
  30510. function SoundTrack(scene, options) {
  30511. this.id = -1;
  30512. this._isMainTrack = false;
  30513. this._scene = scene;
  30514. this._audioEngine = BABYLON.Engine.audioEngine;
  30515. this.soundCollection = new Array();
  30516. if (this._audioEngine.canUseWebAudio) {
  30517. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30518. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30519. if (options) {
  30520. if (options.volume) {
  30521. this._outputAudioNode.gain.value = options.volume;
  30522. }
  30523. if (options.mainTrack) {
  30524. this._isMainTrack = options.mainTrack;
  30525. }
  30526. }
  30527. }
  30528. if (!this._isMainTrack) {
  30529. this._scene.soundTracks.push(this);
  30530. this.id = this._scene.soundTracks.length - 1;
  30531. }
  30532. }
  30533. SoundTrack.prototype.dispose = function () {
  30534. if (this._audioEngine.canUseWebAudio) {
  30535. if (this._connectedAnalyser) {
  30536. this._connectedAnalyser.stopDebugCanvas();
  30537. }
  30538. while (this.soundCollection.length) {
  30539. this.soundCollection[0].dispose();
  30540. }
  30541. if (this._outputAudioNode) {
  30542. this._outputAudioNode.disconnect();
  30543. }
  30544. this._outputAudioNode = null;
  30545. }
  30546. };
  30547. SoundTrack.prototype.AddSound = function (sound) {
  30548. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30549. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30550. }
  30551. if (sound.soundTrackId) {
  30552. if (sound.soundTrackId === -1) {
  30553. this._scene.mainSoundTrack.RemoveSound(sound);
  30554. }
  30555. else {
  30556. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30557. }
  30558. }
  30559. this.soundCollection.push(sound);
  30560. sound.soundTrackId = this.id;
  30561. };
  30562. SoundTrack.prototype.RemoveSound = function (sound) {
  30563. var index = this.soundCollection.indexOf(sound);
  30564. if (index !== -1) {
  30565. this.soundCollection.splice(index, 1);
  30566. }
  30567. };
  30568. SoundTrack.prototype.setVolume = function (newVolume) {
  30569. if (this._audioEngine.canUseWebAudio) {
  30570. this._outputAudioNode.gain.value = newVolume;
  30571. }
  30572. };
  30573. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30574. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30575. for (var i = 0; i < this.soundCollection.length; i++) {
  30576. this.soundCollection[i].switchPanningModelToHRTF();
  30577. }
  30578. }
  30579. };
  30580. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30581. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30582. for (var i = 0; i < this.soundCollection.length; i++) {
  30583. this.soundCollection[i].switchPanningModelToEqualPower();
  30584. }
  30585. }
  30586. };
  30587. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30588. if (this._connectedAnalyser) {
  30589. this._connectedAnalyser.stopDebugCanvas();
  30590. }
  30591. this._connectedAnalyser = analyser;
  30592. if (this._audioEngine.canUseWebAudio) {
  30593. this._outputAudioNode.disconnect();
  30594. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30595. }
  30596. };
  30597. return SoundTrack;
  30598. })();
  30599. BABYLON.SoundTrack = SoundTrack;
  30600. })(BABYLON || (BABYLON = {}));
  30601. var BABYLON;
  30602. (function (BABYLON) {
  30603. var DebugLayer = (function () {
  30604. function DebugLayer(scene) {
  30605. var _this = this;
  30606. this._transformationMatrix = BABYLON.Matrix.Identity();
  30607. this._enabled = false;
  30608. this._labelsEnabled = false;
  30609. this._displayStatistics = true;
  30610. this._displayTree = false;
  30611. this._displayLogs = false;
  30612. this._identityMatrix = BABYLON.Matrix.Identity();
  30613. this.axisRatio = 0.02;
  30614. this.accentColor = "orange";
  30615. this._scene = scene;
  30616. this._syncPositions = function () {
  30617. var engine = _this._scene.getEngine();
  30618. var canvasRect = engine.getRenderingCanvasClientRect();
  30619. if (_this._showUI) {
  30620. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30621. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30622. _this._statsDiv.style.width = "400px";
  30623. _this._statsDiv.style.height = "auto";
  30624. _this._statsSubsetDiv.style.maxHeight = "240px";
  30625. _this._optionsDiv.style.left = "0px";
  30626. _this._optionsDiv.style.top = "10px";
  30627. _this._optionsDiv.style.width = "200px";
  30628. _this._optionsDiv.style.height = "auto";
  30629. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30630. _this._logDiv.style.left = "0px";
  30631. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30632. _this._logDiv.style.width = "600px";
  30633. _this._logDiv.style.height = "160px";
  30634. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30635. _this._treeDiv.style.top = "10px";
  30636. _this._treeDiv.style.width = "300px";
  30637. _this._treeDiv.style.height = "auto";
  30638. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30639. }
  30640. _this._globalDiv.style.left = canvasRect.left + "px";
  30641. _this._globalDiv.style.top = canvasRect.top + "px";
  30642. _this._drawingCanvas.style.left = "0px";
  30643. _this._drawingCanvas.style.top = "0px";
  30644. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30645. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30646. var devicePixelRatio = window.devicePixelRatio || 1;
  30647. var context = _this._drawingContext;
  30648. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30649. context.mozBackingStorePixelRatio ||
  30650. context.msBackingStorePixelRatio ||
  30651. context.oBackingStorePixelRatio ||
  30652. context.backingStorePixelRatio || 1;
  30653. _this._ratio = devicePixelRatio / backingStoreRatio;
  30654. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30655. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30656. };
  30657. this._onCanvasClick = function (evt) {
  30658. _this._clickPosition = {
  30659. x: evt.clientX * _this._ratio,
  30660. y: evt.clientY * _this._ratio
  30661. };
  30662. };
  30663. this._syncUI = function () {
  30664. if (_this._showUI) {
  30665. if (_this._displayStatistics) {
  30666. _this._displayStats();
  30667. _this._statsDiv.style.display = "";
  30668. }
  30669. else {
  30670. _this._statsDiv.style.display = "none";
  30671. }
  30672. if (_this._displayLogs) {
  30673. _this._logDiv.style.display = "";
  30674. }
  30675. else {
  30676. _this._logDiv.style.display = "none";
  30677. }
  30678. if (_this._displayTree) {
  30679. _this._treeDiv.style.display = "";
  30680. if (_this._needToRefreshMeshesTree) {
  30681. _this._needToRefreshMeshesTree = false;
  30682. _this._refreshMeshesTreeContent();
  30683. }
  30684. }
  30685. else {
  30686. _this._treeDiv.style.display = "none";
  30687. }
  30688. }
  30689. };
  30690. this._syncData = function () {
  30691. if (_this._labelsEnabled || !_this._showUI) {
  30692. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30693. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30694. var engine = _this._scene.getEngine();
  30695. var viewport = _this._camera.viewport;
  30696. var globalViewport = viewport.toGlobal(engine);
  30697. // Meshes
  30698. var meshes = _this._camera.getActiveMeshes();
  30699. for (var index = 0; index < meshes.length; index++) {
  30700. var mesh = meshes.data[index];
  30701. var position = mesh.getBoundingInfo().boundingSphere.center;
  30702. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30703. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30704. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30705. }
  30706. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30707. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30708. }
  30709. }
  30710. // Cameras
  30711. var cameras = _this._scene.cameras;
  30712. for (index = 0; index < cameras.length; index++) {
  30713. var camera = cameras[index];
  30714. if (camera === _this._camera) {
  30715. continue;
  30716. }
  30717. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30718. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30719. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30720. _this._camera.detachControl(engine.getRenderingCanvas());
  30721. _this._camera = camera;
  30722. _this._camera.attachControl(engine.getRenderingCanvas());
  30723. }, function () { return "purple"; });
  30724. }
  30725. }
  30726. // Lights
  30727. var lights = _this._scene.lights;
  30728. for (index = 0; index < lights.length; index++) {
  30729. var light = lights[index];
  30730. if (light.position) {
  30731. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30732. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30733. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30734. light.setEnabled(!light.isEnabled());
  30735. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30736. }
  30737. }
  30738. }
  30739. }
  30740. _this._clickPosition = undefined;
  30741. };
  30742. }
  30743. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30744. while (this._treeSubsetDiv.hasChildNodes()) {
  30745. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30746. }
  30747. // Add meshes
  30748. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30749. sortedArray.sort(function (a, b) {
  30750. if (a.name === b.name) {
  30751. return 0;
  30752. }
  30753. return (a.name > b.name) ? 1 : -1;
  30754. });
  30755. for (var index = 0; index < sortedArray.length; index++) {
  30756. var mesh = sortedArray[index];
  30757. if (!mesh.isEnabled()) {
  30758. continue;
  30759. }
  30760. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30761. m.isVisible = element.checked;
  30762. }, mesh);
  30763. }
  30764. };
  30765. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30766. this._drawingContext.beginPath();
  30767. this._drawingContext.moveTo(zero.x, zero.y);
  30768. this._drawingContext.lineTo(unit.x, unit.y);
  30769. this._drawingContext.strokeStyle = color;
  30770. this._drawingContext.lineWidth = 4;
  30771. this._drawingContext.stroke();
  30772. this._drawingContext.font = "normal 14px Segoe UI";
  30773. this._drawingContext.fillStyle = color;
  30774. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30775. };
  30776. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30777. var position = mesh.getBoundingInfo().boundingSphere.center;
  30778. var worldMatrix = mesh.getWorldMatrix();
  30779. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30780. var unit = (unprojectedVector.subtract(position)).length();
  30781. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30782. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30783. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30784. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30785. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30786. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30787. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30788. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30789. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30790. };
  30791. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30792. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30793. this._drawingContext.font = "normal 12px Segoe UI";
  30794. var textMetrics = this._drawingContext.measureText(text);
  30795. var centerX = projectedPosition.x - textMetrics.width / 2;
  30796. var centerY = projectedPosition.y;
  30797. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30798. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30799. onClick();
  30800. }
  30801. this._drawingContext.beginPath();
  30802. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30803. this._drawingContext.fillStyle = getFillStyle();
  30804. this._drawingContext.globalAlpha = 0.5;
  30805. this._drawingContext.fill();
  30806. this._drawingContext.globalAlpha = 1.0;
  30807. this._drawingContext.strokeStyle = '#FFFFFF';
  30808. this._drawingContext.lineWidth = 1;
  30809. this._drawingContext.stroke();
  30810. this._drawingContext.fillStyle = "#FFFFFF";
  30811. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30812. this._drawingContext.beginPath();
  30813. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30814. this._drawingContext.fill();
  30815. }
  30816. };
  30817. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30818. if (!this._clickPosition) {
  30819. return false;
  30820. }
  30821. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30822. return false;
  30823. }
  30824. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30825. return false;
  30826. }
  30827. return true;
  30828. };
  30829. DebugLayer.prototype.isVisible = function () {
  30830. return this._enabled;
  30831. };
  30832. DebugLayer.prototype.hide = function () {
  30833. if (!this._enabled) {
  30834. return;
  30835. }
  30836. this._enabled = false;
  30837. var engine = this._scene.getEngine();
  30838. this._scene.unregisterBeforeRender(this._syncData);
  30839. this._scene.unregisterAfterRender(this._syncUI);
  30840. document.body.removeChild(this._globalDiv);
  30841. window.removeEventListener("resize", this._syncPositions);
  30842. this._scene.forceShowBoundingBoxes = false;
  30843. this._scene.forceWireframe = false;
  30844. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30845. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30846. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30847. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30848. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30849. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30850. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30851. this._scene.shadowsEnabled = true;
  30852. this._scene.particlesEnabled = true;
  30853. this._scene.postProcessesEnabled = true;
  30854. this._scene.collisionsEnabled = true;
  30855. this._scene.lightsEnabled = true;
  30856. this._scene.texturesEnabled = true;
  30857. this._scene.lensFlaresEnabled = true;
  30858. this._scene.proceduralTexturesEnabled = true;
  30859. this._scene.renderTargetsEnabled = true;
  30860. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30861. };
  30862. DebugLayer.prototype.show = function (showUI, camera) {
  30863. if (showUI === void 0) { showUI = true; }
  30864. if (camera === void 0) { camera = null; }
  30865. if (this._enabled) {
  30866. return;
  30867. }
  30868. this._enabled = true;
  30869. if (camera) {
  30870. this._camera = camera;
  30871. }
  30872. else {
  30873. this._camera = this._scene.activeCamera;
  30874. }
  30875. this._showUI = showUI;
  30876. var engine = this._scene.getEngine();
  30877. this._globalDiv = document.createElement("div");
  30878. document.body.appendChild(this._globalDiv);
  30879. this._generateDOMelements();
  30880. window.addEventListener("resize", this._syncPositions);
  30881. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30882. this._syncPositions();
  30883. this._scene.registerBeforeRender(this._syncData);
  30884. this._scene.registerAfterRender(this._syncUI);
  30885. };
  30886. DebugLayer.prototype._clearLabels = function () {
  30887. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30888. for (var index = 0; index < this._scene.meshes.length; index++) {
  30889. var mesh = this._scene.meshes[index];
  30890. mesh.renderOverlay = false;
  30891. }
  30892. };
  30893. DebugLayer.prototype._generateheader = function (root, text) {
  30894. var header = document.createElement("div");
  30895. header.innerHTML = text + "&nbsp;";
  30896. header.style.textAlign = "right";
  30897. header.style.width = "100%";
  30898. header.style.color = "white";
  30899. header.style.backgroundColor = "Black";
  30900. header.style.padding = "5px 5px 4px 0px";
  30901. header.style.marginLeft = "-5px";
  30902. header.style.fontWeight = "bold";
  30903. root.appendChild(header);
  30904. };
  30905. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30906. var label = document.createElement("label");
  30907. label.innerHTML = title;
  30908. label.style.color = color;
  30909. root.appendChild(label);
  30910. root.appendChild(document.createElement("br"));
  30911. };
  30912. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30913. if (tag === void 0) { tag = null; }
  30914. var label = document.createElement("label");
  30915. var boundingBoxesCheckbox = document.createElement("input");
  30916. boundingBoxesCheckbox.type = "checkbox";
  30917. boundingBoxesCheckbox.checked = initialState;
  30918. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30919. task(evt.target, tag);
  30920. });
  30921. label.appendChild(boundingBoxesCheckbox);
  30922. var container = document.createElement("span");
  30923. var leftPart = document.createElement("span");
  30924. var rightPart = document.createElement("span");
  30925. rightPart.style.cssFloat = "right";
  30926. leftPart.innerHTML = leftTitle;
  30927. rightPart.innerHTML = rightTitle;
  30928. rightPart.style.fontSize = "12px";
  30929. rightPart.style.maxWidth = "200px";
  30930. container.appendChild(leftPart);
  30931. container.appendChild(rightPart);
  30932. label.appendChild(container);
  30933. root.appendChild(label);
  30934. root.appendChild(document.createElement("br"));
  30935. };
  30936. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30937. if (tag === void 0) { tag = null; }
  30938. var label = document.createElement("label");
  30939. var checkBox = document.createElement("input");
  30940. checkBox.type = "checkbox";
  30941. checkBox.checked = initialState;
  30942. checkBox.addEventListener("change", function (evt) {
  30943. task(evt.target, tag);
  30944. });
  30945. label.appendChild(checkBox);
  30946. label.appendChild(document.createTextNode(title));
  30947. root.appendChild(label);
  30948. root.appendChild(document.createElement("br"));
  30949. };
  30950. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30951. if (tag === void 0) { tag = null; }
  30952. var button = document.createElement("button");
  30953. button.innerHTML = title;
  30954. button.style.height = "24px";
  30955. button.style.color = "#444444";
  30956. button.style.border = "1px solid white";
  30957. button.className = "debugLayerButton";
  30958. button.addEventListener("click", function (evt) {
  30959. task(evt.target, tag);
  30960. });
  30961. root.appendChild(button);
  30962. root.appendChild(document.createElement("br"));
  30963. };
  30964. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30965. if (tag === void 0) { tag = null; }
  30966. var label = document.createElement("label");
  30967. var boundingBoxesRadio = document.createElement("input");
  30968. boundingBoxesRadio.type = "radio";
  30969. boundingBoxesRadio.name = name;
  30970. boundingBoxesRadio.checked = initialState;
  30971. boundingBoxesRadio.addEventListener("change", function (evt) {
  30972. task(evt.target, tag);
  30973. });
  30974. label.appendChild(boundingBoxesRadio);
  30975. label.appendChild(document.createTextNode(title));
  30976. root.appendChild(label);
  30977. root.appendChild(document.createElement("br"));
  30978. };
  30979. DebugLayer.prototype._generateDOMelements = function () {
  30980. var _this = this;
  30981. this._globalDiv.id = "DebugLayer";
  30982. this._globalDiv.style.position = "absolute";
  30983. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30984. this._globalDiv.style.fontSize = "14px";
  30985. this._globalDiv.style.color = "white";
  30986. // Drawing canvas
  30987. this._drawingCanvas = document.createElement("canvas");
  30988. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30989. this._drawingCanvas.style.position = "absolute";
  30990. this._drawingCanvas.style.pointerEvents = "none";
  30991. this._drawingContext = this._drawingCanvas.getContext("2d");
  30992. this._globalDiv.appendChild(this._drawingCanvas);
  30993. if (this._showUI) {
  30994. var background = "rgba(128, 128, 128, 0.4)";
  30995. var border = "rgb(180, 180, 180) solid 1px";
  30996. // Stats
  30997. this._statsDiv = document.createElement("div");
  30998. this._statsDiv.id = "DebugLayerStats";
  30999. this._statsDiv.style.border = border;
  31000. this._statsDiv.style.position = "absolute";
  31001. this._statsDiv.style.background = background;
  31002. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31003. this._generateheader(this._statsDiv, "STATISTICS");
  31004. this._statsSubsetDiv = document.createElement("div");
  31005. this._statsSubsetDiv.style.paddingTop = "5px";
  31006. this._statsSubsetDiv.style.paddingBottom = "5px";
  31007. this._statsSubsetDiv.style.overflowY = "auto";
  31008. this._statsDiv.appendChild(this._statsSubsetDiv);
  31009. // Tree
  31010. this._treeDiv = document.createElement("div");
  31011. this._treeDiv.id = "DebugLayerTree";
  31012. this._treeDiv.style.border = border;
  31013. this._treeDiv.style.position = "absolute";
  31014. this._treeDiv.style.background = background;
  31015. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31016. this._treeDiv.style.display = "none";
  31017. this._generateheader(this._treeDiv, "MESHES TREE");
  31018. this._treeSubsetDiv = document.createElement("div");
  31019. this._treeSubsetDiv.style.paddingTop = "5px";
  31020. this._treeSubsetDiv.style.paddingRight = "5px";
  31021. this._treeSubsetDiv.style.overflowY = "auto";
  31022. this._treeSubsetDiv.style.maxHeight = "300px";
  31023. this._treeDiv.appendChild(this._treeSubsetDiv);
  31024. this._needToRefreshMeshesTree = true;
  31025. // Logs
  31026. this._logDiv = document.createElement("div");
  31027. this._logDiv.style.border = border;
  31028. this._logDiv.id = "DebugLayerLogs";
  31029. this._logDiv.style.position = "absolute";
  31030. this._logDiv.style.background = background;
  31031. this._logDiv.style.padding = "0px 0px 0px 5px";
  31032. this._logDiv.style.display = "none";
  31033. this._generateheader(this._logDiv, "LOGS");
  31034. this._logSubsetDiv = document.createElement("div");
  31035. this._logSubsetDiv.style.height = "127px";
  31036. this._logSubsetDiv.style.paddingTop = "5px";
  31037. this._logSubsetDiv.style.overflowY = "auto";
  31038. this._logSubsetDiv.style.fontSize = "12px";
  31039. this._logSubsetDiv.style.fontFamily = "consolas";
  31040. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31041. this._logDiv.appendChild(this._logSubsetDiv);
  31042. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31043. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31044. };
  31045. // Options
  31046. this._optionsDiv = document.createElement("div");
  31047. this._optionsDiv.id = "DebugLayerOptions";
  31048. this._optionsDiv.style.border = border;
  31049. this._optionsDiv.style.position = "absolute";
  31050. this._optionsDiv.style.background = background;
  31051. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31052. this._optionsDiv.style.overflowY = "auto";
  31053. this._generateheader(this._optionsDiv, "OPTIONS");
  31054. this._optionsSubsetDiv = document.createElement("div");
  31055. this._optionsSubsetDiv.style.paddingTop = "5px";
  31056. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31057. this._optionsSubsetDiv.style.overflowY = "auto";
  31058. this._optionsSubsetDiv.style.maxHeight = "200px";
  31059. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31060. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31061. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31062. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31063. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31064. _this._displayTree = element.checked;
  31065. _this._needToRefreshMeshesTree = true;
  31066. });
  31067. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31068. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31069. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31070. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31071. _this._labelsEnabled = element.checked;
  31072. if (!_this._labelsEnabled) {
  31073. _this._clearLabels();
  31074. }
  31075. });
  31076. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31077. if (element.checked) {
  31078. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31079. }
  31080. else {
  31081. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31082. }
  31083. });
  31084. ;
  31085. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31086. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31087. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31088. if (element.checked) {
  31089. _this._scene.forceWireframe = false;
  31090. _this._scene.forcePointsCloud = false;
  31091. }
  31092. });
  31093. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31094. if (element.checked) {
  31095. _this._scene.forceWireframe = true;
  31096. _this._scene.forcePointsCloud = false;
  31097. }
  31098. });
  31099. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31100. if (element.checked) {
  31101. _this._scene.forceWireframe = false;
  31102. _this._scene.forcePointsCloud = true;
  31103. }
  31104. });
  31105. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31106. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31107. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31108. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31109. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31110. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31111. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31112. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31113. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31114. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31115. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31116. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31117. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31118. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31119. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31120. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31121. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31122. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31123. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31124. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31125. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31126. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31127. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31128. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31129. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31130. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31131. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31132. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31133. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31134. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31135. if (element.checked) {
  31136. _this._scene.headphone = true;
  31137. }
  31138. });
  31139. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31140. if (element.checked) {
  31141. _this._scene.headphone = false;
  31142. }
  31143. });
  31144. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31145. _this._scene.audioEnabled = !element.checked;
  31146. });
  31147. }
  31148. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31149. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31150. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31151. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31152. this._globalDiv.appendChild(this._statsDiv);
  31153. this._globalDiv.appendChild(this._logDiv);
  31154. this._globalDiv.appendChild(this._optionsDiv);
  31155. this._globalDiv.appendChild(this._treeDiv);
  31156. }
  31157. };
  31158. DebugLayer.prototype._displayStats = function () {
  31159. var scene = this._scene;
  31160. var engine = scene.getEngine();
  31161. var glInfo = engine.getGlInfo();
  31162. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31163. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31164. + "<b>Count</b><br>"
  31165. + "Total meshes: " + scene.meshes.length + "<br>"
  31166. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31167. + "Total materials: " + scene.materials.length + "<br>"
  31168. + "Total textures: " + scene.textures.length + "<br>"
  31169. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31170. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31171. + "Active bones: " + scene.getActiveBones() + "<br>"
  31172. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31173. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31174. + "<b>Duration</b><br>"
  31175. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31176. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31177. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31178. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31179. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31180. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31181. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31182. + "</div>"
  31183. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31184. + "<b>Extensions</b><br>"
  31185. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31186. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31187. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31188. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31189. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31190. + "<b>Caps.</b><br>"
  31191. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31192. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31193. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31194. + "</div><br>"
  31195. + "<b>Info</b><br>"
  31196. + glInfo.version + "<br>"
  31197. + glInfo.renderer + "<br>";
  31198. if (this.customStatsFunction) {
  31199. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31200. }
  31201. };
  31202. return DebugLayer;
  31203. })();
  31204. BABYLON.DebugLayer = DebugLayer;
  31205. })(BABYLON || (BABYLON = {}));
  31206. var BABYLON;
  31207. (function (BABYLON) {
  31208. var RawTexture = (function (_super) {
  31209. __extends(RawTexture, _super);
  31210. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31211. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31212. if (invertY === void 0) { invertY = false; }
  31213. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31214. _super.call(this, null, scene, !generateMipMaps, invertY);
  31215. this.format = format;
  31216. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31217. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31218. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31219. }
  31220. RawTexture.prototype.update = function (data) {
  31221. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31222. };
  31223. // Statics
  31224. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31225. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31226. if (invertY === void 0) { invertY = false; }
  31227. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31228. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31229. };
  31230. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31231. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31232. if (invertY === void 0) { invertY = false; }
  31233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31234. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31235. };
  31236. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31238. if (invertY === void 0) { invertY = false; }
  31239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31240. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31241. };
  31242. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31244. if (invertY === void 0) { invertY = false; }
  31245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31247. };
  31248. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31250. if (invertY === void 0) { invertY = false; }
  31251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31253. };
  31254. return RawTexture;
  31255. })(BABYLON.Texture);
  31256. BABYLON.RawTexture = RawTexture;
  31257. })(BABYLON || (BABYLON = {}));
  31258. var BABYLON;
  31259. (function (BABYLON) {
  31260. var IndexedVector2 = (function (_super) {
  31261. __extends(IndexedVector2, _super);
  31262. function IndexedVector2(original, index) {
  31263. _super.call(this, original.x, original.y);
  31264. this.index = index;
  31265. }
  31266. return IndexedVector2;
  31267. })(BABYLON.Vector2);
  31268. var PolygonPoints = (function () {
  31269. function PolygonPoints() {
  31270. this.elements = new Array();
  31271. }
  31272. PolygonPoints.prototype.add = function (originalPoints) {
  31273. var _this = this;
  31274. var result = new Array();
  31275. originalPoints.forEach(function (point) {
  31276. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31277. var newPoint = new IndexedVector2(point, _this.elements.length);
  31278. result.push(newPoint);
  31279. _this.elements.push(newPoint);
  31280. }
  31281. });
  31282. return result;
  31283. };
  31284. PolygonPoints.prototype.computeBounds = function () {
  31285. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31286. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31287. this.elements.forEach(function (point) {
  31288. // x
  31289. if (point.x < lmin.x) {
  31290. lmin.x = point.x;
  31291. }
  31292. else if (point.x > lmax.x) {
  31293. lmax.x = point.x;
  31294. }
  31295. // y
  31296. if (point.y < lmin.y) {
  31297. lmin.y = point.y;
  31298. }
  31299. else if (point.y > lmax.y) {
  31300. lmax.y = point.y;
  31301. }
  31302. });
  31303. return {
  31304. min: lmin,
  31305. max: lmax,
  31306. width: lmax.x - lmin.x,
  31307. height: lmax.y - lmin.y
  31308. };
  31309. };
  31310. return PolygonPoints;
  31311. })();
  31312. var Polygon = (function () {
  31313. function Polygon() {
  31314. }
  31315. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31316. return [
  31317. new BABYLON.Vector2(xmin, ymin),
  31318. new BABYLON.Vector2(xmax, ymin),
  31319. new BABYLON.Vector2(xmax, ymax),
  31320. new BABYLON.Vector2(xmin, ymax)
  31321. ];
  31322. };
  31323. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31324. if (cx === void 0) { cx = 0; }
  31325. if (cy === void 0) { cy = 0; }
  31326. if (numberOfSides === void 0) { numberOfSides = 32; }
  31327. var result = new Array();
  31328. var angle = 0;
  31329. var increment = (Math.PI * 2) / numberOfSides;
  31330. for (var i = 0; i < numberOfSides; i++) {
  31331. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31332. angle -= increment;
  31333. }
  31334. return result;
  31335. };
  31336. Polygon.Parse = function (input) {
  31337. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31338. var i, result = [];
  31339. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31340. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31341. }
  31342. return result;
  31343. };
  31344. Polygon.StartingAt = function (x, y) {
  31345. return BABYLON.Path2.StartingAt(x, y);
  31346. };
  31347. return Polygon;
  31348. })();
  31349. BABYLON.Polygon = Polygon;
  31350. var PolygonMeshBuilder = (function () {
  31351. function PolygonMeshBuilder(name, contours, scene) {
  31352. this._points = new PolygonPoints();
  31353. this._outlinepoints = new PolygonPoints();
  31354. this._holes = [];
  31355. if (!("poly2tri" in window)) {
  31356. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31357. }
  31358. this._name = name;
  31359. this._scene = scene;
  31360. var points;
  31361. if (contours instanceof BABYLON.Path2) {
  31362. points = contours.getPoints();
  31363. }
  31364. else {
  31365. points = contours;
  31366. }
  31367. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31368. this._outlinepoints.add(points);
  31369. }
  31370. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31371. this._swctx.addHole(this._points.add(hole));
  31372. var holepoints = new PolygonPoints();
  31373. holepoints.add(hole);
  31374. this._holes.push(holepoints);
  31375. return this;
  31376. };
  31377. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31378. var _this = this;
  31379. if (updatable === void 0) { updatable = false; }
  31380. var result = new BABYLON.Mesh(this._name, this._scene);
  31381. var normals = [];
  31382. var positions = [];
  31383. var uvs = [];
  31384. var bounds = this._points.computeBounds();
  31385. this._points.elements.forEach(function (p) {
  31386. normals.push(0, 1.0, 0);
  31387. positions.push(p.x, 0, p.y);
  31388. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31389. });
  31390. var indices = [];
  31391. this._swctx.triangulate();
  31392. this._swctx.getTriangles().forEach(function (triangle) {
  31393. triangle.getPoints().forEach(function (point) {
  31394. indices.push(point.index);
  31395. });
  31396. });
  31397. if (depth > 0) {
  31398. var positionscount = (positions.length / 3); //get the current pointcount
  31399. this._points.elements.forEach(function (p) {
  31400. normals.push(0, -1.0, 0);
  31401. positions.push(p.x, -depth, p.y);
  31402. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31403. });
  31404. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31405. var p2;
  31406. var poscounter = 0;
  31407. this._swctx.getTriangles().forEach(function (triangle) {
  31408. triangle.getPoints().forEach(function (point) {
  31409. switch (poscounter) {
  31410. case 0:
  31411. p1 = point;
  31412. break;
  31413. case 1:
  31414. p2 = point;
  31415. break;
  31416. case 2:
  31417. indices.push(point.index + positionscount);
  31418. indices.push(p2.index + positionscount);
  31419. indices.push(p1.index + positionscount);
  31420. poscounter = -1;
  31421. break;
  31422. }
  31423. poscounter++;
  31424. //indices.push((<IndexedVector2>point).index + positionscount);
  31425. });
  31426. });
  31427. //Add the sides
  31428. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31429. this._holes.forEach(function (hole) {
  31430. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31431. });
  31432. }
  31433. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31434. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31435. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31436. result.setIndices(indices);
  31437. return result;
  31438. };
  31439. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31440. var StartIndex = positions.length / 3;
  31441. var ulength = 0;
  31442. for (var i = 0; i < points.elements.length; i++) {
  31443. var p = points.elements[i];
  31444. var p1;
  31445. if ((i + 1) > points.elements.length - 1) {
  31446. p1 = points.elements[0];
  31447. }
  31448. else {
  31449. p1 = points.elements[i + 1];
  31450. }
  31451. positions.push(p.x, 0, p.y);
  31452. positions.push(p.x, -depth, p.y);
  31453. positions.push(p1.x, 0, p1.y);
  31454. positions.push(p1.x, -depth, p1.y);
  31455. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31456. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31457. var v3 = v2.subtract(v1);
  31458. var v4 = new BABYLON.Vector3(0, 1, 0);
  31459. var vn = BABYLON.Vector3.Cross(v3, v4);
  31460. vn = vn.normalize();
  31461. uvs.push(ulength / bounds.width, 0);
  31462. uvs.push(ulength / bounds.width, 1);
  31463. ulength += v3.length();
  31464. uvs.push((ulength / bounds.width), 0);
  31465. uvs.push((ulength / bounds.width), 1);
  31466. if (!flip) {
  31467. normals.push(-vn.x, -vn.y, -vn.z);
  31468. normals.push(-vn.x, -vn.y, -vn.z);
  31469. normals.push(-vn.x, -vn.y, -vn.z);
  31470. normals.push(-vn.x, -vn.y, -vn.z);
  31471. indices.push(StartIndex);
  31472. indices.push(StartIndex + 1);
  31473. indices.push(StartIndex + 2);
  31474. indices.push(StartIndex + 1);
  31475. indices.push(StartIndex + 3);
  31476. indices.push(StartIndex + 2);
  31477. }
  31478. else {
  31479. normals.push(vn.x, vn.y, vn.z);
  31480. normals.push(vn.x, vn.y, vn.z);
  31481. normals.push(vn.x, vn.y, vn.z);
  31482. normals.push(vn.x, vn.y, vn.z);
  31483. indices.push(StartIndex);
  31484. indices.push(StartIndex + 2);
  31485. indices.push(StartIndex + 1);
  31486. indices.push(StartIndex + 1);
  31487. indices.push(StartIndex + 2);
  31488. indices.push(StartIndex + 3);
  31489. }
  31490. StartIndex += 4;
  31491. }
  31492. ;
  31493. };
  31494. return PolygonMeshBuilder;
  31495. })();
  31496. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31497. })(BABYLON || (BABYLON = {}));
  31498. var BABYLON;
  31499. (function (BABYLON) {
  31500. var SimplificationSettings = (function () {
  31501. function SimplificationSettings(quality, distance, optimizeMesh) {
  31502. this.quality = quality;
  31503. this.distance = distance;
  31504. this.optimizeMesh = optimizeMesh;
  31505. }
  31506. return SimplificationSettings;
  31507. })();
  31508. BABYLON.SimplificationSettings = SimplificationSettings;
  31509. var SimplificationQueue = (function () {
  31510. function SimplificationQueue() {
  31511. this.running = false;
  31512. this._simplificationArray = [];
  31513. }
  31514. SimplificationQueue.prototype.addTask = function (task) {
  31515. this._simplificationArray.push(task);
  31516. };
  31517. SimplificationQueue.prototype.executeNext = function () {
  31518. var task = this._simplificationArray.pop();
  31519. if (task) {
  31520. this.running = true;
  31521. this.runSimplification(task);
  31522. }
  31523. else {
  31524. this.running = false;
  31525. }
  31526. };
  31527. SimplificationQueue.prototype.runSimplification = function (task) {
  31528. var _this = this;
  31529. if (task.parallelProcessing) {
  31530. //parallel simplifier
  31531. task.settings.forEach(function (setting) {
  31532. var simplifier = _this.getSimplifier(task);
  31533. simplifier.simplify(setting, function (newMesh) {
  31534. task.mesh.addLODLevel(setting.distance, newMesh);
  31535. newMesh.isVisible = true;
  31536. //check if it is the last
  31537. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31538. //all done, run the success callback.
  31539. task.successCallback();
  31540. }
  31541. _this.executeNext();
  31542. });
  31543. });
  31544. }
  31545. else {
  31546. //single simplifier.
  31547. var simplifier = this.getSimplifier(task);
  31548. var runDecimation = function (setting, callback) {
  31549. simplifier.simplify(setting, function (newMesh) {
  31550. task.mesh.addLODLevel(setting.distance, newMesh);
  31551. newMesh.isVisible = true;
  31552. //run the next quality level
  31553. callback();
  31554. });
  31555. };
  31556. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31557. runDecimation(task.settings[loop.index], function () {
  31558. loop.executeNext();
  31559. });
  31560. }, function () {
  31561. //execution ended, run the success callback.
  31562. if (task.successCallback) {
  31563. task.successCallback();
  31564. }
  31565. _this.executeNext();
  31566. });
  31567. }
  31568. };
  31569. SimplificationQueue.prototype.getSimplifier = function (task) {
  31570. switch (task.simplificationType) {
  31571. case SimplificationType.QUADRATIC:
  31572. default:
  31573. return new QuadraticErrorSimplification(task.mesh);
  31574. }
  31575. };
  31576. return SimplificationQueue;
  31577. })();
  31578. BABYLON.SimplificationQueue = SimplificationQueue;
  31579. /**
  31580. * The implemented types of simplification.
  31581. * At the moment only Quadratic Error Decimation is implemented.
  31582. */
  31583. (function (SimplificationType) {
  31584. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31585. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31586. var SimplificationType = BABYLON.SimplificationType;
  31587. var DecimationTriangle = (function () {
  31588. function DecimationTriangle(vertices) {
  31589. this.vertices = vertices;
  31590. this.error = new Array(4);
  31591. this.deleted = false;
  31592. this.isDirty = false;
  31593. this.deletePending = false;
  31594. this.borderFactor = 0;
  31595. }
  31596. return DecimationTriangle;
  31597. })();
  31598. BABYLON.DecimationTriangle = DecimationTriangle;
  31599. var DecimationVertex = (function () {
  31600. function DecimationVertex(position, id) {
  31601. this.position = position;
  31602. this.id = id;
  31603. this.isBorder = true;
  31604. this.q = new QuadraticMatrix();
  31605. this.triangleCount = 0;
  31606. this.triangleStart = 0;
  31607. this.originalOffsets = [];
  31608. }
  31609. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31610. this.position.copyFrom(newPosition);
  31611. };
  31612. return DecimationVertex;
  31613. })();
  31614. BABYLON.DecimationVertex = DecimationVertex;
  31615. var QuadraticMatrix = (function () {
  31616. function QuadraticMatrix(data) {
  31617. this.data = new Array(10);
  31618. for (var i = 0; i < 10; ++i) {
  31619. if (data && data[i]) {
  31620. this.data[i] = data[i];
  31621. }
  31622. else {
  31623. this.data[i] = 0;
  31624. }
  31625. }
  31626. }
  31627. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31628. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31629. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31630. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31631. return det;
  31632. };
  31633. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31634. for (var i = 0; i < 10; ++i) {
  31635. this.data[i] += matrix.data[i];
  31636. }
  31637. };
  31638. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31639. for (var i = 0; i < 10; ++i) {
  31640. this.data[i] += data[i];
  31641. }
  31642. };
  31643. QuadraticMatrix.prototype.add = function (matrix) {
  31644. var m = new QuadraticMatrix();
  31645. for (var i = 0; i < 10; ++i) {
  31646. m.data[i] = this.data[i] + matrix.data[i];
  31647. }
  31648. return m;
  31649. };
  31650. QuadraticMatrix.FromData = function (a, b, c, d) {
  31651. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31652. };
  31653. //returning an array to avoid garbage collection
  31654. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31655. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31656. };
  31657. return QuadraticMatrix;
  31658. })();
  31659. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31660. var Reference = (function () {
  31661. function Reference(vertexId, triangleId) {
  31662. this.vertexId = vertexId;
  31663. this.triangleId = triangleId;
  31664. }
  31665. return Reference;
  31666. })();
  31667. BABYLON.Reference = Reference;
  31668. /**
  31669. * An implementation of the Quadratic Error simplification algorithm.
  31670. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31671. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31672. * @author RaananW
  31673. */
  31674. var QuadraticErrorSimplification = (function () {
  31675. function QuadraticErrorSimplification(_mesh) {
  31676. this._mesh = _mesh;
  31677. this.initialized = false;
  31678. this.syncIterations = 5000;
  31679. this.aggressiveness = 7;
  31680. this.decimationIterations = 100;
  31681. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31682. }
  31683. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31684. var _this = this;
  31685. this.initDecimatedMesh();
  31686. //iterating through the submeshes array, one after the other.
  31687. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31688. _this.initWithMesh(loop.index, function () {
  31689. _this.runDecimation(settings, loop.index, function () {
  31690. loop.executeNext();
  31691. });
  31692. }, settings.optimizeMesh);
  31693. }, function () {
  31694. setTimeout(function () {
  31695. successCallback(_this._reconstructedMesh);
  31696. }, 0);
  31697. });
  31698. };
  31699. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31700. var _this = this;
  31701. var gCount = 0;
  31702. triangle.vertices.forEach(function (vertex) {
  31703. var count = 0;
  31704. var vPos = vertex.position;
  31705. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31706. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31707. ++count;
  31708. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31709. ++count;
  31710. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31711. ++count;
  31712. if (count > 1) {
  31713. ++gCount;
  31714. }
  31715. ;
  31716. });
  31717. if (gCount > 1) {
  31718. console.log(triangle, gCount);
  31719. }
  31720. return gCount > 1;
  31721. };
  31722. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31723. var _this = this;
  31724. var targetCount = ~~(this.triangles.length * settings.quality);
  31725. var deletedTriangles = 0;
  31726. var triangleCount = this.triangles.length;
  31727. var iterationFunction = function (iteration, callback) {
  31728. setTimeout(function () {
  31729. if (iteration % 5 === 0) {
  31730. _this.updateMesh(iteration === 0);
  31731. }
  31732. for (var i = 0; i < _this.triangles.length; ++i) {
  31733. _this.triangles[i].isDirty = false;
  31734. }
  31735. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31736. var trianglesIterator = function (i) {
  31737. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31738. var t = _this.triangles[tIdx];
  31739. if (!t)
  31740. return;
  31741. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31742. return;
  31743. }
  31744. for (var j = 0; j < 3; ++j) {
  31745. if (t.error[j] < threshold) {
  31746. var deleted0 = [];
  31747. var deleted1 = [];
  31748. var v0 = t.vertices[j];
  31749. var v1 = t.vertices[(j + 1) % 3];
  31750. if (v0.isBorder !== v1.isBorder)
  31751. continue;
  31752. var p = BABYLON.Vector3.Zero();
  31753. var n = BABYLON.Vector3.Zero();
  31754. var uv = BABYLON.Vector2.Zero();
  31755. var color = new BABYLON.Color4(0, 0, 0, 1);
  31756. _this.calculateError(v0, v1, p, n, uv, color);
  31757. var delTr = [];
  31758. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31759. continue;
  31760. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31761. continue;
  31762. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31763. continue;
  31764. var uniqueArray = [];
  31765. delTr.forEach(function (deletedT) {
  31766. if (uniqueArray.indexOf(deletedT) === -1) {
  31767. deletedT.deletePending = true;
  31768. uniqueArray.push(deletedT);
  31769. }
  31770. });
  31771. if (uniqueArray.length % 2 != 0) {
  31772. continue;
  31773. }
  31774. v0.q = v1.q.add(v0.q);
  31775. v0.updatePosition(p);
  31776. var tStart = _this.references.length;
  31777. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31778. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31779. var tCount = _this.references.length - tStart;
  31780. if (tCount <= v0.triangleCount) {
  31781. if (tCount) {
  31782. for (var c = 0; c < tCount; c++) {
  31783. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31784. }
  31785. }
  31786. }
  31787. else {
  31788. v0.triangleStart = tStart;
  31789. }
  31790. v0.triangleCount = tCount;
  31791. break;
  31792. }
  31793. }
  31794. };
  31795. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31796. }, 0);
  31797. };
  31798. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31799. if (triangleCount - deletedTriangles <= targetCount)
  31800. loop.breakLoop();
  31801. else {
  31802. iterationFunction(loop.index, function () {
  31803. loop.executeNext();
  31804. });
  31805. }
  31806. }, function () {
  31807. setTimeout(function () {
  31808. //reconstruct this part of the mesh
  31809. _this.reconstructMesh(submeshIndex);
  31810. successCallback();
  31811. }, 0);
  31812. });
  31813. };
  31814. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31815. var _this = this;
  31816. this.vertices = [];
  31817. this.triangles = [];
  31818. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31819. var indices = this._mesh.getIndices();
  31820. var submesh = this._mesh.subMeshes[submeshIndex];
  31821. var findInVertices = function (positionToSearch) {
  31822. if (optimizeMesh) {
  31823. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31824. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31825. return _this.vertices[ii];
  31826. }
  31827. }
  31828. }
  31829. return null;
  31830. };
  31831. var vertexReferences = [];
  31832. var vertexInit = function (i) {
  31833. var offset = i + submesh.verticesStart;
  31834. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31835. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31836. vertex.originalOffsets.push(offset);
  31837. if (vertex.id == _this.vertices.length) {
  31838. _this.vertices.push(vertex);
  31839. }
  31840. vertexReferences.push(vertex.id);
  31841. };
  31842. //var totalVertices = mesh.getTotalVertices();
  31843. var totalVertices = submesh.verticesCount;
  31844. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31845. var indicesInit = function (i) {
  31846. var offset = (submesh.indexStart / 3) + i;
  31847. var pos = (offset * 3);
  31848. var i0 = indices[pos + 0];
  31849. var i1 = indices[pos + 1];
  31850. var i2 = indices[pos + 2];
  31851. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31852. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31853. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31854. var triangle = new DecimationTriangle([v0, v1, v2]);
  31855. triangle.originalOffset = pos;
  31856. _this.triangles.push(triangle);
  31857. };
  31858. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31859. _this.init(callback);
  31860. });
  31861. });
  31862. };
  31863. QuadraticErrorSimplification.prototype.init = function (callback) {
  31864. var _this = this;
  31865. var triangleInit1 = function (i) {
  31866. var t = _this.triangles[i];
  31867. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31868. for (var j = 0; j < 3; j++) {
  31869. 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))));
  31870. }
  31871. };
  31872. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31873. var triangleInit2 = function (i) {
  31874. var t = _this.triangles[i];
  31875. for (var j = 0; j < 3; ++j) {
  31876. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31877. }
  31878. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31879. };
  31880. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31881. _this.initialized = true;
  31882. callback();
  31883. });
  31884. });
  31885. };
  31886. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31887. var newTriangles = [];
  31888. var i;
  31889. for (i = 0; i < this.vertices.length; ++i) {
  31890. this.vertices[i].triangleCount = 0;
  31891. }
  31892. var t;
  31893. var j;
  31894. for (i = 0; i < this.triangles.length; ++i) {
  31895. if (!this.triangles[i].deleted) {
  31896. t = this.triangles[i];
  31897. for (j = 0; j < 3; ++j) {
  31898. t.vertices[j].triangleCount = 1;
  31899. }
  31900. newTriangles.push(t);
  31901. }
  31902. }
  31903. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31904. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31905. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31906. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31907. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31908. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31909. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31910. var vertexCount = 0;
  31911. for (i = 0; i < this.vertices.length; ++i) {
  31912. var vertex = this.vertices[i];
  31913. vertex.id = vertexCount;
  31914. if (vertex.triangleCount) {
  31915. vertex.originalOffsets.forEach(function (originalOffset) {
  31916. newPositionData.push(vertex.position.x);
  31917. newPositionData.push(vertex.position.y);
  31918. newPositionData.push(vertex.position.z);
  31919. newNormalData.push(normalData[originalOffset * 3]);
  31920. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31921. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31922. if (uvs && uvs.length) {
  31923. newUVsData.push(uvs[(originalOffset * 2)]);
  31924. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31925. }
  31926. else if (colorsData && colorsData.length) {
  31927. newColorsData.push(colorsData[(originalOffset * 4)]);
  31928. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31929. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31930. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31931. }
  31932. ++vertexCount;
  31933. });
  31934. }
  31935. }
  31936. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31937. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31938. var submeshesArray = this._reconstructedMesh.subMeshes;
  31939. this._reconstructedMesh.subMeshes = [];
  31940. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31941. var originalIndices = this._mesh.getIndices();
  31942. for (i = 0; i < newTriangles.length; ++i) {
  31943. var t = newTriangles[i];
  31944. //now get the new referencing point for each vertex
  31945. [0, 1, 2].forEach(function (idx) {
  31946. var id = originalIndices[t.originalOffset + idx];
  31947. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31948. if (offset < 0)
  31949. offset = 0;
  31950. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31951. });
  31952. }
  31953. //overwriting the old vertex buffers and indices.
  31954. this._reconstructedMesh.setIndices(newIndicesArray);
  31955. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31956. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31957. if (newUVsData.length > 0)
  31958. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31959. if (newColorsData.length > 0)
  31960. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31961. //create submesh
  31962. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31963. if (submeshIndex > 0) {
  31964. this._reconstructedMesh.subMeshes = [];
  31965. submeshesArray.forEach(function (submesh) {
  31966. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31967. });
  31968. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31969. }
  31970. };
  31971. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31972. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31973. this._reconstructedMesh.material = this._mesh.material;
  31974. this._reconstructedMesh.parent = this._mesh.parent;
  31975. this._reconstructedMesh.isVisible = false;
  31976. };
  31977. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31978. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31979. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31980. if (t.deleted)
  31981. continue;
  31982. var s = this.references[vertex1.triangleStart + i].vertexId;
  31983. var v1 = t.vertices[(s + 1) % 3];
  31984. var v2 = t.vertices[(s + 2) % 3];
  31985. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31986. deletedArray[i] = true;
  31987. delTr.push(t);
  31988. continue;
  31989. }
  31990. var d1 = v1.position.subtract(point);
  31991. d1 = d1.normalize();
  31992. var d2 = v2.position.subtract(point);
  31993. d2 = d2.normalize();
  31994. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31995. return true;
  31996. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31997. deletedArray[i] = false;
  31998. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31999. return true;
  32000. }
  32001. return false;
  32002. };
  32003. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32004. var newDeleted = deletedTriangles;
  32005. for (var i = 0; i < vertex.triangleCount; ++i) {
  32006. var ref = this.references[vertex.triangleStart + i];
  32007. var t = this.triangles[ref.triangleId];
  32008. if (t.deleted)
  32009. continue;
  32010. if (deletedArray[i] && t.deletePending) {
  32011. t.deleted = true;
  32012. newDeleted++;
  32013. continue;
  32014. }
  32015. t.vertices[ref.vertexId] = origVertex;
  32016. t.isDirty = true;
  32017. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32018. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32019. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32020. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32021. this.references.push(ref);
  32022. }
  32023. return newDeleted;
  32024. };
  32025. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32026. for (var i = 0; i < this.vertices.length; ++i) {
  32027. var vCount = [];
  32028. var vId = [];
  32029. var v = this.vertices[i];
  32030. var j;
  32031. for (j = 0; j < v.triangleCount; ++j) {
  32032. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32033. for (var ii = 0; ii < 3; ii++) {
  32034. var ofs = 0;
  32035. var vv = triangle.vertices[ii];
  32036. while (ofs < vCount.length) {
  32037. if (vId[ofs] === vv.id)
  32038. break;
  32039. ++ofs;
  32040. }
  32041. if (ofs === vCount.length) {
  32042. vCount.push(1);
  32043. vId.push(vv.id);
  32044. }
  32045. else {
  32046. vCount[ofs]++;
  32047. }
  32048. }
  32049. }
  32050. for (j = 0; j < vCount.length; ++j) {
  32051. if (vCount[j] === 1) {
  32052. this.vertices[vId[j]].isBorder = true;
  32053. }
  32054. else {
  32055. this.vertices[vId[j]].isBorder = false;
  32056. }
  32057. }
  32058. }
  32059. };
  32060. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32061. if (identifyBorders === void 0) { identifyBorders = false; }
  32062. var i;
  32063. if (!identifyBorders) {
  32064. var newTrianglesVector = [];
  32065. for (i = 0; i < this.triangles.length; ++i) {
  32066. if (!this.triangles[i].deleted) {
  32067. newTrianglesVector.push(this.triangles[i]);
  32068. }
  32069. }
  32070. this.triangles = newTrianglesVector;
  32071. }
  32072. for (i = 0; i < this.vertices.length; ++i) {
  32073. this.vertices[i].triangleCount = 0;
  32074. this.vertices[i].triangleStart = 0;
  32075. }
  32076. var t;
  32077. var j;
  32078. var v;
  32079. for (i = 0; i < this.triangles.length; ++i) {
  32080. t = this.triangles[i];
  32081. for (j = 0; j < 3; ++j) {
  32082. v = t.vertices[j];
  32083. v.triangleCount++;
  32084. }
  32085. }
  32086. var tStart = 0;
  32087. for (i = 0; i < this.vertices.length; ++i) {
  32088. this.vertices[i].triangleStart = tStart;
  32089. tStart += this.vertices[i].triangleCount;
  32090. this.vertices[i].triangleCount = 0;
  32091. }
  32092. var newReferences = new Array(this.triangles.length * 3);
  32093. for (i = 0; i < this.triangles.length; ++i) {
  32094. t = this.triangles[i];
  32095. for (j = 0; j < 3; ++j) {
  32096. v = t.vertices[j];
  32097. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32098. v.triangleCount++;
  32099. }
  32100. }
  32101. this.references = newReferences;
  32102. if (identifyBorders) {
  32103. this.identifyBorder();
  32104. }
  32105. };
  32106. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32107. var x = point.x;
  32108. var y = point.y;
  32109. var z = point.z;
  32110. 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
  32111. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32112. };
  32113. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32114. var q = vertex1.q.add(vertex2.q);
  32115. var border = vertex1.isBorder && vertex2.isBorder;
  32116. var error = 0;
  32117. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32118. if (qDet !== 0 && !border) {
  32119. if (!pointResult) {
  32120. pointResult = BABYLON.Vector3.Zero();
  32121. }
  32122. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32123. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32124. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32125. error = this.vertexError(q, pointResult);
  32126. }
  32127. else {
  32128. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32129. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32130. var error1 = this.vertexError(q, vertex1.position);
  32131. var error2 = this.vertexError(q, vertex2.position);
  32132. var error3 = this.vertexError(q, p3);
  32133. error = Math.min(error1, error2, error3);
  32134. if (error === error1) {
  32135. if (pointResult) {
  32136. pointResult.copyFrom(vertex1.position);
  32137. }
  32138. }
  32139. else if (error === error2) {
  32140. if (pointResult) {
  32141. pointResult.copyFrom(vertex2.position);
  32142. }
  32143. }
  32144. else {
  32145. if (pointResult) {
  32146. pointResult.copyFrom(p3);
  32147. }
  32148. }
  32149. }
  32150. return error;
  32151. };
  32152. return QuadraticErrorSimplification;
  32153. })();
  32154. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32155. })(BABYLON || (BABYLON = {}));
  32156. var BABYLON;
  32157. (function (BABYLON) {
  32158. var Analyser = (function () {
  32159. function Analyser(scene) {
  32160. this.SMOOTHING = 0.75;
  32161. this.FFT_SIZE = 512;
  32162. this.BARGRAPHAMPLITUDE = 256;
  32163. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32164. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32165. this._scene = scene;
  32166. this._audioEngine = BABYLON.Engine.audioEngine;
  32167. if (this._audioEngine.canUseWebAudio) {
  32168. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32169. this._webAudioAnalyser.minDecibels = -140;
  32170. this._webAudioAnalyser.maxDecibels = 0;
  32171. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32172. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32173. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32174. }
  32175. }
  32176. Analyser.prototype.getFrequencyBinCount = function () {
  32177. if (this._audioEngine.canUseWebAudio) {
  32178. return this._webAudioAnalyser.frequencyBinCount;
  32179. }
  32180. else {
  32181. return 0;
  32182. }
  32183. };
  32184. Analyser.prototype.getByteFrequencyData = function () {
  32185. if (this._audioEngine.canUseWebAudio) {
  32186. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32187. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32188. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32189. }
  32190. return this._byteFreqs;
  32191. };
  32192. Analyser.prototype.getByteTimeDomainData = function () {
  32193. if (this._audioEngine.canUseWebAudio) {
  32194. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32195. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32196. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32197. }
  32198. return this._byteTime;
  32199. };
  32200. Analyser.prototype.getFloatFrequencyData = function () {
  32201. if (this._audioEngine.canUseWebAudio) {
  32202. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32203. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32204. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32205. }
  32206. return this._floatFreqs;
  32207. };
  32208. Analyser.prototype.drawDebugCanvas = function () {
  32209. var _this = this;
  32210. if (this._audioEngine.canUseWebAudio) {
  32211. if (!this._debugCanvas) {
  32212. this._debugCanvas = document.createElement("canvas");
  32213. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32214. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32215. this._debugCanvas.style.position = "absolute";
  32216. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32217. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32218. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32219. document.body.appendChild(this._debugCanvas);
  32220. this._registerFunc = function () {
  32221. _this.drawDebugCanvas();
  32222. };
  32223. this._scene.registerBeforeRender(this._registerFunc);
  32224. }
  32225. if (this._registerFunc) {
  32226. var workingArray = this.getByteFrequencyData();
  32227. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32228. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32229. // Draw the frequency domain chart.
  32230. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32231. var value = workingArray[i];
  32232. var percent = value / this.BARGRAPHAMPLITUDE;
  32233. var height = this.DEBUGCANVASSIZE.height * percent;
  32234. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32235. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32236. var hue = i / this.getFrequencyBinCount() * 360;
  32237. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32238. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32239. }
  32240. }
  32241. }
  32242. };
  32243. Analyser.prototype.stopDebugCanvas = function () {
  32244. if (this._debugCanvas) {
  32245. this._scene.unregisterBeforeRender(this._registerFunc);
  32246. this._registerFunc = null;
  32247. document.body.removeChild(this._debugCanvas);
  32248. this._debugCanvas = null;
  32249. this._debugCanvasContext = null;
  32250. }
  32251. };
  32252. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32253. if (this._audioEngine.canUseWebAudio) {
  32254. inputAudioNode.connect(this._webAudioAnalyser);
  32255. this._webAudioAnalyser.connect(outputAudioNode);
  32256. }
  32257. };
  32258. Analyser.prototype.dispose = function () {
  32259. if (this._audioEngine.canUseWebAudio) {
  32260. this._webAudioAnalyser.disconnect();
  32261. }
  32262. };
  32263. return Analyser;
  32264. })();
  32265. BABYLON.Analyser = Analyser;
  32266. })(BABYLON || (BABYLON = {}));
  32267. var BABYLON;
  32268. (function (BABYLON) {
  32269. var DepthRenderer = (function () {
  32270. function DepthRenderer(scene, type) {
  32271. var _this = this;
  32272. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32273. this._viewMatrix = BABYLON.Matrix.Zero();
  32274. this._projectionMatrix = BABYLON.Matrix.Zero();
  32275. this._transformMatrix = BABYLON.Matrix.Zero();
  32276. this._worldViewProjection = BABYLON.Matrix.Zero();
  32277. this._scene = scene;
  32278. var engine = scene.getEngine();
  32279. // Render target
  32280. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32281. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32282. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32283. this._depthMap.refreshRate = 1;
  32284. this._depthMap.renderParticles = false;
  32285. this._depthMap.renderList = null;
  32286. // set default depth value to 1.0 (far away)
  32287. this._depthMap.onClear = function (engine) {
  32288. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32289. };
  32290. // Custom render function
  32291. var renderSubMesh = function (subMesh) {
  32292. var mesh = subMesh.getRenderingMesh();
  32293. var scene = _this._scene;
  32294. var engine = scene.getEngine();
  32295. // Culling
  32296. engine.setState(subMesh.getMaterial().backFaceCulling);
  32297. // Managing instances
  32298. var batch = mesh._getInstancesRenderList(subMesh._id);
  32299. if (batch.mustReturn) {
  32300. return;
  32301. }
  32302. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32303. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32304. engine.enableEffect(_this._effect);
  32305. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32306. var material = subMesh.getMaterial();
  32307. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32308. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32309. // Alpha test
  32310. if (material && material.needAlphaTesting()) {
  32311. var alphaTexture = material.getAlphaTestTexture();
  32312. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32313. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32314. }
  32315. // Bones
  32316. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32317. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32318. }
  32319. // Draw
  32320. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32321. }
  32322. };
  32323. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32324. var index;
  32325. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32326. renderSubMesh(opaqueSubMeshes.data[index]);
  32327. }
  32328. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32329. renderSubMesh(alphaTestSubMeshes.data[index]);
  32330. }
  32331. };
  32332. }
  32333. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32334. var defines = [];
  32335. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32336. var mesh = subMesh.getMesh();
  32337. var scene = mesh.getScene();
  32338. var material = subMesh.getMaterial();
  32339. // Alpha test
  32340. if (material && material.needAlphaTesting()) {
  32341. defines.push("#define ALPHATEST");
  32342. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32343. attribs.push(BABYLON.VertexBuffer.UVKind);
  32344. defines.push("#define UV1");
  32345. }
  32346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32347. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32348. defines.push("#define UV2");
  32349. }
  32350. }
  32351. // Bones
  32352. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32355. defines.push("#define BONES");
  32356. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32357. }
  32358. // Instances
  32359. if (useInstances) {
  32360. defines.push("#define INSTANCES");
  32361. attribs.push("world0");
  32362. attribs.push("world1");
  32363. attribs.push("world2");
  32364. attribs.push("world3");
  32365. }
  32366. // Get correct effect
  32367. var join = defines.join("\n");
  32368. if (this._cachedDefines !== join) {
  32369. this._cachedDefines = join;
  32370. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32371. }
  32372. return this._effect.isReady();
  32373. };
  32374. DepthRenderer.prototype.getDepthMap = function () {
  32375. return this._depthMap;
  32376. };
  32377. // Methods
  32378. DepthRenderer.prototype.dispose = function () {
  32379. this._depthMap.dispose();
  32380. };
  32381. return DepthRenderer;
  32382. })();
  32383. BABYLON.DepthRenderer = DepthRenderer;
  32384. })(BABYLON || (BABYLON = {}));
  32385. var BABYLON;
  32386. (function (BABYLON) {
  32387. var SSAORenderingPipeline = (function (_super) {
  32388. __extends(SSAORenderingPipeline, _super);
  32389. /**
  32390. * @constructor
  32391. * @param {string} name - The rendering pipeline name
  32392. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32393. * @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 }
  32394. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32395. */
  32396. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32397. var _this = this;
  32398. _super.call(this, scene.getEngine(), name);
  32399. // Members
  32400. /**
  32401. * The PassPostProcess id in the pipeline that contains the original scene color
  32402. * @type {string}
  32403. */
  32404. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32405. /**
  32406. * The SSAO PostProcess id in the pipeline
  32407. * @type {string}
  32408. */
  32409. this.SSAORenderEffect = "SSAORenderEffect";
  32410. /**
  32411. * The horizontal blur PostProcess id in the pipeline
  32412. * @type {string}
  32413. */
  32414. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32415. /**
  32416. * The vertical blur PostProcess id in the pipeline
  32417. * @type {string}
  32418. */
  32419. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32420. /**
  32421. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32422. * @type {string}
  32423. */
  32424. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32425. /**
  32426. * The output strength of the SSAO post-process. Default value is 1.0.
  32427. * @type {number}
  32428. */
  32429. this.totalStrength = 1.0;
  32430. /**
  32431. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32432. * @type {number}
  32433. */
  32434. this.radius = 0.0002;
  32435. /**
  32436. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32437. * Must not be equal to fallOff and superior to fallOff.
  32438. * Default value is 0.0075
  32439. * @type {number}
  32440. */
  32441. this.area = 0.0075;
  32442. /**
  32443. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32444. * Must not be equal to area and inferior to area.
  32445. * Default value is 0.0002
  32446. * @type {number}
  32447. */
  32448. this.fallOff = 0.0002;
  32449. this._firstUpdate = true;
  32450. this._scene = scene;
  32451. // Set up assets
  32452. this._createRandomTexture();
  32453. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32454. var ssaoRatio = ratio.ssaoRatio || ratio;
  32455. var combineRatio = ratio.combineRatio || ratio;
  32456. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32457. this._createSSAOPostProcess(ssaoRatio);
  32458. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32459. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32460. this._createSSAOCombinePostProcess(combineRatio);
  32461. // Set up pipeline
  32462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32464. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32465. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32466. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32467. // Finish
  32468. scene.postProcessRenderPipelineManager.addPipeline(this);
  32469. if (cameras)
  32470. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32471. }
  32472. // Public Methods
  32473. /**
  32474. * Returns the horizontal blur PostProcess
  32475. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32476. */
  32477. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32478. return this._blurHPostProcess;
  32479. };
  32480. /**
  32481. * Returns the vertical blur PostProcess
  32482. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32483. */
  32484. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32485. return this._blurVPostProcess;
  32486. };
  32487. /**
  32488. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32489. */
  32490. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32491. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32492. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32493. this._originalColorPostProcess = undefined;
  32494. this._ssaoPostProcess = undefined;
  32495. this._blurHPostProcess = undefined;
  32496. this._blurVPostProcess = undefined;
  32497. this._ssaoCombinePostProcess = undefined;
  32498. this._randomTexture.dispose();
  32499. if (disableDepthRender)
  32500. this._scene.disableDepthRenderer();
  32501. };
  32502. // Private Methods
  32503. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32504. var _this = this;
  32505. var sampleSphere = [
  32506. 0.5381, 0.1856, -0.4319,
  32507. 0.1379, 0.2486, 0.4430,
  32508. 0.3371, 0.5679, -0.0057,
  32509. -0.6999, -0.0451, -0.0019,
  32510. 0.0689, -0.1598, -0.8547,
  32511. 0.0560, 0.0069, -0.1843,
  32512. -0.0146, 0.1402, 0.0762,
  32513. 0.0100, -0.1924, -0.0344,
  32514. -0.3577, -0.5301, -0.4358,
  32515. -0.3169, 0.1063, 0.0158,
  32516. 0.0103, -0.5869, 0.0046,
  32517. -0.0897, -0.4940, 0.3287,
  32518. 0.7119, -0.0154, -0.0918,
  32519. -0.0533, 0.0596, -0.5411,
  32520. 0.0352, -0.0631, 0.5460,
  32521. -0.4776, 0.2847, -0.0271
  32522. ];
  32523. var samplesFactor = 1.0 / 16.0;
  32524. 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);
  32525. this._ssaoPostProcess.onApply = function (effect) {
  32526. if (_this._firstUpdate) {
  32527. effect.setArray3("sampleSphere", sampleSphere);
  32528. effect.setFloat("samplesFactor", samplesFactor);
  32529. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32530. _this._firstUpdate = false;
  32531. }
  32532. effect.setFloat("totalStrength", _this.totalStrength);
  32533. effect.setFloat("radius", _this.radius);
  32534. effect.setFloat("area", _this.area);
  32535. effect.setFloat("fallOff", _this.fallOff);
  32536. effect.setTexture("textureSampler", _this._depthTexture);
  32537. effect.setTexture("randomSampler", _this._randomTexture);
  32538. };
  32539. };
  32540. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32541. var _this = this;
  32542. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32543. this._ssaoCombinePostProcess.onApply = function (effect) {
  32544. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32545. };
  32546. };
  32547. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32548. var size = 512;
  32549. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32550. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32551. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32552. var context = this._randomTexture.getContext();
  32553. var rand = function (min, max) {
  32554. return Math.random() * (max - min) + min;
  32555. };
  32556. for (var x = 0; x < size; x++) {
  32557. for (var y = 0; y < size; y++) {
  32558. var randVector = BABYLON.Vector3.Zero();
  32559. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32560. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32561. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32562. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32563. context.fillRect(x, y, 1, 1);
  32564. }
  32565. }
  32566. this._randomTexture.update(false);
  32567. };
  32568. return SSAORenderingPipeline;
  32569. })(BABYLON.PostProcessRenderPipeline);
  32570. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32571. })(BABYLON || (BABYLON = {}));
  32572. var BABYLON;
  32573. (function (BABYLON) {
  32574. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32575. var VolumetricLightScatteringPostProcess = (function (_super) {
  32576. __extends(VolumetricLightScatteringPostProcess, _super);
  32577. /**
  32578. * @constructor
  32579. * @param {string} name - The post-process name
  32580. * @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)
  32581. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32582. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32583. * @param {number} samples - The post-process quality, default 100
  32584. * @param {number} samplingMode - The post-process filtering mode
  32585. * @param {BABYLON.Engine} engine - The babylon engine
  32586. * @param {boolean} reusable - If the post-process is reusable
  32587. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32588. */
  32589. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32590. var _this = this;
  32591. if (samples === void 0) { samples = 100; }
  32592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32593. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32594. this._screenCoordinates = BABYLON.Vector2.Zero();
  32595. /**
  32596. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32597. * @type {boolean}
  32598. */
  32599. this.useCustomMeshPosition = false;
  32600. /**
  32601. * If the post-process should inverse the light scattering direction
  32602. * @type {boolean}
  32603. */
  32604. this.invert = true;
  32605. /**
  32606. * Set to true to use the diffuseColor instead of the diffuseTexture
  32607. * @type {boolean}
  32608. */
  32609. this.useDiffuseColor = false;
  32610. /**
  32611. * Array containing the excluded meshes not rendered in the internal pass
  32612. */
  32613. this.excludedMeshes = new Array();
  32614. /**
  32615. * Controls the overall intensity of the post-process
  32616. * @type {number}
  32617. */
  32618. this.exposure = 0.3;
  32619. /**
  32620. * Dissipates each sample's contribution in range [0, 1]
  32621. * @type {number}
  32622. */
  32623. this.decay = 0.96815;
  32624. /**
  32625. * Controls the overall intensity of each sample
  32626. * @type {number}
  32627. */
  32628. this.weight = 0.58767;
  32629. /**
  32630. * Controls the density of each sample
  32631. * @type {number}
  32632. */
  32633. this.density = 0.926;
  32634. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32635. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32636. // Configure mesh
  32637. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32638. // Configure
  32639. this._createPass(scene, ratio.passRatio || ratio);
  32640. this.onApply = function (effect) {
  32641. _this._updateMeshScreenCoordinates(scene);
  32642. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32643. effect.setFloat("exposure", _this.exposure);
  32644. effect.setFloat("decay", _this.decay);
  32645. effect.setFloat("weight", _this.weight);
  32646. effect.setFloat("density", _this.density);
  32647. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32648. };
  32649. }
  32650. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32651. var mesh = subMesh.getMesh();
  32652. var defines = [];
  32653. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32654. var material = subMesh.getMaterial();
  32655. var needUV = false;
  32656. // Render this.mesh as default
  32657. if (mesh === this.mesh) {
  32658. if (this.useDiffuseColor) {
  32659. defines.push("#define DIFFUSE_COLOR_RENDER");
  32660. }
  32661. else if (material) {
  32662. if (material.diffuseTexture !== undefined) {
  32663. defines.push("#define BASIC_RENDER");
  32664. }
  32665. else {
  32666. defines.push("#define DIFFUSE_COLOR_RENDER");
  32667. }
  32668. }
  32669. defines.push("#define NEED_UV");
  32670. needUV = true;
  32671. }
  32672. // Alpha test
  32673. if (material) {
  32674. if (material.needAlphaTesting()) {
  32675. defines.push("#define ALPHATEST");
  32676. }
  32677. if (material.opacityTexture !== undefined) {
  32678. defines.push("#define OPACITY");
  32679. if (material.opacityTexture.getAlphaFromRGB) {
  32680. defines.push("#define OPACITYRGB");
  32681. }
  32682. if (!needUV) {
  32683. defines.push("#define NEED_UV");
  32684. }
  32685. }
  32686. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32687. attribs.push(BABYLON.VertexBuffer.UVKind);
  32688. defines.push("#define UV1");
  32689. }
  32690. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32691. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32692. defines.push("#define UV2");
  32693. }
  32694. }
  32695. // Bones
  32696. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32697. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32698. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32699. defines.push("#define BONES");
  32700. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32701. }
  32702. // Instances
  32703. if (useInstances) {
  32704. defines.push("#define INSTANCES");
  32705. attribs.push("world0");
  32706. attribs.push("world1");
  32707. attribs.push("world2");
  32708. attribs.push("world3");
  32709. }
  32710. // Get correct effect
  32711. var join = defines.join("\n");
  32712. if (this._cachedDefines !== join) {
  32713. this._cachedDefines = join;
  32714. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32715. }
  32716. return this._volumetricLightScatteringPass.isReady();
  32717. };
  32718. /**
  32719. * Sets the new light position for light scattering effect
  32720. * @param {BABYLON.Vector3} The new custom light position
  32721. */
  32722. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32723. this._customMeshPosition = position;
  32724. };
  32725. /**
  32726. * Returns the light position for light scattering effect
  32727. * @return {BABYLON.Vector3} The custom light position
  32728. */
  32729. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32730. return this._customMeshPosition;
  32731. };
  32732. /**
  32733. * Disposes the internal assets and detaches the post-process from the camera
  32734. */
  32735. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32736. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32737. if (rttIndex !== -1) {
  32738. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32739. }
  32740. this._volumetricLightScatteringRTT.dispose();
  32741. _super.prototype.dispose.call(this, camera);
  32742. };
  32743. /**
  32744. * Returns the render target texture used by the post-process
  32745. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32746. */
  32747. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32748. return this._volumetricLightScatteringRTT;
  32749. };
  32750. // Private methods
  32751. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32752. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32753. return true;
  32754. }
  32755. return false;
  32756. };
  32757. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32758. var _this = this;
  32759. var engine = scene.getEngine();
  32760. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32761. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32762. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32763. this._volumetricLightScatteringRTT.renderList = null;
  32764. this._volumetricLightScatteringRTT.renderParticles = false;
  32765. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32766. // Custom render function for submeshes
  32767. var renderSubMesh = function (subMesh) {
  32768. var mesh = subMesh.getRenderingMesh();
  32769. if (_this._meshExcluded(mesh)) {
  32770. return;
  32771. }
  32772. var scene = mesh.getScene();
  32773. var engine = scene.getEngine();
  32774. // Culling
  32775. engine.setState(subMesh.getMaterial().backFaceCulling);
  32776. // Managing instances
  32777. var batch = mesh._getInstancesRenderList(subMesh._id);
  32778. if (batch.mustReturn) {
  32779. return;
  32780. }
  32781. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32782. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32783. engine.enableEffect(_this._volumetricLightScatteringPass);
  32784. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32785. var material = subMesh.getMaterial();
  32786. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32787. // Alpha test
  32788. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32789. var alphaTexture = material.getAlphaTestTexture();
  32790. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32791. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32792. }
  32793. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32794. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32795. if (alphaTexture) {
  32796. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32797. }
  32798. }
  32799. if (material.opacityTexture !== undefined) {
  32800. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32801. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32802. }
  32803. }
  32804. // Bones
  32805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32806. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32807. }
  32808. // Draw
  32809. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32810. }
  32811. };
  32812. // Render target texture callbacks
  32813. var savedSceneClearColor;
  32814. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32815. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32816. savedSceneClearColor = scene.clearColor;
  32817. scene.clearColor = sceneClearColor;
  32818. };
  32819. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32820. scene.clearColor = savedSceneClearColor;
  32821. };
  32822. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32823. var engine = scene.getEngine();
  32824. var index;
  32825. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32826. renderSubMesh(opaqueSubMeshes.data[index]);
  32827. }
  32828. engine.setAlphaTesting(true);
  32829. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32830. renderSubMesh(alphaTestSubMeshes.data[index]);
  32831. }
  32832. engine.setAlphaTesting(false);
  32833. if (transparentSubMeshes.length) {
  32834. // Sort sub meshes
  32835. for (index = 0; index < transparentSubMeshes.length; index++) {
  32836. var submesh = transparentSubMeshes.data[index];
  32837. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32838. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32839. }
  32840. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32841. sortedArray.sort(function (a, b) {
  32842. // Alpha index first
  32843. if (a._alphaIndex > b._alphaIndex) {
  32844. return 1;
  32845. }
  32846. if (a._alphaIndex < b._alphaIndex) {
  32847. return -1;
  32848. }
  32849. // Then distance to camera
  32850. if (a._distanceToCamera < b._distanceToCamera) {
  32851. return 1;
  32852. }
  32853. if (a._distanceToCamera > b._distanceToCamera) {
  32854. return -1;
  32855. }
  32856. return 0;
  32857. });
  32858. // Render sub meshes
  32859. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32860. for (index = 0; index < sortedArray.length; index++) {
  32861. renderSubMesh(sortedArray[index]);
  32862. }
  32863. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32864. }
  32865. };
  32866. };
  32867. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32868. var transform = scene.getTransformMatrix();
  32869. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32870. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32871. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32872. if (this.invert)
  32873. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32874. };
  32875. // Static methods
  32876. /**
  32877. * Creates a default mesh for the Volumeric Light Scattering post-process
  32878. * @param {string} The mesh name
  32879. * @param {BABYLON.Scene} The scene where to create the mesh
  32880. * @return {BABYLON.Mesh} the default mesh
  32881. */
  32882. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32883. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32884. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32885. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32886. return mesh;
  32887. };
  32888. return VolumetricLightScatteringPostProcess;
  32889. })(BABYLON.PostProcess);
  32890. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32891. })(BABYLON || (BABYLON = {}));
  32892. var BABYLON;
  32893. (function (BABYLON) {
  32894. var LensRenderingPipeline = (function (_super) {
  32895. __extends(LensRenderingPipeline, _super);
  32896. /**
  32897. * @constructor
  32898. *
  32899. * Effect parameters are as follow:
  32900. * {
  32901. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32902. * edge_blur: number; // from 0 to x (1 for realism)
  32903. * distortion: number; // from 0 to x (1 for realism)
  32904. * grain_amount: number; // from 0 to 1
  32905. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32906. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32907. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32908. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32909. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32910. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32911. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32912. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32913. * }
  32914. * Note: if an effect parameter is unset, effect is disabled
  32915. *
  32916. * @param {string} name - The rendering pipeline name
  32917. * @param {object} parameters - An object containing all parameters (see above)
  32918. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32919. * @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)
  32920. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32921. */
  32922. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32923. var _this = this;
  32924. if (ratio === void 0) { ratio = 1.0; }
  32925. _super.call(this, scene.getEngine(), name);
  32926. // Lens effects can be of the following:
  32927. // - chromatic aberration (slight shift of RGB colors)
  32928. // - blur on the edge of the lens
  32929. // - lens distortion
  32930. // - depth-of-field blur & highlights enhancing
  32931. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32932. // - grain effect (noise or custom texture)
  32933. // Two additional texture samplers are needed:
  32934. // - depth map (for depth-of-field)
  32935. // - grain texture
  32936. /**
  32937. * The chromatic aberration PostProcess id in the pipeline
  32938. * @type {string}
  32939. */
  32940. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32941. /**
  32942. * The highlights enhancing PostProcess id in the pipeline
  32943. * @type {string}
  32944. */
  32945. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32946. /**
  32947. * The depth-of-field PostProcess id in the pipeline
  32948. * @type {string}
  32949. */
  32950. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32951. this._scene = scene;
  32952. // Fetch texture samplers
  32953. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32954. if (parameters.grain_texture) {
  32955. this._grainTexture = parameters.grain_texture;
  32956. }
  32957. else {
  32958. this._createGrainTexture();
  32959. }
  32960. // save parameters
  32961. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32962. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32963. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32964. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32965. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32966. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32967. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32968. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32969. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32970. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32971. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32972. // Create effects
  32973. this._createChromaticAberrationPostProcess(ratio);
  32974. this._createHighlightsPostProcess(ratio);
  32975. this._createDepthOfFieldPostProcess(ratio / 4);
  32976. // Set up pipeline
  32977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32978. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32979. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32980. if (this._highlightsGain == -1) {
  32981. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32982. }
  32983. // Finish
  32984. scene.postProcessRenderPipelineManager.addPipeline(this);
  32985. if (cameras) {
  32986. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32987. }
  32988. }
  32989. // public methods (self explanatory)
  32990. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32991. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32992. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32993. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32994. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32995. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32996. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32997. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32998. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32999. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  33000. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  33001. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  33002. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  33003. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  33004. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  33005. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  33006. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  33007. this._highlightsGain = amount;
  33008. };
  33009. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  33010. if (this._highlightsGain == -1) {
  33011. this._highlightsGain = 1.0;
  33012. }
  33013. this._highlightsThreshold = amount;
  33014. };
  33015. LensRenderingPipeline.prototype.disableHighlights = function () {
  33016. this._highlightsGain = -1;
  33017. };
  33018. /**
  33019. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  33020. */
  33021. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33022. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33023. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33024. this._chromaticAberrationPostProcess = undefined;
  33025. this._highlightsPostProcess = undefined;
  33026. this._depthOfFieldPostProcess = undefined;
  33027. this._grainTexture.dispose();
  33028. if (disableDepthRender)
  33029. this._scene.disableDepthRenderer();
  33030. };
  33031. // colors shifting and distortion
  33032. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  33033. var _this = this;
  33034. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  33035. [], // samplers
  33036. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33037. this._chromaticAberrationPostProcess.onApply = function (effect) {
  33038. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  33039. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33040. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33041. };
  33042. };
  33043. // highlights enhancing
  33044. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33045. var _this = this;
  33046. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33047. [], // samplers
  33048. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33049. this._highlightsPostProcess.onApply = function (effect) {
  33050. effect.setFloat('gain', _this._highlightsGain);
  33051. effect.setFloat('threshold', _this._highlightsThreshold);
  33052. effect.setBool('pentagon', _this._dofPentagon);
  33053. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33054. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33055. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33056. };
  33057. };
  33058. // colors shifting and distortion
  33059. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33060. var _this = this;
  33061. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33062. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33063. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33064. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33065. this._depthOfFieldPostProcess.onApply = function (effect) {
  33066. effect.setTexture("depthSampler", _this._depthTexture);
  33067. effect.setTexture("grainSampler", _this._grainTexture);
  33068. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33069. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33070. effect.setFloat('grain_amount', _this._grainAmount);
  33071. effect.setBool('blur_noise', _this._blurNoise);
  33072. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33073. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33074. effect.setFloat('distortion', _this._distortion);
  33075. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33076. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33077. effect.setFloat('aperture', _this._dofAperture);
  33078. effect.setFloat('darken', _this._dofDarken);
  33079. effect.setFloat('edge_blur', _this._edgeBlur);
  33080. effect.setBool('highlights', (_this._highlightsGain != -1));
  33081. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33082. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33083. };
  33084. };
  33085. // creates a black and white random noise texture, 512x512
  33086. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33087. var size = 512;
  33088. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33089. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33090. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33091. var context = this._grainTexture.getContext();
  33092. var rand = function (min, max) {
  33093. return Math.random() * (max - min) + min;
  33094. };
  33095. var value;
  33096. for (var x = 0; x < size; x++) {
  33097. for (var y = 0; y < size; y++) {
  33098. value = Math.floor(rand(0.42, 0.58) * 255);
  33099. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33100. context.fillRect(x, y, 1, 1);
  33101. }
  33102. }
  33103. this._grainTexture.update(false);
  33104. };
  33105. return LensRenderingPipeline;
  33106. })(BABYLON.PostProcessRenderPipeline);
  33107. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33108. })(BABYLON || (BABYLON = {}));
  33109. //
  33110. // This post-process allows the modification of rendered colors by using
  33111. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33112. //
  33113. // The object needs to be provided an url to a texture containing the color
  33114. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33115. // Use an image editing software to tweak the LUT to match your needs.
  33116. //
  33117. // For an example of a color LUT, see here:
  33118. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33119. // For explanations on color grading, see here:
  33120. // http://udn.epicgames.com/Three/ColorGrading.html
  33121. //
  33122. var BABYLON;
  33123. (function (BABYLON) {
  33124. var ColorCorrectionPostProcess = (function (_super) {
  33125. __extends(ColorCorrectionPostProcess, _super);
  33126. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33127. var _this = this;
  33128. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33129. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33130. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33131. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33132. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33133. this.onApply = function (effect) {
  33134. effect.setTexture("colorTable", _this._colorTableTexture);
  33135. };
  33136. }
  33137. return ColorCorrectionPostProcess;
  33138. })(BABYLON.PostProcess);
  33139. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33140. })(BABYLON || (BABYLON = {}));
  33141. var BABYLON;
  33142. (function (BABYLON) {
  33143. var AnaglyphFreeCamera = (function (_super) {
  33144. __extends(AnaglyphFreeCamera, _super);
  33145. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33146. _super.call(this, name, position, scene);
  33147. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33148. }
  33149. return AnaglyphFreeCamera;
  33150. })(BABYLON.FreeCamera);
  33151. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33152. var AnaglyphArcRotateCamera = (function (_super) {
  33153. __extends(AnaglyphArcRotateCamera, _super);
  33154. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33155. _super.call(this, name, alpha, beta, radius, target, scene);
  33156. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33157. }
  33158. return AnaglyphArcRotateCamera;
  33159. })(BABYLON.ArcRotateCamera);
  33160. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33161. var AnaglyphGamepadCamera = (function (_super) {
  33162. __extends(AnaglyphGamepadCamera, _super);
  33163. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33164. _super.call(this, name, position, scene);
  33165. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33166. }
  33167. return AnaglyphGamepadCamera;
  33168. })(BABYLON.GamepadCamera);
  33169. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33170. var StereoscopicFreeCamera = (function (_super) {
  33171. __extends(StereoscopicFreeCamera, _super);
  33172. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33173. _super.call(this, name, position, scene);
  33174. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33175. }
  33176. return StereoscopicFreeCamera;
  33177. })(BABYLON.FreeCamera);
  33178. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33179. var StereoscopicArcRotateCamera = (function (_super) {
  33180. __extends(StereoscopicArcRotateCamera, _super);
  33181. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33182. _super.call(this, name, alpha, beta, radius, target, scene);
  33183. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33184. }
  33185. return StereoscopicArcRotateCamera;
  33186. })(BABYLON.ArcRotateCamera);
  33187. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33188. var StereoscopicGamepadCamera = (function (_super) {
  33189. __extends(StereoscopicGamepadCamera, _super);
  33190. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33191. _super.call(this, name, position, scene);
  33192. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33193. }
  33194. return StereoscopicGamepadCamera;
  33195. })(BABYLON.GamepadCamera);
  33196. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33197. })(BABYLON || (BABYLON = {}));
  33198. var BABYLON;
  33199. (function (BABYLON) {
  33200. var HDRRenderingPipeline = (function (_super) {
  33201. __extends(HDRRenderingPipeline, _super);
  33202. /**
  33203. * @constructor
  33204. * @param {string} name - The rendering pipeline name
  33205. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33206. * @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)
  33207. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33208. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33209. */
  33210. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33211. var _this = this;
  33212. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33213. _super.call(this, scene.getEngine(), name);
  33214. /**
  33215. * Public members
  33216. */
  33217. // Gaussian Blur
  33218. /**
  33219. * Gaussian blur coefficient
  33220. * @type {number}
  33221. */
  33222. this.gaussCoeff = 0.3;
  33223. /**
  33224. * Gaussian blur mean
  33225. * @type {number}
  33226. */
  33227. this.gaussMean = 1.0;
  33228. /**
  33229. * Gaussian blur standard deviation
  33230. * @type {number}
  33231. */
  33232. this.gaussStandDev = 0.8;
  33233. // HDR
  33234. /**
  33235. * Exposure, controls the overall intensity of the pipeline
  33236. * @type {number}
  33237. */
  33238. this.exposure = 1.0;
  33239. /**
  33240. * Minimum luminance that the post-process can output. Luminance is >= 0
  33241. * @type {number}
  33242. */
  33243. this.minimumLuminance = 1.0;
  33244. /**
  33245. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33246. * @type {number}
  33247. */
  33248. this.maximumLuminance = 1e20;
  33249. /**
  33250. * Increase rate for luminance: eye adaptation speed to dark
  33251. * @type {number}
  33252. */
  33253. this.luminanceIncreaserate = 0.5;
  33254. /**
  33255. * Decrease rate for luminance: eye adaptation speed to bright
  33256. * @type {number}
  33257. */
  33258. this.luminanceDecreaseRate = 0.5;
  33259. // Bright pass
  33260. /**
  33261. * Minimum luminance needed to compute HDR
  33262. * @type {number}
  33263. */
  33264. this.brightThreshold = 0.8;
  33265. this._needUpdate = true;
  33266. this._scene = scene;
  33267. // Bright pass
  33268. this._createBrightPassPostProcess(scene, ratio);
  33269. // Down sample X4
  33270. this._createDownSampleX4PostProcess(scene, ratio);
  33271. // Create gaussian blur post-processes
  33272. this._createGaussianBlurPostProcess(scene, ratio);
  33273. // Texture adder
  33274. this._createTextureAdderPostProcess(scene, ratio);
  33275. // Luminance generator
  33276. this._createLuminanceGeneratorPostProcess(scene);
  33277. // HDR
  33278. this._createHDRPostProcess(scene, ratio);
  33279. // Pass postprocess
  33280. if (originalPostProcess === null) {
  33281. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33282. }
  33283. else {
  33284. this._originalPostProcess = originalPostProcess;
  33285. }
  33286. // Configure pipeline
  33287. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33293. var addDownSamplerPostProcess = function (id) {
  33294. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33295. };
  33296. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33297. addDownSamplerPostProcess(i);
  33298. }
  33299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33300. // Finish
  33301. scene.postProcessRenderPipelineManager.addPipeline(this);
  33302. if (cameras !== null) {
  33303. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33304. }
  33305. this.update();
  33306. }
  33307. /**
  33308. * Tells the pipeline to update its post-processes
  33309. */
  33310. HDRRenderingPipeline.prototype.update = function () {
  33311. this._needUpdate = true;
  33312. };
  33313. /**
  33314. * Returns the current calculated luminance
  33315. */
  33316. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33317. return this._hdrCurrentLuminance;
  33318. };
  33319. /**
  33320. * Returns the currently drawn luminance
  33321. */
  33322. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33323. return this._hdrOutputLuminance;
  33324. };
  33325. /**
  33326. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33327. */
  33328. HDRRenderingPipeline.prototype.dispose = function () {
  33329. this._originalPostProcess = undefined;
  33330. this._brightPassPostProcess = undefined;
  33331. this._downSampleX4PostProcess = undefined;
  33332. this._guassianBlurHPostProcess = undefined;
  33333. this._guassianBlurVPostProcess = undefined;
  33334. this._textureAdderPostProcess = undefined;
  33335. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33336. this._downSamplePostProcesses[i] = undefined;
  33337. }
  33338. this._hdrPostProcess = undefined;
  33339. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33340. };
  33341. /**
  33342. * Creates the HDR post-process and computes the luminance adaptation
  33343. */
  33344. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33345. var _this = this;
  33346. var hdrLastLuminance = 0.0;
  33347. this._hdrOutputLuminance = -1.0;
  33348. this._hdrCurrentLuminance = 1.0;
  33349. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33350. this._hdrPostProcess.onApply = function (effect) {
  33351. if (_this._hdrOutputLuminance < 0.0) {
  33352. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33353. }
  33354. else {
  33355. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33356. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33357. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33358. }
  33359. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33360. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33361. }
  33362. else {
  33363. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33364. }
  33365. }
  33366. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33367. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33368. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33369. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33370. effect.setFloat("exposure", _this.exposure);
  33371. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33372. _this._needUpdate = false;
  33373. };
  33374. };
  33375. /**
  33376. * Texture Adder post-process
  33377. */
  33378. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33379. var _this = this;
  33380. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33381. this._textureAdderPostProcess.onApply = function (effect) {
  33382. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33383. };
  33384. };
  33385. /**
  33386. * Down sample X4 post-process
  33387. */
  33388. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33389. var _this = this;
  33390. var downSampleX4Offsets = new Array(32);
  33391. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33392. this._downSampleX4PostProcess.onApply = function (effect) {
  33393. if (_this._needUpdate) {
  33394. var id = 0;
  33395. for (var i = -2; i < 2; i++) {
  33396. for (var j = -2; j < 2; j++) {
  33397. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33398. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33399. id += 2;
  33400. }
  33401. }
  33402. }
  33403. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33404. };
  33405. };
  33406. /**
  33407. * Bright pass post-process
  33408. */
  33409. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33410. var _this = this;
  33411. var brightOffsets = new Array(8);
  33412. var brightPassCallback = function (effect) {
  33413. if (_this._needUpdate) {
  33414. var sU = (1.0 / _this._brightPassPostProcess.width);
  33415. var sV = (1.0 / _this._brightPassPostProcess.height);
  33416. brightOffsets[0] = -0.5 * sU;
  33417. brightOffsets[1] = 0.5 * sV;
  33418. brightOffsets[2] = 0.5 * sU;
  33419. brightOffsets[3] = 0.5 * sV;
  33420. brightOffsets[4] = -0.5 * sU;
  33421. brightOffsets[5] = -0.5 * sV;
  33422. brightOffsets[6] = 0.5 * sU;
  33423. brightOffsets[7] = -0.5 * sV;
  33424. }
  33425. effect.setArray2("dsOffsets", brightOffsets);
  33426. effect.setFloat("brightThreshold", _this.brightThreshold);
  33427. };
  33428. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33429. this._brightPassPostProcess.onApply = brightPassCallback;
  33430. };
  33431. /**
  33432. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33433. */
  33434. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33435. var _this = this;
  33436. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33437. var luminanceOffsets = new Array(8);
  33438. var downSampleOffsets = new Array(18);
  33439. var halfDestPixelSize;
  33440. this._downSamplePostProcesses = new Array(lumSteps);
  33441. // Utils for luminance
  33442. var luminanceUpdateSourceOffsets = function (width, height) {
  33443. var sU = (1.0 / width);
  33444. var sV = (1.0 / height);
  33445. luminanceOffsets[0] = -0.5 * sU;
  33446. luminanceOffsets[1] = 0.5 * sV;
  33447. luminanceOffsets[2] = 0.5 * sU;
  33448. luminanceOffsets[3] = 0.5 * sV;
  33449. luminanceOffsets[4] = -0.5 * sU;
  33450. luminanceOffsets[5] = -0.5 * sV;
  33451. luminanceOffsets[6] = 0.5 * sU;
  33452. luminanceOffsets[7] = -0.5 * sV;
  33453. };
  33454. var luminanceUpdateDestOffsets = function (width, height) {
  33455. var id = 0;
  33456. for (var x = -1; x < 2; x++) {
  33457. for (var y = -1; y < 2; y++) {
  33458. downSampleOffsets[id] = (x) / width;
  33459. downSampleOffsets[id + 1] = (y) / height;
  33460. id += 2;
  33461. }
  33462. }
  33463. };
  33464. // Luminance callback
  33465. var luminanceCallback = function (effect) {
  33466. if (_this._needUpdate) {
  33467. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33468. }
  33469. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33470. effect.setArray2("lumOffsets", luminanceOffsets);
  33471. };
  33472. // Down sample callbacks
  33473. var downSampleCallback = function (indice) {
  33474. var i = indice;
  33475. return function (effect) {
  33476. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33477. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33478. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33479. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33480. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33481. effect.setArray2("dsOffsets", downSampleOffsets);
  33482. };
  33483. };
  33484. var downSampleAfterRenderCallback = function (effect) {
  33485. // Unpack result
  33486. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33487. 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);
  33488. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33489. };
  33490. // Create luminance post-process
  33491. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33492. 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);
  33493. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33494. // Create down sample post-processes
  33495. for (var i = lumSteps - 2; i >= 0; i--) {
  33496. var length = Math.pow(3, i);
  33497. ratio = { width: length, height: length };
  33498. var defines = "#define DOWN_SAMPLE\n";
  33499. if (i === 0) {
  33500. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33501. }
  33502. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33503. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33504. if (i === 0) {
  33505. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33506. }
  33507. }
  33508. };
  33509. /**
  33510. * Gaussian blur post-processes. Horizontal and Vertical
  33511. */
  33512. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33513. var _this = this;
  33514. var blurOffsetsW = new Array(9);
  33515. var blurOffsetsH = new Array(9);
  33516. var blurWeights = new Array(9);
  33517. var uniforms = ["blurOffsets", "blurWeights"];
  33518. // Utils for gaussian blur
  33519. var calculateBlurOffsets = function (height) {
  33520. var lastOutputDimensions = {
  33521. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33522. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33523. };
  33524. for (var i = 0; i < 9; i++) {
  33525. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33526. if (height) {
  33527. blurOffsetsH[i] = value;
  33528. }
  33529. else {
  33530. blurOffsetsW[i] = value;
  33531. }
  33532. }
  33533. };
  33534. var calculateWeights = function () {
  33535. var x = 0.0;
  33536. for (var i = 0; i < 9; i++) {
  33537. x = (i - 4.0) / 4.0;
  33538. 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));
  33539. }
  33540. };
  33541. // Callback
  33542. var gaussianBlurCallback = function (height) {
  33543. return function (effect) {
  33544. if (_this._needUpdate) {
  33545. calculateWeights();
  33546. calculateBlurOffsets(height);
  33547. }
  33548. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33549. effect.setArray("blurWeights", blurWeights);
  33550. };
  33551. };
  33552. // Create horizontal gaussian blur post-processes
  33553. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33554. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33555. // Create vertical gaussian blur post-process
  33556. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33557. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33558. };
  33559. // Luminance generator
  33560. HDRRenderingPipeline.LUM_STEPS = 6;
  33561. return HDRRenderingPipeline;
  33562. })(BABYLON.PostProcessRenderPipeline);
  33563. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33564. })(BABYLON || (BABYLON = {}));
  33565. var BABYLON;
  33566. (function (BABYLON) {
  33567. var FaceAdjacencies = (function () {
  33568. function FaceAdjacencies() {
  33569. this.edges = new Array();
  33570. this.edgesConnectedCount = 0;
  33571. }
  33572. return FaceAdjacencies;
  33573. })();
  33574. var EdgesRenderer = (function () {
  33575. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33576. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33577. if (epsilon === void 0) { epsilon = 0.95; }
  33578. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33579. this._linesPositions = new Array();
  33580. this._linesNormals = new Array();
  33581. this._linesIndices = new Array();
  33582. this._buffers = new Array();
  33583. this._checkVerticesInsteadOfIndices = false;
  33584. this._source = source;
  33585. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33586. this._epsilon = epsilon;
  33587. this._prepareRessources();
  33588. this._generateEdgesLines();
  33589. }
  33590. EdgesRenderer.prototype._prepareRessources = function () {
  33591. if (this._lineShader) {
  33592. return;
  33593. }
  33594. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33595. attributes: ["position", "normal"],
  33596. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33597. });
  33598. this._lineShader.disableDepthWrite = true;
  33599. this._lineShader.backFaceCulling = false;
  33600. };
  33601. EdgesRenderer.prototype.dispose = function () {
  33602. this._vb0.dispose();
  33603. this._vb1.dispose();
  33604. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33605. this._lineShader.dispose();
  33606. };
  33607. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33608. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33609. return 0;
  33610. }
  33611. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33612. return 1;
  33613. }
  33614. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33615. return 2;
  33616. }
  33617. return -1;
  33618. };
  33619. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33620. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33621. return 0;
  33622. }
  33623. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33624. return 1;
  33625. }
  33626. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33627. return 2;
  33628. }
  33629. return -1;
  33630. };
  33631. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33632. var needToCreateLine;
  33633. if (edge === undefined) {
  33634. needToCreateLine = true;
  33635. }
  33636. else {
  33637. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33638. needToCreateLine = dotProduct < this._epsilon;
  33639. }
  33640. if (needToCreateLine) {
  33641. var offset = this._linesPositions.length / 3;
  33642. var normal = p0.subtract(p1);
  33643. normal.normalize();
  33644. // Positions
  33645. this._linesPositions.push(p0.x);
  33646. this._linesPositions.push(p0.y);
  33647. this._linesPositions.push(p0.z);
  33648. this._linesPositions.push(p0.x);
  33649. this._linesPositions.push(p0.y);
  33650. this._linesPositions.push(p0.z);
  33651. this._linesPositions.push(p1.x);
  33652. this._linesPositions.push(p1.y);
  33653. this._linesPositions.push(p1.z);
  33654. this._linesPositions.push(p1.x);
  33655. this._linesPositions.push(p1.y);
  33656. this._linesPositions.push(p1.z);
  33657. // Normals
  33658. this._linesNormals.push(p1.x);
  33659. this._linesNormals.push(p1.y);
  33660. this._linesNormals.push(p1.z);
  33661. this._linesNormals.push(-1);
  33662. this._linesNormals.push(p1.x);
  33663. this._linesNormals.push(p1.y);
  33664. this._linesNormals.push(p1.z);
  33665. this._linesNormals.push(1);
  33666. this._linesNormals.push(p0.x);
  33667. this._linesNormals.push(p0.y);
  33668. this._linesNormals.push(p0.z);
  33669. this._linesNormals.push(-1);
  33670. this._linesNormals.push(p0.x);
  33671. this._linesNormals.push(p0.y);
  33672. this._linesNormals.push(p0.z);
  33673. this._linesNormals.push(1);
  33674. // Indices
  33675. this._linesIndices.push(offset);
  33676. this._linesIndices.push(offset + 1);
  33677. this._linesIndices.push(offset + 2);
  33678. this._linesIndices.push(offset);
  33679. this._linesIndices.push(offset + 2);
  33680. this._linesIndices.push(offset + 3);
  33681. }
  33682. };
  33683. EdgesRenderer.prototype._generateEdgesLines = function () {
  33684. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33685. var indices = this._source.getIndices();
  33686. // First let's find adjacencies
  33687. var adjacencies = new Array();
  33688. var faceNormals = new Array();
  33689. var index;
  33690. var faceAdjacencies;
  33691. // Prepare faces
  33692. for (index = 0; index < indices.length; index += 3) {
  33693. faceAdjacencies = new FaceAdjacencies();
  33694. var p0Index = indices[index];
  33695. var p1Index = indices[index + 1];
  33696. var p2Index = indices[index + 2];
  33697. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33698. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33699. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33700. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33701. faceNormal.normalize();
  33702. faceNormals.push(faceNormal);
  33703. adjacencies.push(faceAdjacencies);
  33704. }
  33705. // Scan
  33706. for (index = 0; index < adjacencies.length; index++) {
  33707. faceAdjacencies = adjacencies[index];
  33708. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33709. var otherFaceAdjacencies = adjacencies[otherIndex];
  33710. if (faceAdjacencies.edgesConnectedCount === 3) {
  33711. break;
  33712. }
  33713. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33714. continue;
  33715. }
  33716. var otherP0 = indices[otherIndex * 3];
  33717. var otherP1 = indices[otherIndex * 3 + 1];
  33718. var otherP2 = indices[otherIndex * 3 + 2];
  33719. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33720. var otherEdgeIndex;
  33721. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33722. continue;
  33723. }
  33724. switch (edgeIndex) {
  33725. case 0:
  33726. if (this._checkVerticesInsteadOfIndices) {
  33727. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33728. }
  33729. else {
  33730. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33731. }
  33732. break;
  33733. case 1:
  33734. if (this._checkVerticesInsteadOfIndices) {
  33735. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33736. }
  33737. else {
  33738. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33739. }
  33740. break;
  33741. case 2:
  33742. if (this._checkVerticesInsteadOfIndices) {
  33743. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33744. }
  33745. else {
  33746. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33747. }
  33748. break;
  33749. }
  33750. if (otherEdgeIndex === -1) {
  33751. continue;
  33752. }
  33753. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33754. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33755. faceAdjacencies.edgesConnectedCount++;
  33756. otherFaceAdjacencies.edgesConnectedCount++;
  33757. if (faceAdjacencies.edgesConnectedCount === 3) {
  33758. break;
  33759. }
  33760. }
  33761. }
  33762. }
  33763. // Create lines
  33764. for (index = 0; index < adjacencies.length; index++) {
  33765. // 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
  33766. var current = adjacencies[index];
  33767. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33768. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33769. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33770. }
  33771. // Merge into a single mesh
  33772. var engine = this._source.getScene().getEngine();
  33773. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33774. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33775. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33776. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33777. this._ib = engine.createIndexBuffer(this._linesIndices);
  33778. this._indicesCount = this._linesIndices.length;
  33779. };
  33780. EdgesRenderer.prototype.render = function () {
  33781. if (!this._lineShader.isReady()) {
  33782. return;
  33783. }
  33784. var scene = this._source.getScene();
  33785. var engine = scene.getEngine();
  33786. this._lineShader._preBind();
  33787. // VBOs
  33788. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33789. scene.resetCachedMaterial();
  33790. this._lineShader.setColor4("color", this._source.edgesColor);
  33791. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33792. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33793. this._lineShader.bind(this._source.getWorldMatrix());
  33794. // Draw order
  33795. engine.draw(true, 0, this._indicesCount);
  33796. this._lineShader.unbind();
  33797. engine.setDepthWrite(true);
  33798. };
  33799. return EdgesRenderer;
  33800. })();
  33801. BABYLON.EdgesRenderer = EdgesRenderer;
  33802. })(BABYLON || (BABYLON = {}));
  33803. var BABYLON;
  33804. (function (BABYLON) {
  33805. (function (TonemappingOperator) {
  33806. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  33807. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  33808. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  33809. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  33810. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  33811. var TonemappingOperator = BABYLON.TonemappingOperator;
  33812. ;
  33813. var TonemapPostProcess = (function (_super) {
  33814. __extends(TonemapPostProcess, _super);
  33815. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  33816. var _this = this;
  33817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33818. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33819. this._operator = operator;
  33820. this._exposureAdjustment = exposureAdjustment;
  33821. var params = ["_ExposureAdjustment"];
  33822. var defines = "#define ";
  33823. if (operator === TonemappingOperator.Hable)
  33824. defines += "HABLE_TONEMAPPING";
  33825. else if (operator === TonemappingOperator.Reinhard)
  33826. defines += "REINHARD_TONEMAPPING";
  33827. else if (operator === TonemappingOperator.HejiDawson)
  33828. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  33829. else if (operator === TonemappingOperator.Photographic)
  33830. defines += "PHOTOGRAPHIC_TONEMAPPING";
  33831. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  33832. this.onApply = function (effect) {
  33833. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  33834. };
  33835. }
  33836. return TonemapPostProcess;
  33837. })(BABYLON.PostProcess);
  33838. BABYLON.TonemapPostProcess = TonemapPostProcess;
  33839. })(BABYLON || (BABYLON = {}));
  33840. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += lightmapColor;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  33841. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r=i.Zero();return i.RotationFromAxisToRef(t,o,n,r),r},i.RotationFromAxisToRef=function(o,n,r,s){var e,a,h,u=i.Normalize(o),l=i.Normalize(r),m=f.X,x=f.Y,y=0,c=0,p=0,z=0,M=0,w=0,d=0,I=-1,D=0,S=0;t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?w=1:t.Tools.WithinEpsilon(l.x,0,t.Engine.Epsilon)?z=1:(d=l.z/l.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),a=new i(z,M,w),a.normalize(),h=i.Cross(l,a),h.normalize(),e=i.Cross(u,a),e.normalize(),i.Dot(l,e)<0&&(I=1),S=i.Dot(u,a),S=Math.min(1,Math.max(-1,S)),p=Math.acos(S)*I,i.Dot(a,m)<0&&(p=Math.PI+p,a=a.scaleInPlace(-1),h=h.scaleInPlace(-1),D++);var v,g;z=0,M=0,w=0,I=-1,t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?z=1:(d=a.z/a.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),v=new i(z,M,w),v.normalize(),g=i.Cross(v,a),g.normalize(),e=i.Cross(l,v),e.normalize(),i.Dot(a,e)<0&&(I=1),S=i.Dot(l,v),S=Math.min(1,Math.max(-1,S)),c=Math.acos(S)*I,i.Dot(g,x)<0&&(c=Math.PI+c,g=g.scaleInPlace(-1),v=v.scaleInPlace(-1),D++),I=-1,e=i.Cross(m,a),e.normalize(),i.Dot(e,x)<0&&(I=1),S=i.Dot(a,m),S=Math.min(1,Math.max(-1,S)),y=-Math.acos(S)*I,0>S&&2>D&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return i.normalize(),n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i,o){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=o||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._raw||this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  33842. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33843. module.exports = BABYLON;
  33844. };