babylon.max.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  807. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  808. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  809. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  810. vector = vector.scale(1.0 / num);
  811. }
  812. return vector;
  813. };
  814. Vector3.Minimize = function (left, right) {
  815. var min = left.clone();
  816. min.MinimizeInPlace(right);
  817. return min;
  818. };
  819. Vector3.Maximize = function (left, right) {
  820. var max = left.clone();
  821. max.MaximizeInPlace(right);
  822. return max;
  823. };
  824. Vector3.Distance = function (value1, value2) {
  825. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  826. };
  827. Vector3.DistanceSquared = function (value1, value2) {
  828. var x = value1.x - value2.x;
  829. var y = value1.y - value2.y;
  830. var z = value1.z - value2.z;
  831. return (x * x) + (y * y) + (z * z);
  832. };
  833. Vector3.Center = function (value1, value2) {
  834. var center = value1.add(value2);
  835. center.scaleInPlace(0.5);
  836. return center;
  837. };
  838. /**
  839. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  840. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  841. * to something in order to rotate it from its local system to the given target system.
  842. */
  843. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  844. var rotation = Vector3.Zero();
  845. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  846. return rotation;
  847. };
  848. /**
  849. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  850. */
  851. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  852. var u = Vector3.Normalize(axis1);
  853. var w = Vector3.Normalize(axis3);
  854. // world axis
  855. var X = Axis.X;
  856. var Y = Axis.Y;
  857. // equation unknowns and vars
  858. var yaw = 0.0;
  859. var pitch = 0.0;
  860. var roll = 0.0;
  861. var x = 0.0;
  862. var y = 0.0;
  863. var z = 0.0;
  864. var t = 0.0;
  865. var sign = -1.0;
  866. var nbRevert = 0;
  867. var cross;
  868. var dot = 0.0;
  869. // step 1 : rotation around w
  870. // Rv3(u) = u1, and u1 belongs to plane xOz
  871. // Rv3(w) = w1 = w invariant
  872. var u1;
  873. var v1;
  874. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  875. z = 1.0;
  876. }
  877. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  878. x = 1.0;
  879. }
  880. else {
  881. t = w.z / w.x;
  882. x = -t * Math.sqrt(1 / (1 + t * t));
  883. z = Math.sqrt(1 / (1 + t * t));
  884. }
  885. u1 = new Vector3(x, y, z);
  886. u1.normalize();
  887. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  888. v1.normalize();
  889. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  890. cross.normalize();
  891. if (Vector3.Dot(w, cross) < 0) {
  892. sign = 1.0;
  893. }
  894. dot = Vector3.Dot(u, u1);
  895. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  896. roll = Math.acos(dot) * sign;
  897. if (Vector3.Dot(u1, X) < 0) {
  898. roll = Math.PI + roll;
  899. u1 = u1.scaleInPlace(-1);
  900. v1 = v1.scaleInPlace(-1);
  901. nbRevert++;
  902. }
  903. // step 2 : rotate around u1
  904. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  905. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  906. var w2;
  907. var v2;
  908. x = 0.0;
  909. y = 0.0;
  910. z = 0.0;
  911. sign = -1;
  912. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  913. x = 1.0;
  914. }
  915. else {
  916. t = u1.z / u1.x;
  917. x = -t * Math.sqrt(1 / (1 + t * t));
  918. z = Math.sqrt(1 / (1 + t * t));
  919. }
  920. w2 = new Vector3(x, y, z);
  921. w2.normalize();
  922. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  923. v2.normalize();
  924. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  925. cross.normalize();
  926. if (Vector3.Dot(u1, cross) < 0) {
  927. sign = 1.0;
  928. }
  929. dot = Vector3.Dot(w, w2);
  930. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  931. pitch = Math.acos(dot) * sign;
  932. if (Vector3.Dot(v2, Y) < 0) {
  933. pitch = Math.PI + pitch;
  934. v2 = v2.scaleInPlace(-1);
  935. w2 = w2.scaleInPlace(-1);
  936. nbRevert++;
  937. }
  938. // step 3 : rotate around v2
  939. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  940. sign = -1;
  941. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(cross, Y) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(u1, X);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  949. if (dot < 0 && nbRevert < 2) {
  950. yaw = Math.PI + yaw;
  951. }
  952. ref.x = pitch;
  953. ref.y = yaw;
  954. ref.z = roll;
  955. };
  956. return Vector3;
  957. })();
  958. BABYLON.Vector3 = Vector3;
  959. //Vector4 class created for EulerAngle class conversion to Quaternion
  960. var Vector4 = (function () {
  961. function Vector4(x, y, z, w) {
  962. this.x = x;
  963. this.y = y;
  964. this.z = z;
  965. this.w = w;
  966. }
  967. Vector4.prototype.toString = function () {
  968. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  969. };
  970. // Operators
  971. Vector4.prototype.asArray = function () {
  972. var result = [];
  973. this.toArray(result, 0);
  974. return result;
  975. };
  976. Vector4.prototype.toArray = function (array, index) {
  977. if (index === undefined) {
  978. index = 0;
  979. }
  980. array[index] = this.x;
  981. array[index + 1] = this.y;
  982. array[index + 2] = this.z;
  983. array[index + 3] = this.w;
  984. return this;
  985. };
  986. Vector4.prototype.addInPlace = function (otherVector) {
  987. this.x += otherVector.x;
  988. this.y += otherVector.y;
  989. this.z += otherVector.z;
  990. this.w += otherVector.w;
  991. return this;
  992. };
  993. Vector4.prototype.add = function (otherVector) {
  994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  995. };
  996. Vector4.prototype.addToRef = function (otherVector, result) {
  997. result.x = this.x + otherVector.x;
  998. result.y = this.y + otherVector.y;
  999. result.z = this.z + otherVector.z;
  1000. result.w = this.w + otherVector.w;
  1001. return this;
  1002. };
  1003. Vector4.prototype.subtractInPlace = function (otherVector) {
  1004. this.x -= otherVector.x;
  1005. this.y -= otherVector.y;
  1006. this.z -= otherVector.z;
  1007. this.w -= otherVector.w;
  1008. return this;
  1009. };
  1010. Vector4.prototype.subtract = function (otherVector) {
  1011. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1012. };
  1013. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1014. result.x = this.x - otherVector.x;
  1015. result.y = this.y - otherVector.y;
  1016. result.z = this.z - otherVector.z;
  1017. result.w = this.w - otherVector.w;
  1018. return this;
  1019. };
  1020. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1021. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1022. };
  1023. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1024. result.x = this.x - x;
  1025. result.y = this.y - y;
  1026. result.z = this.z - z;
  1027. result.w = this.w - w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.negate = function () {
  1031. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1032. };
  1033. Vector4.prototype.scaleInPlace = function (scale) {
  1034. this.x *= scale;
  1035. this.y *= scale;
  1036. this.z *= scale;
  1037. this.w *= scale;
  1038. return this;
  1039. };
  1040. Vector4.prototype.scale = function (scale) {
  1041. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1042. };
  1043. Vector4.prototype.scaleToRef = function (scale, result) {
  1044. result.x = this.x * scale;
  1045. result.y = this.y * scale;
  1046. result.z = this.z * scale;
  1047. result.w = this.w * scale;
  1048. };
  1049. Vector4.prototype.equals = function (otherVector) {
  1050. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1051. };
  1052. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1053. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1054. return otherVector
  1055. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1056. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1057. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1059. };
  1060. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1061. return this.x === x && this.y === y && this.z === z && this.w === w;
  1062. };
  1063. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1064. this.x *= otherVector.x;
  1065. this.y *= otherVector.y;
  1066. this.z *= otherVector.z;
  1067. this.w *= otherVector.w;
  1068. return this;
  1069. };
  1070. Vector4.prototype.multiply = function (otherVector) {
  1071. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1072. };
  1073. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1074. result.x = this.x * otherVector.x;
  1075. result.y = this.y * otherVector.y;
  1076. result.z = this.z * otherVector.z;
  1077. result.w = this.w * otherVector.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1082. };
  1083. Vector4.prototype.divide = function (otherVector) {
  1084. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1085. };
  1086. Vector4.prototype.divideToRef = function (otherVector, result) {
  1087. result.x = this.x / otherVector.x;
  1088. result.y = this.y / otherVector.y;
  1089. result.z = this.z / otherVector.z;
  1090. result.w = this.w / otherVector.w;
  1091. return this;
  1092. };
  1093. Vector4.prototype.MinimizeInPlace = function (other) {
  1094. if (other.x < this.x)
  1095. this.x = other.x;
  1096. if (other.y < this.y)
  1097. this.y = other.y;
  1098. if (other.z < this.z)
  1099. this.z = other.z;
  1100. if (other.w < this.w)
  1101. this.w = other.w;
  1102. return this;
  1103. };
  1104. Vector4.prototype.MaximizeInPlace = function (other) {
  1105. if (other.x > this.x)
  1106. this.x = other.x;
  1107. if (other.y > this.y)
  1108. this.y = other.y;
  1109. if (other.z > this.z)
  1110. this.z = other.z;
  1111. if (other.w > this.w)
  1112. this.w = other.w;
  1113. return this;
  1114. };
  1115. // Properties
  1116. Vector4.prototype.length = function () {
  1117. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1118. };
  1119. Vector4.prototype.lengthSquared = function () {
  1120. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1121. };
  1122. // Methods
  1123. Vector4.prototype.normalize = function () {
  1124. var len = this.length();
  1125. if (len === 0)
  1126. return this;
  1127. var num = 1.0 / len;
  1128. this.x *= num;
  1129. this.y *= num;
  1130. this.z *= num;
  1131. this.w *= num;
  1132. return this;
  1133. };
  1134. Vector4.prototype.clone = function () {
  1135. return new Vector4(this.x, this.y, this.z, this.w);
  1136. };
  1137. Vector4.prototype.copyFrom = function (source) {
  1138. this.x = source.x;
  1139. this.y = source.y;
  1140. this.z = source.z;
  1141. this.w = source.w;
  1142. return this;
  1143. };
  1144. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1145. this.x = x;
  1146. this.y = y;
  1147. this.z = z;
  1148. this.w = w;
  1149. return this;
  1150. };
  1151. // Statics
  1152. Vector4.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Vector4.FromArrayToRef = function (array, offset, result) {
  1159. result.x = array[offset];
  1160. result.y = array[offset + 1];
  1161. result.z = array[offset + 2];
  1162. result.w = array[offset + 3];
  1163. };
  1164. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1165. result.x = array[offset];
  1166. result.y = array[offset + 1];
  1167. result.z = array[offset + 2];
  1168. result.w = array[offset + 3];
  1169. };
  1170. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1171. result.x = x;
  1172. result.y = y;
  1173. result.z = z;
  1174. result.w = w;
  1175. };
  1176. Vector4.Zero = function () {
  1177. return new Vector4(0, 0, 0, 0);
  1178. };
  1179. Vector4.Normalize = function (vector) {
  1180. var result = Vector4.Zero();
  1181. Vector4.NormalizeToRef(vector, result);
  1182. return result;
  1183. };
  1184. Vector4.NormalizeToRef = function (vector, result) {
  1185. result.copyFrom(vector);
  1186. result.normalize();
  1187. };
  1188. Vector4.Minimize = function (left, right) {
  1189. var min = left.clone();
  1190. min.MinimizeInPlace(right);
  1191. return min;
  1192. };
  1193. Vector4.Maximize = function (left, right) {
  1194. var max = left.clone();
  1195. max.MaximizeInPlace(right);
  1196. return max;
  1197. };
  1198. Vector4.Distance = function (value1, value2) {
  1199. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1200. };
  1201. Vector4.DistanceSquared = function (value1, value2) {
  1202. var x = value1.x - value2.x;
  1203. var y = value1.y - value2.y;
  1204. var z = value1.z - value2.z;
  1205. var w = value1.w - value2.w;
  1206. return (x * x) + (y * y) + (z * z) + (w * w);
  1207. };
  1208. Vector4.Center = function (value1, value2) {
  1209. var center = value1.add(value2);
  1210. center.scaleInPlace(0.5);
  1211. return center;
  1212. };
  1213. return Vector4;
  1214. })();
  1215. BABYLON.Vector4 = Vector4;
  1216. var Quaternion = (function () {
  1217. function Quaternion(x, y, z, w) {
  1218. if (x === void 0) { x = 0; }
  1219. if (y === void 0) { y = 0; }
  1220. if (z === void 0) { z = 0; }
  1221. if (w === void 0) { w = 1; }
  1222. this.x = x;
  1223. this.y = y;
  1224. this.z = z;
  1225. this.w = w;
  1226. }
  1227. Quaternion.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1229. };
  1230. Quaternion.prototype.asArray = function () {
  1231. return [this.x, this.y, this.z, this.w];
  1232. };
  1233. Quaternion.prototype.equals = function (otherQuaternion) {
  1234. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1235. };
  1236. Quaternion.prototype.clone = function () {
  1237. return new Quaternion(this.x, this.y, this.z, this.w);
  1238. };
  1239. Quaternion.prototype.copyFrom = function (other) {
  1240. this.x = other.x;
  1241. this.y = other.y;
  1242. this.z = other.z;
  1243. this.w = other.w;
  1244. return this;
  1245. };
  1246. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. };
  1253. Quaternion.prototype.add = function (other) {
  1254. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1255. };
  1256. Quaternion.prototype.subtract = function (other) {
  1257. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1258. };
  1259. Quaternion.prototype.scale = function (value) {
  1260. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1261. };
  1262. Quaternion.prototype.multiply = function (q1) {
  1263. var result = new Quaternion(0, 0, 0, 1.0);
  1264. this.multiplyToRef(q1, result);
  1265. return result;
  1266. };
  1267. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1268. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1269. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1270. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1271. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1272. result.copyFromFloats(x, y, z, w);
  1273. return this;
  1274. };
  1275. Quaternion.prototype.length = function () {
  1276. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1277. };
  1278. Quaternion.prototype.normalize = function () {
  1279. var length = 1.0 / this.length();
  1280. this.x *= length;
  1281. this.y *= length;
  1282. this.z *= length;
  1283. this.w *= length;
  1284. return this;
  1285. };
  1286. Quaternion.prototype.toEulerAngles = function () {
  1287. var result = Vector3.Zero();
  1288. this.toEulerAnglesToRef(result);
  1289. return result;
  1290. };
  1291. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1292. //result is an EulerAngles in the in the z-x-z convention
  1293. var qx = this.x;
  1294. var qy = this.y;
  1295. var qz = this.z;
  1296. var qw = this.w;
  1297. var qxy = qx * qy;
  1298. var qxz = qx * qz;
  1299. var qwy = qw * qy;
  1300. var qwz = qw * qz;
  1301. var qwx = qw * qx;
  1302. var qyz = qy * qz;
  1303. var sqx = qx * qx;
  1304. var sqy = qy * qy;
  1305. var determinant = sqx + sqy;
  1306. if (determinant !== 0.000 && determinant !== 1.000) {
  1307. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1308. result.y = Math.acos(1 - 2 * determinant);
  1309. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1310. }
  1311. else {
  1312. if (determinant === 0.0) {
  1313. result.x = 0.0;
  1314. result.y = 0.0;
  1315. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1316. }
  1317. else {
  1318. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1319. result.y = Math.PI;
  1320. result.z = 0.0;
  1321. }
  1322. }
  1323. return this;
  1324. };
  1325. Quaternion.prototype.toRotationMatrix = function (result) {
  1326. var xx = this.x * this.x;
  1327. var yy = this.y * this.y;
  1328. var zz = this.z * this.z;
  1329. var xy = this.x * this.y;
  1330. var zw = this.z * this.w;
  1331. var zx = this.z * this.x;
  1332. var yw = this.y * this.w;
  1333. var yz = this.y * this.z;
  1334. var xw = this.x * this.w;
  1335. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1336. result.m[1] = 2.0 * (xy + zw);
  1337. result.m[2] = 2.0 * (zx - yw);
  1338. result.m[3] = 0;
  1339. result.m[4] = 2.0 * (xy - zw);
  1340. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1341. result.m[6] = 2.0 * (yz + xw);
  1342. result.m[7] = 0;
  1343. result.m[8] = 2.0 * (zx + yw);
  1344. result.m[9] = 2.0 * (yz - xw);
  1345. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1346. result.m[11] = 0;
  1347. result.m[12] = 0;
  1348. result.m[13] = 0;
  1349. result.m[14] = 0;
  1350. result.m[15] = 1.0;
  1351. return this;
  1352. };
  1353. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1354. Quaternion.FromRotationMatrixToRef(matrix, this);
  1355. return this;
  1356. };
  1357. // Statics
  1358. Quaternion.FromRotationMatrix = function (matrix) {
  1359. var result = new Quaternion();
  1360. Quaternion.FromRotationMatrixToRef(matrix, result);
  1361. return result;
  1362. };
  1363. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1364. var data = matrix.m;
  1365. var m11 = data[0], m12 = data[4], m13 = data[8];
  1366. var m21 = data[1], m22 = data[5], m23 = data[9];
  1367. var m31 = data[2], m32 = data[6], m33 = data[10];
  1368. var trace = m11 + m22 + m33;
  1369. var s;
  1370. if (trace > 0) {
  1371. s = 0.5 / Math.sqrt(trace + 1.0);
  1372. result.w = 0.25 / s;
  1373. result.x = (m32 - m23) * s;
  1374. result.y = (m13 - m31) * s;
  1375. result.z = (m21 - m12) * s;
  1376. }
  1377. else if (m11 > m22 && m11 > m33) {
  1378. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1379. result.w = (m32 - m23) / s;
  1380. result.x = 0.25 * s;
  1381. result.y = (m12 + m21) / s;
  1382. result.z = (m13 + m31) / s;
  1383. }
  1384. else if (m22 > m33) {
  1385. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1386. result.w = (m13 - m31) / s;
  1387. result.x = (m12 + m21) / s;
  1388. result.y = 0.25 * s;
  1389. result.z = (m23 + m32) / s;
  1390. }
  1391. else {
  1392. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1393. result.w = (m21 - m12) / s;
  1394. result.x = (m13 + m31) / s;
  1395. result.y = (m23 + m32) / s;
  1396. result.z = 0.25 * s;
  1397. }
  1398. };
  1399. Quaternion.Inverse = function (q) {
  1400. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1401. };
  1402. Quaternion.Identity = function () {
  1403. return new Quaternion(0, 0, 0, 1);
  1404. };
  1405. Quaternion.RotationAxis = function (axis, angle) {
  1406. var result = new Quaternion();
  1407. var sin = Math.sin(angle / 2);
  1408. axis.normalize();
  1409. result.w = Math.cos(angle / 2);
  1410. result.x = axis.x * sin;
  1411. result.y = axis.y * sin;
  1412. result.z = axis.z * sin;
  1413. return result;
  1414. };
  1415. Quaternion.FromArray = function (array, offset) {
  1416. if (!offset) {
  1417. offset = 0;
  1418. }
  1419. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1420. };
  1421. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1422. var result = new Quaternion();
  1423. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1424. return result;
  1425. };
  1426. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1427. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1428. var halfRoll = roll * 0.5;
  1429. var halfPitch = pitch * 0.5;
  1430. var halfYaw = yaw * 0.5;
  1431. var sinRoll = Math.sin(halfRoll);
  1432. var cosRoll = Math.cos(halfRoll);
  1433. var sinPitch = Math.sin(halfPitch);
  1434. var cosPitch = Math.cos(halfPitch);
  1435. var sinYaw = Math.sin(halfYaw);
  1436. var cosYaw = Math.cos(halfYaw);
  1437. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1438. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1439. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1440. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1441. };
  1442. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1448. // Produces a quaternion from Euler angles in the z-x-z orientation
  1449. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1450. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1451. var halfBeta = beta * 0.5;
  1452. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1453. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1454. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1455. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1456. };
  1457. Quaternion.Slerp = function (left, right, amount) {
  1458. var num2;
  1459. var num3;
  1460. var num = amount;
  1461. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1462. var flag = false;
  1463. if (num4 < 0) {
  1464. flag = true;
  1465. num4 = -num4;
  1466. }
  1467. if (num4 > 0.999999) {
  1468. num3 = 1 - num;
  1469. num2 = flag ? -num : num;
  1470. }
  1471. else {
  1472. var num5 = Math.acos(num4);
  1473. var num6 = (1.0 / Math.sin(num5));
  1474. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1475. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1476. }
  1477. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1478. };
  1479. return Quaternion;
  1480. })();
  1481. BABYLON.Quaternion = Quaternion;
  1482. var Matrix = (function () {
  1483. function Matrix() {
  1484. this.m = new Float32Array(16);
  1485. }
  1486. // Properties
  1487. Matrix.prototype.isIdentity = function () {
  1488. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1489. return false;
  1490. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1491. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1492. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1493. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1494. return false;
  1495. return true;
  1496. };
  1497. Matrix.prototype.determinant = function () {
  1498. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1499. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1500. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1501. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1502. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1503. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1504. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1505. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1506. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1507. };
  1508. // Methods
  1509. Matrix.prototype.toArray = function () {
  1510. return this.m;
  1511. };
  1512. Matrix.prototype.asArray = function () {
  1513. return this.toArray();
  1514. };
  1515. Matrix.prototype.invert = function () {
  1516. this.invertToRef(this);
  1517. return this;
  1518. };
  1519. Matrix.prototype.reset = function () {
  1520. for (var index = 0; index < 16; index++) {
  1521. this.m[index] = 0;
  1522. }
  1523. return this;
  1524. };
  1525. Matrix.prototype.add = function (other) {
  1526. var result = new Matrix();
  1527. this.addToRef(other, result);
  1528. return result;
  1529. };
  1530. Matrix.prototype.addToRef = function (other, result) {
  1531. for (var index = 0; index < 16; index++) {
  1532. result.m[index] = this.m[index] + other.m[index];
  1533. }
  1534. return this;
  1535. };
  1536. Matrix.prototype.addToSelf = function (other) {
  1537. for (var index = 0; index < 16; index++) {
  1538. this.m[index] += other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.invertToRef = function (other) {
  1543. var l1 = this.m[0];
  1544. var l2 = this.m[1];
  1545. var l3 = this.m[2];
  1546. var l4 = this.m[3];
  1547. var l5 = this.m[4];
  1548. var l6 = this.m[5];
  1549. var l7 = this.m[6];
  1550. var l8 = this.m[7];
  1551. var l9 = this.m[8];
  1552. var l10 = this.m[9];
  1553. var l11 = this.m[10];
  1554. var l12 = this.m[11];
  1555. var l13 = this.m[12];
  1556. var l14 = this.m[13];
  1557. var l15 = this.m[14];
  1558. var l16 = this.m[15];
  1559. var l17 = (l11 * l16) - (l12 * l15);
  1560. var l18 = (l10 * l16) - (l12 * l14);
  1561. var l19 = (l10 * l15) - (l11 * l14);
  1562. var l20 = (l9 * l16) - (l12 * l13);
  1563. var l21 = (l9 * l15) - (l11 * l13);
  1564. var l22 = (l9 * l14) - (l10 * l13);
  1565. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1566. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1567. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1568. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1569. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1570. var l28 = (l7 * l16) - (l8 * l15);
  1571. var l29 = (l6 * l16) - (l8 * l14);
  1572. var l30 = (l6 * l15) - (l7 * l14);
  1573. var l31 = (l5 * l16) - (l8 * l13);
  1574. var l32 = (l5 * l15) - (l7 * l13);
  1575. var l33 = (l5 * l14) - (l6 * l13);
  1576. var l34 = (l7 * l12) - (l8 * l11);
  1577. var l35 = (l6 * l12) - (l8 * l10);
  1578. var l36 = (l6 * l11) - (l7 * l10);
  1579. var l37 = (l5 * l12) - (l8 * l9);
  1580. var l38 = (l5 * l11) - (l7 * l9);
  1581. var l39 = (l5 * l10) - (l6 * l9);
  1582. other.m[0] = l23 * l27;
  1583. other.m[4] = l24 * l27;
  1584. other.m[8] = l25 * l27;
  1585. other.m[12] = l26 * l27;
  1586. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1587. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1588. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1589. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1590. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1591. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1592. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1593. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1594. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1595. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1596. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1597. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1598. return this;
  1599. };
  1600. Matrix.prototype.invertToRefSIMD = function (other) {
  1601. var src = this.m;
  1602. var dest = other.m;
  1603. var row0, row1, row2, row3;
  1604. var tmp1;
  1605. var minor0, minor1, minor2, minor3;
  1606. var det;
  1607. // Load the 4 rows
  1608. var src0 = SIMD.float32x4.load(src, 0);
  1609. var src1 = SIMD.float32x4.load(src, 4);
  1610. var src2 = SIMD.float32x4.load(src, 8);
  1611. var src3 = SIMD.float32x4.load(src, 12);
  1612. // Transpose the source matrix. Sort of. Not a true transpose operation
  1613. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1614. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1615. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1616. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1617. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1618. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1619. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1620. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1621. // This is a true transposition, but it will lead to an incorrect result
  1622. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1623. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1624. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1625. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1626. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1627. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1628. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1629. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1630. // ----
  1631. tmp1 = SIMD.float32x4.mul(row2, row3);
  1632. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1633. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1634. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1635. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1636. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1637. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1638. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1639. // ----
  1640. tmp1 = SIMD.float32x4.mul(row1, row2);
  1641. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1643. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1646. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1647. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1652. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1653. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1654. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1655. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1656. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1657. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1658. // ----
  1659. tmp1 = SIMD.float32x4.mul(row0, row1);
  1660. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1661. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1662. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1663. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1664. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1665. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1666. // ----
  1667. tmp1 = SIMD.float32x4.mul(row0, row3);
  1668. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1669. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1670. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1671. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1672. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1673. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1674. // ----
  1675. tmp1 = SIMD.float32x4.mul(row0, row2);
  1676. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1677. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1678. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1679. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1680. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1681. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1682. // Compute determinant
  1683. det = SIMD.float32x4.mul(row0, minor0);
  1684. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1685. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1686. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1687. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1688. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1689. // These shuffles aren't necessary if the faulty transposition is done
  1690. // up at the top of this function.
  1691. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1692. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1693. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1694. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1695. // Compute final values by multiplying with 1/det
  1696. minor0 = SIMD.float32x4.mul(det, minor0);
  1697. minor1 = SIMD.float32x4.mul(det, minor1);
  1698. minor2 = SIMD.float32x4.mul(det, minor2);
  1699. minor3 = SIMD.float32x4.mul(det, minor3);
  1700. SIMD.float32x4.store(dest, 0, minor0);
  1701. SIMD.float32x4.store(dest, 4, minor1);
  1702. SIMD.float32x4.store(dest, 8, minor2);
  1703. SIMD.float32x4.store(dest, 12, minor3);
  1704. return this;
  1705. };
  1706. Matrix.prototype.setTranslation = function (vector3) {
  1707. this.m[12] = vector3.x;
  1708. this.m[13] = vector3.y;
  1709. this.m[14] = vector3.z;
  1710. return this;
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1786. if (offset === void 0) { offset = 0; }
  1787. var tm = this.m;
  1788. var om = other.m;
  1789. var om0 = SIMD.float32x4.load(om, 0);
  1790. var om1 = SIMD.float32x4.load(om, 4);
  1791. var om2 = SIMD.float32x4.load(om, 8);
  1792. var om3 = SIMD.float32x4.load(om, 12);
  1793. var tm0 = SIMD.float32x4.load(tm, 0);
  1794. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1795. var tm1 = SIMD.float32x4.load(tm, 4);
  1796. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1797. var tm2 = SIMD.float32x4.load(tm, 8);
  1798. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1799. var tm3 = SIMD.float32x4.load(tm, 12);
  1800. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1801. };
  1802. Matrix.prototype.equals = function (value) {
  1803. return value &&
  1804. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1805. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1806. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1807. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1808. };
  1809. Matrix.prototype.clone = function () {
  1810. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1811. };
  1812. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1813. translation.x = this.m[12];
  1814. translation.y = this.m[13];
  1815. translation.z = this.m[14];
  1816. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1817. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1818. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1819. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1820. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1821. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1822. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1823. rotation.x = 0;
  1824. rotation.y = 0;
  1825. rotation.z = 0;
  1826. rotation.w = 1;
  1827. return false;
  1828. }
  1829. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1830. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1831. return true;
  1832. };
  1833. // Statics
  1834. Matrix.FromArray = function (array, offset) {
  1835. var result = new Matrix();
  1836. if (!offset) {
  1837. offset = 0;
  1838. }
  1839. Matrix.FromArrayToRef(array, offset, result);
  1840. return result;
  1841. };
  1842. Matrix.FromArrayToRef = function (array, offset, result) {
  1843. for (var index = 0; index < 16; index++) {
  1844. result.m[index] = array[index + offset];
  1845. }
  1846. };
  1847. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1848. for (var index = 0; index < 16; index++) {
  1849. result.m[index] = array[index + offset] * scale;
  1850. }
  1851. };
  1852. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1853. result.m[0] = initialM11;
  1854. result.m[1] = initialM12;
  1855. result.m[2] = initialM13;
  1856. result.m[3] = initialM14;
  1857. result.m[4] = initialM21;
  1858. result.m[5] = initialM22;
  1859. result.m[6] = initialM23;
  1860. result.m[7] = initialM24;
  1861. result.m[8] = initialM31;
  1862. result.m[9] = initialM32;
  1863. result.m[10] = initialM33;
  1864. result.m[11] = initialM34;
  1865. result.m[12] = initialM41;
  1866. result.m[13] = initialM42;
  1867. result.m[14] = initialM43;
  1868. result.m[15] = initialM44;
  1869. };
  1870. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1871. var result = new Matrix();
  1872. result.m[0] = initialM11;
  1873. result.m[1] = initialM12;
  1874. result.m[2] = initialM13;
  1875. result.m[3] = initialM14;
  1876. result.m[4] = initialM21;
  1877. result.m[5] = initialM22;
  1878. result.m[6] = initialM23;
  1879. result.m[7] = initialM24;
  1880. result.m[8] = initialM31;
  1881. result.m[9] = initialM32;
  1882. result.m[10] = initialM33;
  1883. result.m[11] = initialM34;
  1884. result.m[12] = initialM41;
  1885. result.m[13] = initialM42;
  1886. result.m[14] = initialM43;
  1887. result.m[15] = initialM44;
  1888. return result;
  1889. };
  1890. Matrix.Compose = function (scale, rotation, translation) {
  1891. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1892. var rotationMatrix = Matrix.Identity();
  1893. rotation.toRotationMatrix(rotationMatrix);
  1894. result = result.multiply(rotationMatrix);
  1895. result.setTranslation(translation);
  1896. return result;
  1897. };
  1898. Matrix.Identity = function () {
  1899. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1900. };
  1901. Matrix.IdentityToRef = function (result) {
  1902. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1903. };
  1904. Matrix.Zero = function () {
  1905. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1906. };
  1907. Matrix.RotationX = function (angle) {
  1908. var result = new Matrix();
  1909. Matrix.RotationXToRef(angle, result);
  1910. return result;
  1911. };
  1912. Matrix.Invert = function (source) {
  1913. var result = new Matrix();
  1914. source.invertToRef(result);
  1915. return result;
  1916. };
  1917. Matrix.RotationXToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[0] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[5] = c;
  1923. result.m[10] = c;
  1924. result.m[9] = -s;
  1925. result.m[6] = s;
  1926. result.m[1] = 0;
  1927. result.m[2] = 0;
  1928. result.m[3] = 0;
  1929. result.m[4] = 0;
  1930. result.m[7] = 0;
  1931. result.m[8] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationY = function (angle) {
  1938. var result = new Matrix();
  1939. Matrix.RotationYToRef(angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationYToRef = function (angle, result) {
  1943. var s = Math.sin(angle);
  1944. var c = Math.cos(angle);
  1945. result.m[5] = 1.0;
  1946. result.m[15] = 1.0;
  1947. result.m[0] = c;
  1948. result.m[2] = -s;
  1949. result.m[8] = s;
  1950. result.m[10] = c;
  1951. result.m[1] = 0;
  1952. result.m[3] = 0;
  1953. result.m[4] = 0;
  1954. result.m[6] = 0;
  1955. result.m[7] = 0;
  1956. result.m[9] = 0;
  1957. result.m[11] = 0;
  1958. result.m[12] = 0;
  1959. result.m[13] = 0;
  1960. result.m[14] = 0;
  1961. };
  1962. Matrix.RotationZ = function (angle) {
  1963. var result = new Matrix();
  1964. Matrix.RotationZToRef(angle, result);
  1965. return result;
  1966. };
  1967. Matrix.RotationZToRef = function (angle, result) {
  1968. var s = Math.sin(angle);
  1969. var c = Math.cos(angle);
  1970. result.m[10] = 1.0;
  1971. result.m[15] = 1.0;
  1972. result.m[0] = c;
  1973. result.m[1] = s;
  1974. result.m[4] = -s;
  1975. result.m[5] = c;
  1976. result.m[2] = 0;
  1977. result.m[3] = 0;
  1978. result.m[6] = 0;
  1979. result.m[7] = 0;
  1980. result.m[8] = 0;
  1981. result.m[9] = 0;
  1982. result.m[11] = 0;
  1983. result.m[12] = 0;
  1984. result.m[13] = 0;
  1985. result.m[14] = 0;
  1986. };
  1987. Matrix.RotationAxis = function (axis, angle) {
  1988. var result = Matrix.Zero();
  1989. Matrix.RotationAxisToRef(axis, angle, result);
  1990. return result;
  1991. };
  1992. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1993. var s = Math.sin(-angle);
  1994. var c = Math.cos(-angle);
  1995. var c1 = 1 - c;
  1996. axis.normalize();
  1997. result.m[0] = (axis.x * axis.x) * c1 + c;
  1998. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1999. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2000. result.m[3] = 0.0;
  2001. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2002. result.m[5] = (axis.y * axis.y) * c1 + c;
  2003. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2004. result.m[7] = 0.0;
  2005. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2006. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2007. result.m[10] = (axis.z * axis.z) * c1 + c;
  2008. result.m[11] = 0.0;
  2009. result.m[15] = 1.0;
  2010. };
  2011. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2012. var result = new Matrix();
  2013. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2014. return result;
  2015. };
  2016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2018. this._tempQuaternion.toRotationMatrix(result);
  2019. };
  2020. Matrix.Scaling = function (x, y, z) {
  2021. var result = Matrix.Zero();
  2022. Matrix.ScalingToRef(x, y, z, result);
  2023. return result;
  2024. };
  2025. Matrix.ScalingToRef = function (x, y, z, result) {
  2026. result.m[0] = x;
  2027. result.m[1] = 0;
  2028. result.m[2] = 0;
  2029. result.m[3] = 0;
  2030. result.m[4] = 0;
  2031. result.m[5] = y;
  2032. result.m[6] = 0;
  2033. result.m[7] = 0;
  2034. result.m[8] = 0;
  2035. result.m[9] = 0;
  2036. result.m[10] = z;
  2037. result.m[11] = 0;
  2038. result.m[12] = 0;
  2039. result.m[13] = 0;
  2040. result.m[14] = 0;
  2041. result.m[15] = 1.0;
  2042. };
  2043. Matrix.Translation = function (x, y, z) {
  2044. var result = Matrix.Identity();
  2045. Matrix.TranslationToRef(x, y, z, result);
  2046. return result;
  2047. };
  2048. Matrix.TranslationToRef = function (x, y, z, result) {
  2049. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2050. };
  2051. Matrix.LookAtLH = function (eye, target, up) {
  2052. var result = Matrix.Zero();
  2053. Matrix.LookAtLHToRef(eye, target, up, result);
  2054. return result;
  2055. };
  2056. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2057. // Z axis
  2058. target.subtractToRef(eye, this._zAxis);
  2059. this._zAxis.normalize();
  2060. // X axis
  2061. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2062. if (this._xAxis.lengthSquared() === 0) {
  2063. this._xAxis.x = 1.0;
  2064. }
  2065. else {
  2066. this._xAxis.normalize();
  2067. }
  2068. // Y axis
  2069. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2070. this._yAxis.normalize();
  2071. // Eye angles
  2072. var ex = -Vector3.Dot(this._xAxis, eye);
  2073. var ey = -Vector3.Dot(this._yAxis, eye);
  2074. var ez = -Vector3.Dot(this._zAxis, eye);
  2075. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2076. };
  2077. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2078. var out = result.m;
  2079. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2080. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2081. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2082. // cc.kmVec3Subtract(f, pCenter, pEye);
  2083. var f = SIMD.float32x4.sub(center, eye);
  2084. // cc.kmVec3Normalize(f, f);
  2085. var tmp = SIMD.float32x4.mul(f, f);
  2086. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2087. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2088. // cc.kmVec3Assign(up, pUp);
  2089. // cc.kmVec3Normalize(up, up);
  2090. tmp = SIMD.float32x4.mul(up, up);
  2091. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2092. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2093. // cc.kmVec3Cross(s, f, up);
  2094. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2095. // cc.kmVec3Normalize(s, s);
  2096. tmp = SIMD.float32x4.mul(s, s);
  2097. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2098. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2099. // cc.kmVec3Cross(u, s, f);
  2100. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2101. // cc.kmVec3Normalize(s, s);
  2102. tmp = SIMD.float32x4.mul(s, s);
  2103. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2104. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2105. var zero = SIMD.float32x4.splat(0.0);
  2106. s = SIMD.float32x4.neg(s);
  2107. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2108. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2109. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2110. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2111. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2112. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2113. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2114. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2115. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2116. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2117. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2118. var b3 = SIMD.float32x4.neg(eye);
  2119. b3 = SIMD.float32x4.withW(b3, 1.0);
  2120. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2121. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2122. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2123. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2124. };
  2125. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2126. var matrix = Matrix.Zero();
  2127. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2128. return matrix;
  2129. };
  2130. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2131. var hw = 2.0 / width;
  2132. var hh = 2.0 / height;
  2133. var id = 1.0 / (zfar - znear);
  2134. var nid = znear / (znear - zfar);
  2135. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2136. };
  2137. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2138. var matrix = Matrix.Zero();
  2139. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2140. return matrix;
  2141. };
  2142. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2143. result.m[0] = 2.0 / (right - left);
  2144. result.m[1] = result.m[2] = result.m[3] = 0;
  2145. result.m[5] = 2.0 / (top - bottom);
  2146. result.m[4] = result.m[6] = result.m[7] = 0;
  2147. result.m[10] = -1.0 / (znear - zfar);
  2148. result.m[8] = result.m[9] = result.m[11] = 0;
  2149. result.m[12] = (left + right) / (left - right);
  2150. result.m[13] = (top + bottom) / (bottom - top);
  2151. result.m[14] = znear / (znear - zfar);
  2152. result.m[15] = 1.0;
  2153. };
  2154. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2155. var matrix = Matrix.Zero();
  2156. matrix.m[0] = (2.0 * znear) / width;
  2157. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2158. matrix.m[5] = (2.0 * znear) / height;
  2159. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2160. matrix.m[10] = -zfar / (znear - zfar);
  2161. matrix.m[8] = matrix.m[9] = 0.0;
  2162. matrix.m[11] = 1.0;
  2163. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2164. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2165. return matrix;
  2166. };
  2167. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2168. var matrix = Matrix.Zero();
  2169. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2170. return matrix;
  2171. };
  2172. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2173. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2174. var tan = 1.0 / (Math.tan(fov * 0.5));
  2175. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2176. if (v_fixed) {
  2177. result.m[0] = tan / aspect;
  2178. }
  2179. else {
  2180. result.m[0] = tan;
  2181. }
  2182. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2183. if (v_fixed) {
  2184. result.m[5] = tan;
  2185. }
  2186. else {
  2187. result.m[5] = tan * aspect;
  2188. }
  2189. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2190. result.m[8] = result.m[9] = 0.0;
  2191. result.m[10] = -zfar / (znear - zfar);
  2192. result.m[11] = 1.0;
  2193. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2194. result.m[14] = (znear * zfar) / (znear - zfar);
  2195. };
  2196. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2197. var cw = viewport.width;
  2198. var ch = viewport.height;
  2199. var cx = viewport.x;
  2200. var cy = viewport.y;
  2201. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2202. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2203. };
  2204. Matrix.GetAsMatrix2x2 = function (matrix) {
  2205. return new Float32Array([
  2206. matrix.m[0], matrix.m[1],
  2207. matrix.m[4], matrix.m[5]
  2208. ]);
  2209. };
  2210. Matrix.GetAsMatrix3x3 = function (matrix) {
  2211. return new Float32Array([
  2212. matrix.m[0], matrix.m[1], matrix.m[2],
  2213. matrix.m[4], matrix.m[5], matrix.m[6],
  2214. matrix.m[8], matrix.m[9], matrix.m[10]
  2215. ]);
  2216. };
  2217. Matrix.Transpose = function (matrix) {
  2218. var result = new Matrix();
  2219. result.m[0] = matrix.m[0];
  2220. result.m[1] = matrix.m[4];
  2221. result.m[2] = matrix.m[8];
  2222. result.m[3] = matrix.m[12];
  2223. result.m[4] = matrix.m[1];
  2224. result.m[5] = matrix.m[5];
  2225. result.m[6] = matrix.m[9];
  2226. result.m[7] = matrix.m[13];
  2227. result.m[8] = matrix.m[2];
  2228. result.m[9] = matrix.m[6];
  2229. result.m[10] = matrix.m[10];
  2230. result.m[11] = matrix.m[14];
  2231. result.m[12] = matrix.m[3];
  2232. result.m[13] = matrix.m[7];
  2233. result.m[14] = matrix.m[11];
  2234. result.m[15] = matrix.m[15];
  2235. return result;
  2236. };
  2237. Matrix.Reflection = function (plane) {
  2238. var matrix = new Matrix();
  2239. Matrix.ReflectionToRef(plane, matrix);
  2240. return matrix;
  2241. };
  2242. Matrix.ReflectionToRef = function (plane, result) {
  2243. plane.normalize();
  2244. var x = plane.normal.x;
  2245. var y = plane.normal.y;
  2246. var z = plane.normal.z;
  2247. var temp = -2 * x;
  2248. var temp2 = -2 * y;
  2249. var temp3 = -2 * z;
  2250. result.m[0] = (temp * x) + 1;
  2251. result.m[1] = temp2 * x;
  2252. result.m[2] = temp3 * x;
  2253. result.m[3] = 0.0;
  2254. result.m[4] = temp * y;
  2255. result.m[5] = (temp2 * y) + 1;
  2256. result.m[6] = temp3 * y;
  2257. result.m[7] = 0.0;
  2258. result.m[8] = temp * z;
  2259. result.m[9] = temp2 * z;
  2260. result.m[10] = (temp3 * z) + 1;
  2261. result.m[11] = 0.0;
  2262. result.m[12] = temp * plane.d;
  2263. result.m[13] = temp2 * plane.d;
  2264. result.m[14] = temp3 * plane.d;
  2265. result.m[15] = 1.0;
  2266. };
  2267. Matrix._tempQuaternion = new Quaternion();
  2268. Matrix._xAxis = Vector3.Zero();
  2269. Matrix._yAxis = Vector3.Zero();
  2270. Matrix._zAxis = Vector3.Zero();
  2271. return Matrix;
  2272. })();
  2273. BABYLON.Matrix = Matrix;
  2274. var Plane = (function () {
  2275. function Plane(a, b, c, d) {
  2276. this.normal = new Vector3(a, b, c);
  2277. this.d = d;
  2278. }
  2279. Plane.prototype.asArray = function () {
  2280. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2281. };
  2282. // Methods
  2283. Plane.prototype.clone = function () {
  2284. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2285. };
  2286. Plane.prototype.normalize = function () {
  2287. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2288. var magnitude = 0;
  2289. if (norm !== 0) {
  2290. magnitude = 1.0 / norm;
  2291. }
  2292. this.normal.x *= magnitude;
  2293. this.normal.y *= magnitude;
  2294. this.normal.z *= magnitude;
  2295. this.d *= magnitude;
  2296. return this;
  2297. };
  2298. Plane.prototype.transform = function (transformation) {
  2299. var transposedMatrix = Matrix.Transpose(transformation);
  2300. var x = this.normal.x;
  2301. var y = this.normal.y;
  2302. var z = this.normal.z;
  2303. var d = this.d;
  2304. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2305. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2306. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2307. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2308. return new Plane(normalX, normalY, normalZ, finalD);
  2309. };
  2310. Plane.prototype.dotCoordinate = function (point) {
  2311. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2312. };
  2313. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2314. var x1 = point2.x - point1.x;
  2315. var y1 = point2.y - point1.y;
  2316. var z1 = point2.z - point1.z;
  2317. var x2 = point3.x - point1.x;
  2318. var y2 = point3.y - point1.y;
  2319. var z2 = point3.z - point1.z;
  2320. var yz = (y1 * z2) - (z1 * y2);
  2321. var xz = (z1 * x2) - (x1 * z2);
  2322. var xy = (x1 * y2) - (y1 * x2);
  2323. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2324. var invPyth;
  2325. if (pyth !== 0) {
  2326. invPyth = 1.0 / pyth;
  2327. }
  2328. else {
  2329. invPyth = 0;
  2330. }
  2331. this.normal.x = yz * invPyth;
  2332. this.normal.y = xz * invPyth;
  2333. this.normal.z = xy * invPyth;
  2334. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2335. return this;
  2336. };
  2337. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2338. var dot = Vector3.Dot(this.normal, direction);
  2339. return (dot <= epsilon);
  2340. };
  2341. Plane.prototype.signedDistanceTo = function (point) {
  2342. return Vector3.Dot(point, this.normal) + this.d;
  2343. };
  2344. // Statics
  2345. Plane.FromArray = function (array) {
  2346. return new Plane(array[0], array[1], array[2], array[3]);
  2347. };
  2348. Plane.FromPoints = function (point1, point2, point3) {
  2349. var result = new Plane(0, 0, 0, 0);
  2350. result.copyFromPoints(point1, point2, point3);
  2351. return result;
  2352. };
  2353. Plane.FromPositionAndNormal = function (origin, normal) {
  2354. var result = new Plane(0, 0, 0, 0);
  2355. normal.normalize();
  2356. result.normal = normal;
  2357. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2358. return result;
  2359. };
  2360. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2361. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2362. return Vector3.Dot(point, normal) + d;
  2363. };
  2364. return Plane;
  2365. })();
  2366. BABYLON.Plane = Plane;
  2367. var Viewport = (function () {
  2368. function Viewport(x, y, width, height) {
  2369. this.x = x;
  2370. this.y = y;
  2371. this.width = width;
  2372. this.height = height;
  2373. }
  2374. Viewport.prototype.toGlobal = function (engine) {
  2375. var width = engine.getRenderWidth();
  2376. var height = engine.getRenderHeight();
  2377. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2378. };
  2379. return Viewport;
  2380. })();
  2381. BABYLON.Viewport = Viewport;
  2382. var Frustum = (function () {
  2383. function Frustum() {
  2384. }
  2385. Frustum.GetPlanes = function (transform) {
  2386. var frustumPlanes = [];
  2387. for (var index = 0; index < 6; index++) {
  2388. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2389. }
  2390. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2391. return frustumPlanes;
  2392. };
  2393. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2394. // Near
  2395. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2396. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2397. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2398. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2399. frustumPlanes[0].normalize();
  2400. // Far
  2401. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2402. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2403. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2404. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2405. frustumPlanes[1].normalize();
  2406. // Left
  2407. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2408. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2409. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2410. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2411. frustumPlanes[2].normalize();
  2412. // Right
  2413. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2414. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2415. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2416. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2417. frustumPlanes[3].normalize();
  2418. // Top
  2419. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2420. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2421. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2422. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2423. frustumPlanes[4].normalize();
  2424. // Bottom
  2425. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2426. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2427. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2428. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2429. frustumPlanes[5].normalize();
  2430. };
  2431. return Frustum;
  2432. })();
  2433. BABYLON.Frustum = Frustum;
  2434. var Ray = (function () {
  2435. function Ray(origin, direction, length) {
  2436. if (length === void 0) { length = Number.MAX_VALUE; }
  2437. this.origin = origin;
  2438. this.direction = direction;
  2439. this.length = length;
  2440. }
  2441. // Methods
  2442. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2443. var d = 0.0;
  2444. var maxValue = Number.MAX_VALUE;
  2445. var inv;
  2446. var min;
  2447. var max;
  2448. var temp;
  2449. if (Math.abs(this.direction.x) < 0.0000001) {
  2450. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2451. return false;
  2452. }
  2453. }
  2454. else {
  2455. inv = 1.0 / this.direction.x;
  2456. min = (minimum.x - this.origin.x) * inv;
  2457. max = (maximum.x - this.origin.x) * inv;
  2458. if (max === -Infinity) {
  2459. max = Infinity;
  2460. }
  2461. if (min > max) {
  2462. temp = min;
  2463. min = max;
  2464. max = temp;
  2465. }
  2466. d = Math.max(min, d);
  2467. maxValue = Math.min(max, maxValue);
  2468. if (d > maxValue) {
  2469. return false;
  2470. }
  2471. }
  2472. if (Math.abs(this.direction.y) < 0.0000001) {
  2473. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2474. return false;
  2475. }
  2476. }
  2477. else {
  2478. inv = 1.0 / this.direction.y;
  2479. min = (minimum.y - this.origin.y) * inv;
  2480. max = (maximum.y - this.origin.y) * inv;
  2481. if (max === -Infinity) {
  2482. max = Infinity;
  2483. }
  2484. if (min > max) {
  2485. temp = min;
  2486. min = max;
  2487. max = temp;
  2488. }
  2489. d = Math.max(min, d);
  2490. maxValue = Math.min(max, maxValue);
  2491. if (d > maxValue) {
  2492. return false;
  2493. }
  2494. }
  2495. if (Math.abs(this.direction.z) < 0.0000001) {
  2496. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2497. return false;
  2498. }
  2499. }
  2500. else {
  2501. inv = 1.0 / this.direction.z;
  2502. min = (minimum.z - this.origin.z) * inv;
  2503. max = (maximum.z - this.origin.z) * inv;
  2504. if (max === -Infinity) {
  2505. max = Infinity;
  2506. }
  2507. if (min > max) {
  2508. temp = min;
  2509. min = max;
  2510. max = temp;
  2511. }
  2512. d = Math.max(min, d);
  2513. maxValue = Math.min(max, maxValue);
  2514. if (d > maxValue) {
  2515. return false;
  2516. }
  2517. }
  2518. return true;
  2519. };
  2520. Ray.prototype.intersectsBox = function (box) {
  2521. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2522. };
  2523. Ray.prototype.intersectsSphere = function (sphere) {
  2524. var x = sphere.center.x - this.origin.x;
  2525. var y = sphere.center.y - this.origin.y;
  2526. var z = sphere.center.z - this.origin.z;
  2527. var pyth = (x * x) + (y * y) + (z * z);
  2528. var rr = sphere.radius * sphere.radius;
  2529. if (pyth <= rr) {
  2530. return true;
  2531. }
  2532. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2533. if (dot < 0.0) {
  2534. return false;
  2535. }
  2536. var temp = pyth - (dot * dot);
  2537. return temp <= rr;
  2538. };
  2539. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2540. if (!this._edge1) {
  2541. this._edge1 = Vector3.Zero();
  2542. this._edge2 = Vector3.Zero();
  2543. this._pvec = Vector3.Zero();
  2544. this._tvec = Vector3.Zero();
  2545. this._qvec = Vector3.Zero();
  2546. }
  2547. vertex1.subtractToRef(vertex0, this._edge1);
  2548. vertex2.subtractToRef(vertex0, this._edge2);
  2549. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2550. var det = Vector3.Dot(this._edge1, this._pvec);
  2551. if (det === 0) {
  2552. return null;
  2553. }
  2554. var invdet = 1 / det;
  2555. this.origin.subtractToRef(vertex0, this._tvec);
  2556. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2557. if (bu < 0 || bu > 1.0) {
  2558. return null;
  2559. }
  2560. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2561. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2562. if (bv < 0 || bu + bv > 1.0) {
  2563. return null;
  2564. }
  2565. //check if the distance is longer than the predefined length.
  2566. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2567. if (distance > this.length) {
  2568. return null;
  2569. }
  2570. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2571. };
  2572. // Statics
  2573. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2574. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2575. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2576. var direction = end.subtract(start);
  2577. direction.normalize();
  2578. return new Ray(start, direction);
  2579. };
  2580. /**
  2581. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2582. * transformed to the given world matrix.
  2583. * @param origin The origin point
  2584. * @param end The end point
  2585. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2586. */
  2587. Ray.CreateNewFromTo = function (origin, end, world) {
  2588. if (world === void 0) { world = Matrix.Identity(); }
  2589. var direction = end.subtract(origin);
  2590. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2591. direction.normalize();
  2592. return Ray.Transform(new Ray(origin, direction, length), world);
  2593. };
  2594. Ray.Transform = function (ray, matrix) {
  2595. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2596. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2597. return new Ray(newOrigin, newDirection, ray.length);
  2598. };
  2599. return Ray;
  2600. })();
  2601. BABYLON.Ray = Ray;
  2602. (function (Space) {
  2603. Space[Space["LOCAL"] = 0] = "LOCAL";
  2604. Space[Space["WORLD"] = 1] = "WORLD";
  2605. })(BABYLON.Space || (BABYLON.Space = {}));
  2606. var Space = BABYLON.Space;
  2607. var Axis = (function () {
  2608. function Axis() {
  2609. }
  2610. Axis.X = new Vector3(1, 0, 0);
  2611. Axis.Y = new Vector3(0, 1, 0);
  2612. Axis.Z = new Vector3(0, 0, 1);
  2613. return Axis;
  2614. })();
  2615. BABYLON.Axis = Axis;
  2616. ;
  2617. var BezierCurve = (function () {
  2618. function BezierCurve() {
  2619. }
  2620. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2621. // Extract X (which is equal to time here)
  2622. var f0 = 1 - 3 * x2 + 3 * x1;
  2623. var f1 = 3 * x2 - 6 * x1;
  2624. var f2 = 3 * x1;
  2625. var refinedT = t;
  2626. for (var i = 0; i < 5; i++) {
  2627. var refinedT2 = refinedT * refinedT;
  2628. var refinedT3 = refinedT2 * refinedT;
  2629. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2630. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2631. refinedT -= (x - t) * slope;
  2632. refinedT = Math.min(1, Math.max(0, refinedT));
  2633. }
  2634. // Resolve cubic bezier for the given x
  2635. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2636. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2637. Math.pow(refinedT, 3);
  2638. };
  2639. return BezierCurve;
  2640. })();
  2641. BABYLON.BezierCurve = BezierCurve;
  2642. (function (Orientation) {
  2643. Orientation[Orientation["CW"] = 0] = "CW";
  2644. Orientation[Orientation["CCW"] = 1] = "CCW";
  2645. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2646. var Orientation = BABYLON.Orientation;
  2647. var Angle = (function () {
  2648. function Angle(radians) {
  2649. var _this = this;
  2650. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2651. this.radians = function () { return _this._radians; };
  2652. this._radians = radians;
  2653. if (this._radians < 0)
  2654. this._radians += (2 * Math.PI);
  2655. }
  2656. Angle.BetweenTwoPoints = function (a, b) {
  2657. var delta = b.subtract(a);
  2658. var theta = Math.atan2(delta.y, delta.x);
  2659. return new Angle(theta);
  2660. };
  2661. Angle.FromRadians = function (radians) {
  2662. return new Angle(radians);
  2663. };
  2664. Angle.FromDegrees = function (degrees) {
  2665. return new Angle(degrees * Math.PI / 180);
  2666. };
  2667. return Angle;
  2668. })();
  2669. BABYLON.Angle = Angle;
  2670. var Arc2 = (function () {
  2671. function Arc2(startPoint, midPoint, endPoint) {
  2672. this.startPoint = startPoint;
  2673. this.midPoint = midPoint;
  2674. this.endPoint = endPoint;
  2675. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2676. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2677. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2678. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2679. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2680. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2681. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2682. var a1 = this.startAngle.degrees();
  2683. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2684. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2685. // angles correction
  2686. if (a2 - a1 > +180.0)
  2687. a2 -= 360.0;
  2688. if (a2 - a1 < -180.0)
  2689. a2 += 360.0;
  2690. if (a3 - a2 > +180.0)
  2691. a3 -= 360.0;
  2692. if (a3 - a2 < -180.0)
  2693. a3 += 360.0;
  2694. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2695. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2696. }
  2697. return Arc2;
  2698. })();
  2699. BABYLON.Arc2 = Arc2;
  2700. var PathCursor = (function () {
  2701. function PathCursor(path) {
  2702. this.path = path;
  2703. this._onchange = new Array();
  2704. this.value = 0;
  2705. this.animations = new Array();
  2706. }
  2707. PathCursor.prototype.getPoint = function () {
  2708. var point = this.path.getPointAtLengthPosition(this.value);
  2709. return new Vector3(point.x, 0, point.y);
  2710. };
  2711. PathCursor.prototype.moveAhead = function (step) {
  2712. if (step === void 0) { step = 0.002; }
  2713. this.move(step);
  2714. return this;
  2715. };
  2716. PathCursor.prototype.moveBack = function (step) {
  2717. if (step === void 0) { step = 0.002; }
  2718. this.move(-step);
  2719. return this;
  2720. };
  2721. PathCursor.prototype.move = function (step) {
  2722. if (Math.abs(step) > 1) {
  2723. throw "step size should be less than 1.";
  2724. }
  2725. this.value += step;
  2726. this.ensureLimits();
  2727. this.raiseOnChange();
  2728. return this;
  2729. };
  2730. PathCursor.prototype.ensureLimits = function () {
  2731. while (this.value > 1) {
  2732. this.value -= 1;
  2733. }
  2734. while (this.value < 0) {
  2735. this.value += 1;
  2736. }
  2737. return this;
  2738. };
  2739. // used by animation engine
  2740. PathCursor.prototype.markAsDirty = function (propertyName) {
  2741. this.ensureLimits();
  2742. this.raiseOnChange();
  2743. return this;
  2744. };
  2745. PathCursor.prototype.raiseOnChange = function () {
  2746. var _this = this;
  2747. this._onchange.forEach(function (f) { return f(_this); });
  2748. return this;
  2749. };
  2750. PathCursor.prototype.onchange = function (f) {
  2751. this._onchange.push(f);
  2752. return this;
  2753. };
  2754. return PathCursor;
  2755. })();
  2756. BABYLON.PathCursor = PathCursor;
  2757. var Path2 = (function () {
  2758. function Path2(x, y) {
  2759. this._points = new Array();
  2760. this._length = 0;
  2761. this.closed = false;
  2762. this._points.push(new Vector2(x, y));
  2763. }
  2764. Path2.prototype.addLineTo = function (x, y) {
  2765. if (closed) {
  2766. BABYLON.Tools.Error("cannot add lines to closed paths");
  2767. return this;
  2768. }
  2769. var newPoint = new Vector2(x, y);
  2770. var previousPoint = this._points[this._points.length - 1];
  2771. this._points.push(newPoint);
  2772. this._length += newPoint.subtract(previousPoint).length();
  2773. return this;
  2774. };
  2775. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2776. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2777. if (closed) {
  2778. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2779. return this;
  2780. }
  2781. var startPoint = this._points[this._points.length - 1];
  2782. var midPoint = new Vector2(midX, midY);
  2783. var endPoint = new Vector2(endX, endY);
  2784. var arc = new Arc2(startPoint, midPoint, endPoint);
  2785. var increment = arc.angle.radians() / numberOfSegments;
  2786. if (arc.orientation === Orientation.CW)
  2787. increment *= -1;
  2788. var currentAngle = arc.startAngle.radians() + increment;
  2789. for (var i = 0; i < numberOfSegments; i++) {
  2790. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2791. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2792. this.addLineTo(x, y);
  2793. currentAngle += increment;
  2794. }
  2795. return this;
  2796. };
  2797. Path2.prototype.close = function () {
  2798. this.closed = true;
  2799. return this;
  2800. };
  2801. Path2.prototype.length = function () {
  2802. var result = this._length;
  2803. if (!this.closed) {
  2804. var lastPoint = this._points[this._points.length - 1];
  2805. var firstPoint = this._points[0];
  2806. result += (firstPoint.subtract(lastPoint).length());
  2807. }
  2808. return result;
  2809. };
  2810. Path2.prototype.getPoints = function () {
  2811. return this._points;
  2812. };
  2813. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2814. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2815. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2816. return Vector2.Zero();
  2817. }
  2818. var lengthPosition = normalizedLengthPosition * this.length();
  2819. var previousOffset = 0;
  2820. for (var i = 0; i < this._points.length; i++) {
  2821. var j = (i + 1) % this._points.length;
  2822. var a = this._points[i];
  2823. var b = this._points[j];
  2824. var bToA = b.subtract(a);
  2825. var nextOffset = (bToA.length() + previousOffset);
  2826. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2827. var dir = bToA.normalize();
  2828. var localOffset = lengthPosition - previousOffset;
  2829. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2830. }
  2831. previousOffset = nextOffset;
  2832. }
  2833. BABYLON.Tools.Error("internal error");
  2834. return Vector2.Zero();
  2835. };
  2836. Path2.StartingAt = function (x, y) {
  2837. return new Path2(x, y);
  2838. };
  2839. return Path2;
  2840. })();
  2841. BABYLON.Path2 = Path2;
  2842. var Path3D = (function () {
  2843. /**
  2844. * new Path3D(path, normal, raw)
  2845. * path : an array of Vector3, the curve axis of the Path3D
  2846. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2847. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2848. */
  2849. function Path3D(path, firstNormal, raw) {
  2850. this.path = path;
  2851. this._curve = new Array();
  2852. this._distances = new Array();
  2853. this._tangents = new Array();
  2854. this._normals = new Array();
  2855. this._binormals = new Array();
  2856. for (var p = 0; p < path.length; p++) {
  2857. this._curve[p] = path[p].clone(); // hard copy
  2858. }
  2859. this._raw = raw || false;
  2860. this._compute(firstNormal);
  2861. }
  2862. Path3D.prototype.getCurve = function () {
  2863. return this._curve;
  2864. };
  2865. Path3D.prototype.getTangents = function () {
  2866. return this._tangents;
  2867. };
  2868. Path3D.prototype.getNormals = function () {
  2869. return this._normals;
  2870. };
  2871. Path3D.prototype.getBinormals = function () {
  2872. return this._binormals;
  2873. };
  2874. Path3D.prototype.getDistances = function () {
  2875. return this._distances;
  2876. };
  2877. Path3D.prototype.update = function (path, firstNormal) {
  2878. for (var p = 0; p < path.length; p++) {
  2879. this._curve[p].x = path[p].x;
  2880. this._curve[p].y = path[p].y;
  2881. this._curve[p].z = path[p].z;
  2882. }
  2883. this._compute(firstNormal);
  2884. return this;
  2885. };
  2886. // private function compute() : computes tangents, normals and binormals
  2887. Path3D.prototype._compute = function (firstNormal) {
  2888. var l = this._curve.length;
  2889. // first and last tangents
  2890. this._tangents[0] = this._getFirstNonNullVector(0);
  2891. if (!this._raw) {
  2892. this._tangents[0].normalize();
  2893. }
  2894. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2895. if (!this._raw) {
  2896. this._tangents[l - 1].normalize();
  2897. }
  2898. // normals and binormals at first point : arbitrary vector with _normalVector()
  2899. var tg0 = this._tangents[0];
  2900. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2901. this._normals[0] = pp0;
  2902. if (!this._raw) {
  2903. this._normals[0].normalize();
  2904. }
  2905. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2906. if (!this._raw) {
  2907. this._binormals[0].normalize();
  2908. }
  2909. this._distances[0] = 0;
  2910. // normals and binormals : next points
  2911. var prev; // previous vector (segment)
  2912. var cur; // current vector (segment)
  2913. var curTang; // current tangent
  2914. // previous normal
  2915. var prevBinor; // previous binormal
  2916. for (var i = 1; i < l; i++) {
  2917. // tangents
  2918. prev = this._getLastNonNullVector(i);
  2919. if (i < l - 1) {
  2920. cur = this._getFirstNonNullVector(i);
  2921. this._tangents[i] = prev.add(cur);
  2922. this._tangents[i].normalize();
  2923. }
  2924. this._distances[i] = this._distances[i - 1] + prev.length();
  2925. // normals and binormals
  2926. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2927. curTang = this._tangents[i];
  2928. prevBinor = this._binormals[i - 1];
  2929. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2930. if (!this._raw) {
  2931. this._normals[i].normalize();
  2932. }
  2933. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2934. if (!this._raw) {
  2935. this._binormals[i].normalize();
  2936. }
  2937. }
  2938. };
  2939. // private function getFirstNonNullVector(index)
  2940. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2941. Path3D.prototype._getFirstNonNullVector = function (index) {
  2942. var i = 1;
  2943. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2944. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2945. i++;
  2946. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2947. }
  2948. return nNVector;
  2949. };
  2950. // private function getLastNonNullVector(index)
  2951. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2952. Path3D.prototype._getLastNonNullVector = function (index) {
  2953. var i = 1;
  2954. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2955. while (nLVector.length() === 0 && index > i + 1) {
  2956. i++;
  2957. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2958. }
  2959. return nLVector;
  2960. };
  2961. // private function normalVector(v0, vt, va) :
  2962. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2963. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2964. Path3D.prototype._normalVector = function (v0, vt, va) {
  2965. var normal0;
  2966. if (va === undefined || va === null) {
  2967. var point;
  2968. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2969. point = new Vector3(0, -1, 0);
  2970. }
  2971. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2972. point = new Vector3(1, 0, 0);
  2973. }
  2974. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2975. point = new Vector3(0, 0, 1);
  2976. }
  2977. normal0 = Vector3.Cross(vt, point);
  2978. }
  2979. else {
  2980. normal0 = Vector3.Cross(vt, va);
  2981. Vector3.CrossToRef(normal0, vt, normal0);
  2982. }
  2983. normal0.normalize();
  2984. return normal0;
  2985. };
  2986. return Path3D;
  2987. })();
  2988. BABYLON.Path3D = Path3D;
  2989. var Curve3 = (function () {
  2990. function Curve3(points) {
  2991. this._length = 0;
  2992. this._points = points;
  2993. this._length = this._computeLength(points);
  2994. }
  2995. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2996. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2997. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2998. var bez = new Array();
  2999. var equation = function (t, val0, val1, val2) {
  3000. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  3001. return res;
  3002. };
  3003. for (var i = 0; i <= nbPoints; i++) {
  3004. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3005. }
  3006. return new Curve3(bez);
  3007. };
  3008. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  3009. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3010. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3011. var bez = new Array();
  3012. var equation = function (t, val0, val1, val2, val3) {
  3013. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  3014. return res;
  3015. };
  3016. for (var i = 0; i <= nbPoints; i++) {
  3017. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3018. }
  3019. return new Curve3(bez);
  3020. };
  3021. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  3022. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3023. var hermite = new Array();
  3024. var step = 1 / nbPoints;
  3025. for (var i = 0; i <= nbPoints; i++) {
  3026. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3027. }
  3028. return new Curve3(hermite);
  3029. };
  3030. Curve3.prototype.getPoints = function () {
  3031. return this._points;
  3032. };
  3033. Curve3.prototype.length = function () {
  3034. return this._length;
  3035. };
  3036. Curve3.prototype.continue = function (curve) {
  3037. var lastPoint = this._points[this._points.length - 1];
  3038. var continuedPoints = this._points.slice();
  3039. var curvePoints = curve.getPoints();
  3040. for (var i = 1; i < curvePoints.length; i++) {
  3041. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3042. }
  3043. var continuedCurve = new Curve3(continuedPoints);
  3044. return continuedCurve;
  3045. };
  3046. Curve3.prototype._computeLength = function (path) {
  3047. var l = 0;
  3048. for (var i = 1; i < path.length; i++) {
  3049. l += (path[i].subtract(path[i - 1])).length();
  3050. }
  3051. return l;
  3052. };
  3053. return Curve3;
  3054. })();
  3055. BABYLON.Curve3 = Curve3;
  3056. // Vertex formats
  3057. var PositionNormalVertex = (function () {
  3058. function PositionNormalVertex(position, normal) {
  3059. if (position === void 0) { position = Vector3.Zero(); }
  3060. if (normal === void 0) { normal = Vector3.Up(); }
  3061. this.position = position;
  3062. this.normal = normal;
  3063. }
  3064. PositionNormalVertex.prototype.clone = function () {
  3065. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3066. };
  3067. return PositionNormalVertex;
  3068. })();
  3069. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3070. var PositionNormalTextureVertex = (function () {
  3071. function PositionNormalTextureVertex(position, normal, uv) {
  3072. if (position === void 0) { position = Vector3.Zero(); }
  3073. if (normal === void 0) { normal = Vector3.Up(); }
  3074. if (uv === void 0) { uv = Vector2.Zero(); }
  3075. this.position = position;
  3076. this.normal = normal;
  3077. this.uv = uv;
  3078. }
  3079. PositionNormalTextureVertex.prototype.clone = function () {
  3080. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3081. };
  3082. return PositionNormalTextureVertex;
  3083. })();
  3084. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3085. // SIMD
  3086. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3087. var previousInvertToRef = Matrix.prototype.invertToRef;
  3088. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3089. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3090. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3091. var SIMDHelper = (function () {
  3092. function SIMDHelper() {
  3093. }
  3094. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3095. get: function () {
  3096. return SIMDHelper._isEnabled;
  3097. },
  3098. enumerable: true,
  3099. configurable: true
  3100. });
  3101. SIMDHelper.DisableSIMD = function () {
  3102. // Replace functions
  3103. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3104. Matrix.prototype.invertToRef = previousInvertToRef;
  3105. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3106. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3107. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3108. SIMDHelper._isEnabled = false;
  3109. };
  3110. SIMDHelper.EnableSIMD = function () {
  3111. if (window.SIMD === undefined) {
  3112. return;
  3113. }
  3114. // Replace functions
  3115. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3116. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3117. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3118. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3119. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3120. Object.defineProperty(Vector3.prototype, "x", {
  3121. get: function () { return this._data[0]; },
  3122. set: function (value) {
  3123. if (!this._data) {
  3124. this._data = new Float32Array(3);
  3125. }
  3126. this._data[0] = value;
  3127. }
  3128. });
  3129. Object.defineProperty(Vector3.prototype, "y", {
  3130. get: function () { return this._data[1]; },
  3131. set: function (value) {
  3132. this._data[1] = value;
  3133. }
  3134. });
  3135. Object.defineProperty(Vector3.prototype, "z", {
  3136. get: function () { return this._data[2]; },
  3137. set: function (value) {
  3138. this._data[2] = value;
  3139. }
  3140. });
  3141. SIMDHelper._isEnabled = true;
  3142. };
  3143. SIMDHelper._isEnabled = false;
  3144. return SIMDHelper;
  3145. })();
  3146. BABYLON.SIMDHelper = SIMDHelper;
  3147. })(BABYLON || (BABYLON = {}));
  3148. var BABYLON;
  3149. (function (BABYLON) {
  3150. var Database = (function () {
  3151. function Database(urlToScene, callbackManifestChecked) {
  3152. // Handling various flavors of prefixed version of IndexedDB
  3153. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3154. this.callbackManifestChecked = callbackManifestChecked;
  3155. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3156. this.db = null;
  3157. this.enableSceneOffline = false;
  3158. this.enableTexturesOffline = false;
  3159. this.manifestVersionFound = 0;
  3160. this.mustUpdateRessources = false;
  3161. this.hasReachedQuota = false;
  3162. if (!Database.IDBStorageEnabled) {
  3163. this.callbackManifestChecked(true);
  3164. }
  3165. else {
  3166. this.checkManifestFile();
  3167. }
  3168. }
  3169. Database.prototype.checkManifestFile = function () {
  3170. var _this = this;
  3171. function noManifestFile() {
  3172. that.enableSceneOffline = false;
  3173. that.enableTexturesOffline = false;
  3174. that.callbackManifestChecked(false);
  3175. }
  3176. var that = this;
  3177. var manifestURL = this.currentSceneUrl + ".manifest";
  3178. var xhr = new XMLHttpRequest();
  3179. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3180. xhr.open("GET", manifestURLTimeStamped, true);
  3181. xhr.addEventListener("load", function () {
  3182. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3183. try {
  3184. var manifestFile = JSON.parse(xhr.response);
  3185. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3186. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3187. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3188. _this.manifestVersionFound = manifestFile.version;
  3189. }
  3190. if (_this.callbackManifestChecked) {
  3191. _this.callbackManifestChecked(true);
  3192. }
  3193. }
  3194. catch (ex) {
  3195. noManifestFile();
  3196. }
  3197. }
  3198. else {
  3199. noManifestFile();
  3200. }
  3201. }, false);
  3202. xhr.addEventListener("error", function (event) {
  3203. noManifestFile();
  3204. }, false);
  3205. try {
  3206. xhr.send();
  3207. }
  3208. catch (ex) {
  3209. BABYLON.Tools.Error("Error on XHR send request.");
  3210. that.callbackManifestChecked(false);
  3211. }
  3212. };
  3213. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3214. var _this = this;
  3215. function handleError() {
  3216. that.isSupported = false;
  3217. if (errorCallback)
  3218. errorCallback();
  3219. }
  3220. var that = this;
  3221. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3222. // Your browser doesn't support IndexedDB
  3223. this.isSupported = false;
  3224. if (errorCallback)
  3225. errorCallback();
  3226. }
  3227. else {
  3228. // If the DB hasn't been opened or created yet
  3229. if (!this.db) {
  3230. this.hasReachedQuota = false;
  3231. this.isSupported = true;
  3232. var request = this.idbFactory.open("babylonjs", 1);
  3233. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3234. request.onerror = function (event) {
  3235. handleError();
  3236. };
  3237. // executes when a version change transaction cannot complete due to other active transactions
  3238. request.onblocked = function (event) {
  3239. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3240. handleError();
  3241. };
  3242. // DB has been opened successfully
  3243. request.onsuccess = function (event) {
  3244. _this.db = request.result;
  3245. successCallback();
  3246. };
  3247. // Initialization of the DB. Creating Scenes & Textures stores
  3248. request.onupgradeneeded = function (event) {
  3249. _this.db = (event.target).result;
  3250. try {
  3251. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3252. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3253. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3254. }
  3255. catch (ex) {
  3256. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3257. handleError();
  3258. }
  3259. };
  3260. }
  3261. else {
  3262. if (successCallback)
  3263. successCallback();
  3264. }
  3265. }
  3266. };
  3267. Database.prototype.loadImageFromDB = function (url, image) {
  3268. var _this = this;
  3269. var completeURL = Database.ReturnFullUrlLocation(url);
  3270. var saveAndLoadImage = function () {
  3271. if (!_this.hasReachedQuota && _this.db !== null) {
  3272. // the texture is not yet in the DB, let's try to save it
  3273. _this._saveImageIntoDBAsync(completeURL, image);
  3274. }
  3275. else {
  3276. image.src = url;
  3277. }
  3278. };
  3279. if (!this.mustUpdateRessources) {
  3280. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3281. }
  3282. else {
  3283. saveAndLoadImage();
  3284. }
  3285. };
  3286. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3287. if (this.isSupported && this.db !== null) {
  3288. var texture;
  3289. var transaction = this.db.transaction(["textures"]);
  3290. transaction.onabort = function (event) {
  3291. image.src = url;
  3292. };
  3293. transaction.oncomplete = function (event) {
  3294. var blobTextureURL;
  3295. if (texture) {
  3296. var URL = window.URL || window.webkitURL;
  3297. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3298. image.onerror = function () {
  3299. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3300. image.src = url;
  3301. };
  3302. image.src = blobTextureURL;
  3303. }
  3304. else {
  3305. notInDBCallback();
  3306. }
  3307. };
  3308. var getRequest = transaction.objectStore("textures").get(url);
  3309. getRequest.onsuccess = function (event) {
  3310. texture = (event.target).result;
  3311. };
  3312. getRequest.onerror = function (event) {
  3313. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3314. image.src = url;
  3315. };
  3316. }
  3317. else {
  3318. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3319. image.src = url;
  3320. }
  3321. };
  3322. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3323. var _this = this;
  3324. if (this.isSupported) {
  3325. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3326. var generateBlobUrl = function () {
  3327. var blobTextureURL;
  3328. if (blob) {
  3329. var URL = window.URL || window.webkitURL;
  3330. try {
  3331. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3332. }
  3333. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3334. catch (ex) {
  3335. blobTextureURL = URL.createObjectURL(blob);
  3336. }
  3337. }
  3338. image.src = blobTextureURL;
  3339. };
  3340. if (Database.IsUASupportingBlobStorage) {
  3341. var xhr = new XMLHttpRequest(), blob;
  3342. xhr.open("GET", url, true);
  3343. xhr.responseType = "blob";
  3344. xhr.addEventListener("load", function () {
  3345. if (xhr.status === 200) {
  3346. // Blob as response (XHR2)
  3347. blob = xhr.response;
  3348. var transaction = _this.db.transaction(["textures"], "readwrite");
  3349. // the transaction could abort because of a QuotaExceededError error
  3350. transaction.onabort = function (event) {
  3351. try {
  3352. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3353. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3354. this.hasReachedQuota = true;
  3355. }
  3356. }
  3357. catch (ex) { }
  3358. generateBlobUrl();
  3359. };
  3360. transaction.oncomplete = function (event) {
  3361. generateBlobUrl();
  3362. };
  3363. var newTexture = { textureUrl: url, data: blob };
  3364. try {
  3365. // Put the blob into the dabase
  3366. var addRequest = transaction.objectStore("textures").put(newTexture);
  3367. addRequest.onsuccess = function (event) {
  3368. };
  3369. addRequest.onerror = function (event) {
  3370. generateBlobUrl();
  3371. };
  3372. }
  3373. catch (ex) {
  3374. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3375. if (ex.code === 25) {
  3376. Database.IsUASupportingBlobStorage = false;
  3377. }
  3378. image.src = url;
  3379. }
  3380. }
  3381. else {
  3382. image.src = url;
  3383. }
  3384. }, false);
  3385. xhr.addEventListener("error", function (event) {
  3386. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3387. image.src = url;
  3388. }, false);
  3389. xhr.send();
  3390. }
  3391. else {
  3392. image.src = url;
  3393. }
  3394. }
  3395. else {
  3396. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3397. image.src = url;
  3398. }
  3399. };
  3400. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3401. var _this = this;
  3402. var updateVersion = function (event) {
  3403. // the version is not yet in the DB or we need to update it
  3404. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3405. };
  3406. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3407. };
  3408. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3409. var _this = this;
  3410. if (this.isSupported) {
  3411. var version;
  3412. try {
  3413. var transaction = this.db.transaction(["versions"]);
  3414. transaction.oncomplete = function (event) {
  3415. if (version) {
  3416. // If the version in the JSON file is > than the version in DB
  3417. if (_this.manifestVersionFound > version.data) {
  3418. _this.mustUpdateRessources = true;
  3419. updateInDBCallback();
  3420. }
  3421. else {
  3422. callback(version.data);
  3423. }
  3424. }
  3425. else {
  3426. _this.mustUpdateRessources = true;
  3427. updateInDBCallback();
  3428. }
  3429. };
  3430. transaction.onabort = function (event) {
  3431. callback(-1);
  3432. };
  3433. var getRequest = transaction.objectStore("versions").get(url);
  3434. getRequest.onsuccess = function (event) {
  3435. version = (event.target).result;
  3436. };
  3437. getRequest.onerror = function (event) {
  3438. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3439. callback(-1);
  3440. };
  3441. }
  3442. catch (ex) {
  3443. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3444. callback(-1);
  3445. }
  3446. }
  3447. else {
  3448. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3453. var _this = this;
  3454. if (this.isSupported && !this.hasReachedQuota) {
  3455. try {
  3456. // Open a transaction to the database
  3457. var transaction = this.db.transaction(["versions"], "readwrite");
  3458. // the transaction could abort because of a QuotaExceededError error
  3459. transaction.onabort = function (event) {
  3460. try {
  3461. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3462. _this.hasReachedQuota = true;
  3463. }
  3464. }
  3465. catch (ex) { }
  3466. callback(-1);
  3467. };
  3468. transaction.oncomplete = function (event) {
  3469. callback(_this.manifestVersionFound);
  3470. };
  3471. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore("versions").put(newVersion);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3482. callback(-1);
  3483. }
  3484. }
  3485. else {
  3486. callback(-1);
  3487. }
  3488. };
  3489. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3490. var _this = this;
  3491. var completeUrl = Database.ReturnFullUrlLocation(url);
  3492. var saveAndLoadFile = function (event) {
  3493. // the scene is not yet in the DB, let's try to save it
  3494. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3495. };
  3496. this._checkVersionFromDB(completeUrl, function (version) {
  3497. if (version !== -1) {
  3498. if (!_this.mustUpdateRessources) {
  3499. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3500. }
  3501. else {
  3502. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3503. }
  3504. }
  3505. else {
  3506. errorCallback();
  3507. }
  3508. });
  3509. };
  3510. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. var file;
  3520. var transaction = this.db.transaction([targetStore]);
  3521. transaction.oncomplete = function (event) {
  3522. if (file) {
  3523. callback(file.data);
  3524. }
  3525. else {
  3526. notInDBCallback();
  3527. }
  3528. };
  3529. transaction.onabort = function (event) {
  3530. notInDBCallback();
  3531. };
  3532. var getRequest = transaction.objectStore(targetStore).get(url);
  3533. getRequest.onsuccess = function (event) {
  3534. file = (event.target).result;
  3535. };
  3536. getRequest.onerror = function (event) {
  3537. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3538. notInDBCallback();
  3539. };
  3540. }
  3541. else {
  3542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3543. callback();
  3544. }
  3545. };
  3546. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3547. var _this = this;
  3548. if (this.isSupported) {
  3549. var targetStore;
  3550. if (url.indexOf(".babylon") !== -1) {
  3551. targetStore = "scenes";
  3552. }
  3553. else {
  3554. targetStore = "textures";
  3555. }
  3556. // Create XHR
  3557. var xhr = new XMLHttpRequest(), fileData;
  3558. xhr.open("GET", url, true);
  3559. if (useArrayBuffer) {
  3560. xhr.responseType = "arraybuffer";
  3561. }
  3562. xhr.onprogress = progressCallback;
  3563. xhr.addEventListener("load", function () {
  3564. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3565. // Blob as response (XHR2)
  3566. //fileData = xhr.responseText;
  3567. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3568. if (!_this.hasReachedQuota) {
  3569. // Open a transaction to the database
  3570. var transaction = _this.db.transaction([targetStore], "readwrite");
  3571. // the transaction could abort because of a QuotaExceededError error
  3572. transaction.onabort = function (event) {
  3573. try {
  3574. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3575. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3576. this.hasReachedQuota = true;
  3577. }
  3578. }
  3579. catch (ex) { }
  3580. callback(fileData);
  3581. };
  3582. transaction.oncomplete = function (event) {
  3583. callback(fileData);
  3584. };
  3585. var newFile;
  3586. if (targetStore === "scenes") {
  3587. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3588. }
  3589. else {
  3590. newFile = { textureUrl: url, data: fileData };
  3591. }
  3592. try {
  3593. // Put the scene into the database
  3594. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3595. addRequest.onsuccess = function (event) {
  3596. };
  3597. addRequest.onerror = function (event) {
  3598. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3599. };
  3600. }
  3601. catch (ex) {
  3602. callback(fileData);
  3603. }
  3604. }
  3605. else {
  3606. callback(fileData);
  3607. }
  3608. }
  3609. else {
  3610. callback();
  3611. }
  3612. }, false);
  3613. xhr.addEventListener("error", function (event) {
  3614. BABYLON.Tools.Error("error on XHR request.");
  3615. callback();
  3616. }, false);
  3617. xhr.send();
  3618. }
  3619. else {
  3620. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3621. callback();
  3622. }
  3623. };
  3624. Database.IsUASupportingBlobStorage = true;
  3625. Database.IDBStorageEnabled = true;
  3626. Database.parseURL = function (url) {
  3627. var a = document.createElement('a');
  3628. a.href = url;
  3629. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3630. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3631. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3632. return absLocation;
  3633. };
  3634. Database.ReturnFullUrlLocation = function (url) {
  3635. if (url.indexOf("http:/") === -1) {
  3636. return (Database.parseURL(window.location.href) + url);
  3637. }
  3638. else {
  3639. return url;
  3640. }
  3641. };
  3642. return Database;
  3643. })();
  3644. BABYLON.Database = Database;
  3645. })(BABYLON || (BABYLON = {}));
  3646. var BABYLON;
  3647. (function (BABYLON) {
  3648. var Internals;
  3649. (function (Internals) {
  3650. /*
  3651. * Based on jsTGALoader - Javascript loader for TGA file
  3652. * By Vincent Thibault
  3653. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3654. */
  3655. var TGATools = (function () {
  3656. function TGATools() {
  3657. }
  3658. TGATools.GetTGAHeader = function (data) {
  3659. var offset = 0;
  3660. var header = {
  3661. id_length: data[offset++],
  3662. colormap_type: data[offset++],
  3663. image_type: data[offset++],
  3664. colormap_index: data[offset++] | data[offset++] << 8,
  3665. colormap_length: data[offset++] | data[offset++] << 8,
  3666. colormap_size: data[offset++],
  3667. origin: [
  3668. data[offset++] | data[offset++] << 8,
  3669. data[offset++] | data[offset++] << 8
  3670. ],
  3671. width: data[offset++] | data[offset++] << 8,
  3672. height: data[offset++] | data[offset++] << 8,
  3673. pixel_size: data[offset++],
  3674. flags: data[offset++]
  3675. };
  3676. return header;
  3677. };
  3678. TGATools.UploadContent = function (gl, data) {
  3679. // Not enough data to contain header ?
  3680. if (data.length < 19) {
  3681. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3682. return;
  3683. }
  3684. // Read Header
  3685. var offset = 18;
  3686. var header = TGATools.GetTGAHeader(data);
  3687. // Assume it's a valid Targa file.
  3688. if (header.id_length + offset > data.length) {
  3689. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3690. return;
  3691. }
  3692. // Skip not needed data
  3693. offset += header.id_length;
  3694. var use_rle = false;
  3695. var use_pal = false;
  3696. var use_rgb = false;
  3697. var use_grey = false;
  3698. // Get some informations.
  3699. switch (header.image_type) {
  3700. case TGATools._TYPE_RLE_INDEXED:
  3701. use_rle = true;
  3702. case TGATools._TYPE_INDEXED:
  3703. use_pal = true;
  3704. break;
  3705. case TGATools._TYPE_RLE_RGB:
  3706. use_rle = true;
  3707. case TGATools._TYPE_RGB:
  3708. use_rgb = true;
  3709. break;
  3710. case TGATools._TYPE_RLE_GREY:
  3711. use_rle = true;
  3712. case TGATools._TYPE_GREY:
  3713. use_grey = true;
  3714. break;
  3715. }
  3716. var pixel_data;
  3717. var numAlphaBits = header.flags & 0xf;
  3718. var pixel_size = header.pixel_size >> 3;
  3719. var pixel_total = header.width * header.height * pixel_size;
  3720. // Read palettes
  3721. var palettes;
  3722. if (use_pal) {
  3723. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3724. }
  3725. // Read LRE
  3726. if (use_rle) {
  3727. pixel_data = new Uint8Array(pixel_total);
  3728. var c, count, i;
  3729. var localOffset = 0;
  3730. var pixels = new Uint8Array(pixel_size);
  3731. while (offset < pixel_total && localOffset < pixel_total) {
  3732. c = data[offset++];
  3733. count = (c & 0x7f) + 1;
  3734. // RLE pixels
  3735. if (c & 0x80) {
  3736. // Bind pixel tmp array
  3737. for (i = 0; i < pixel_size; ++i) {
  3738. pixels[i] = data[offset++];
  3739. }
  3740. // Copy pixel array
  3741. for (i = 0; i < count; ++i) {
  3742. pixel_data.set(pixels, localOffset + i * pixel_size);
  3743. }
  3744. localOffset += pixel_size * count;
  3745. }
  3746. else {
  3747. count *= pixel_size;
  3748. for (i = 0; i < count; ++i) {
  3749. pixel_data[localOffset + i] = data[offset++];
  3750. }
  3751. localOffset += count;
  3752. }
  3753. }
  3754. }
  3755. else {
  3756. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3757. }
  3758. // Load to texture
  3759. var x_start, y_start, x_step, y_step, y_end, x_end;
  3760. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3761. default:
  3762. case TGATools._ORIGIN_UL:
  3763. x_start = 0;
  3764. x_step = 1;
  3765. x_end = header.width;
  3766. y_start = 0;
  3767. y_step = 1;
  3768. y_end = header.height;
  3769. break;
  3770. case TGATools._ORIGIN_BL:
  3771. x_start = 0;
  3772. x_step = 1;
  3773. x_end = header.width;
  3774. y_start = header.height - 1;
  3775. y_step = -1;
  3776. y_end = -1;
  3777. break;
  3778. case TGATools._ORIGIN_UR:
  3779. x_start = header.width - 1;
  3780. x_step = -1;
  3781. x_end = -1;
  3782. y_start = 0;
  3783. y_step = 1;
  3784. y_end = header.height;
  3785. break;
  3786. case TGATools._ORIGIN_BR:
  3787. x_start = header.width - 1;
  3788. x_step = -1;
  3789. x_end = -1;
  3790. y_start = header.height - 1;
  3791. y_step = -1;
  3792. y_end = -1;
  3793. break;
  3794. }
  3795. // Load the specify method
  3796. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3797. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3798. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3799. };
  3800. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3801. var image = pixel_data, colormap = palettes;
  3802. var width = header.width, height = header.height;
  3803. var color, i = 0, x, y;
  3804. var imageData = new Uint8Array(width * height * 4);
  3805. for (y = y_start; y !== y_end; y += y_step) {
  3806. for (x = x_start; x !== x_end; x += x_step, i++) {
  3807. color = image[i];
  3808. imageData[(x + width * y) * 4 + 3] = 255;
  3809. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3810. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3811. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3812. }
  3813. }
  3814. return imageData;
  3815. };
  3816. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3817. var image = pixel_data;
  3818. var width = header.width, height = header.height;
  3819. var color, i = 0, x, y;
  3820. var imageData = new Uint8Array(width * height * 4);
  3821. for (y = y_start; y !== y_end; y += y_step) {
  3822. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3823. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3824. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3825. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3826. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3827. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3828. }
  3829. }
  3830. return imageData;
  3831. };
  3832. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3833. var image = pixel_data;
  3834. var width = header.width, height = header.height;
  3835. var i = 0, x, y;
  3836. var imageData = new Uint8Array(width * height * 4);
  3837. for (y = y_start; y !== y_end; y += y_step) {
  3838. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3839. imageData[(x + width * y) * 4 + 3] = 255;
  3840. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3841. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3842. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3843. }
  3844. }
  3845. return imageData;
  3846. };
  3847. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3848. var image = pixel_data;
  3849. var width = header.width, height = header.height;
  3850. var i = 0, x, y;
  3851. var imageData = new Uint8Array(width * height * 4);
  3852. for (y = y_start; y !== y_end; y += y_step) {
  3853. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3854. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3855. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3856. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3857. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3858. }
  3859. }
  3860. return imageData;
  3861. };
  3862. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3863. var image = pixel_data;
  3864. var width = header.width, height = header.height;
  3865. var color, i = 0, x, y;
  3866. var imageData = new Uint8Array(width * height * 4);
  3867. for (y = y_start; y !== y_end; y += y_step) {
  3868. for (x = x_start; x !== x_end; x += x_step, i++) {
  3869. color = image[i];
  3870. imageData[(x + width * y) * 4 + 0] = color;
  3871. imageData[(x + width * y) * 4 + 1] = color;
  3872. imageData[(x + width * y) * 4 + 2] = color;
  3873. imageData[(x + width * y) * 4 + 3] = 255;
  3874. }
  3875. }
  3876. return imageData;
  3877. };
  3878. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3879. var image = pixel_data;
  3880. var width = header.width, height = header.height;
  3881. var i = 0, x, y;
  3882. var imageData = new Uint8Array(width * height * 4);
  3883. for (y = y_start; y !== y_end; y += y_step) {
  3884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3885. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3886. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3887. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3888. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3889. }
  3890. }
  3891. return imageData;
  3892. };
  3893. TGATools._TYPE_NO_DATA = 0;
  3894. TGATools._TYPE_INDEXED = 1;
  3895. TGATools._TYPE_RGB = 2;
  3896. TGATools._TYPE_GREY = 3;
  3897. TGATools._TYPE_RLE_INDEXED = 9;
  3898. TGATools._TYPE_RLE_RGB = 10;
  3899. TGATools._TYPE_RLE_GREY = 11;
  3900. TGATools._ORIGIN_MASK = 0x30;
  3901. TGATools._ORIGIN_SHIFT = 0x04;
  3902. TGATools._ORIGIN_BL = 0x00;
  3903. TGATools._ORIGIN_BR = 0x01;
  3904. TGATools._ORIGIN_UL = 0x02;
  3905. TGATools._ORIGIN_UR = 0x03;
  3906. return TGATools;
  3907. })();
  3908. Internals.TGATools = TGATools;
  3909. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3910. })(BABYLON || (BABYLON = {}));
  3911. var BABYLON;
  3912. (function (BABYLON) {
  3913. var Internals;
  3914. (function (Internals) {
  3915. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3916. // All values and structures referenced from:
  3917. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3918. var DDS_MAGIC = 0x20534444;
  3919. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  3920. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3921. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  3922. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3923. function FourCCToInt32(value) {
  3924. return value.charCodeAt(0) +
  3925. (value.charCodeAt(1) << 8) +
  3926. (value.charCodeAt(2) << 16) +
  3927. (value.charCodeAt(3) << 24);
  3928. }
  3929. function Int32ToFourCC(value) {
  3930. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3931. }
  3932. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3933. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3934. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3935. var headerLengthInt = 31; // The header length in 32 bit ints
  3936. // Offsets into the header array
  3937. var off_magic = 0;
  3938. var off_size = 1;
  3939. var off_flags = 2;
  3940. var off_height = 3;
  3941. var off_width = 4;
  3942. var off_mipmapCount = 7;
  3943. var off_pfFlags = 20;
  3944. var off_pfFourCC = 21;
  3945. var off_RGBbpp = 22;
  3946. var off_RMask = 23;
  3947. var off_GMask = 24;
  3948. var off_BMask = 25;
  3949. var off_AMask = 26;
  3950. var off_caps1 = 27;
  3951. var off_caps2 = 28;
  3952. ;
  3953. var DDSTools = (function () {
  3954. function DDSTools() {
  3955. }
  3956. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3957. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3958. var mipmapCount = 1;
  3959. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3960. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3961. }
  3962. return {
  3963. width: header[off_width],
  3964. height: header[off_height],
  3965. mipmapCount: mipmapCount,
  3966. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3967. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3968. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3969. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3970. };
  3971. };
  3972. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3973. var byteArray = new Uint8Array(dataLength);
  3974. var srcData = new Uint8Array(arrayBuffer);
  3975. var index = 0;
  3976. for (var y = height - 1; y >= 0; y--) {
  3977. for (var x = 0; x < width; x++) {
  3978. var srcPos = dataOffset + (x + y * width) * 4;
  3979. byteArray[index + 2] = srcData[srcPos];
  3980. byteArray[index + 1] = srcData[srcPos + 1];
  3981. byteArray[index] = srcData[srcPos + 2];
  3982. byteArray[index + 3] = srcData[srcPos + 3];
  3983. index += 4;
  3984. }
  3985. }
  3986. return byteArray;
  3987. };
  3988. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3989. var byteArray = new Uint8Array(dataLength);
  3990. var srcData = new Uint8Array(arrayBuffer);
  3991. var index = 0;
  3992. for (var y = height - 1; y >= 0; y--) {
  3993. for (var x = 0; x < width; x++) {
  3994. var srcPos = dataOffset + (x + y * width) * 3;
  3995. byteArray[index + 2] = srcData[srcPos];
  3996. byteArray[index + 1] = srcData[srcPos + 1];
  3997. byteArray[index] = srcData[srcPos + 2];
  3998. index += 3;
  3999. }
  4000. }
  4001. return byteArray;
  4002. };
  4003. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  4004. var byteArray = new Uint8Array(dataLength);
  4005. var srcData = new Uint8Array(arrayBuffer);
  4006. var index = 0;
  4007. for (var y = height - 1; y >= 0; y--) {
  4008. for (var x = 0; x < width; x++) {
  4009. var srcPos = dataOffset + (x + y * width);
  4010. byteArray[index] = srcData[srcPos];
  4011. index++;
  4012. }
  4013. }
  4014. return byteArray;
  4015. };
  4016. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  4017. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  4018. if (header[off_magic] != DDS_MAGIC) {
  4019. BABYLON.Tools.Error("Invalid magic number in DDS header");
  4020. return;
  4021. }
  4022. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  4023. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  4024. return;
  4025. }
  4026. if (info.isFourCC) {
  4027. fourCC = header[off_pfFourCC];
  4028. switch (fourCC) {
  4029. case FOURCC_DXT1:
  4030. blockBytes = 8;
  4031. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  4032. break;
  4033. case FOURCC_DXT3:
  4034. blockBytes = 16;
  4035. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  4036. break;
  4037. case FOURCC_DXT5:
  4038. blockBytes = 16;
  4039. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4040. break;
  4041. default:
  4042. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4043. return;
  4044. }
  4045. }
  4046. mipmapCount = 1;
  4047. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4048. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4049. }
  4050. var bpp = header[off_RGBbpp];
  4051. for (var face = 0; face < faces; face++) {
  4052. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4053. width = header[off_width];
  4054. height = header[off_height];
  4055. dataOffset = header[off_size] + 4;
  4056. for (i = 0; i < mipmapCount; ++i) {
  4057. if (info.isRGB) {
  4058. if (bpp === 24) {
  4059. dataLength = width * height * 3;
  4060. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4061. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4062. }
  4063. else {
  4064. dataLength = width * height * 4;
  4065. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4066. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4067. }
  4068. }
  4069. else if (info.isLuminance) {
  4070. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4071. var unpaddedRowSize = width;
  4072. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4073. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4074. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4075. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4076. }
  4077. else {
  4078. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4079. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4080. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4081. }
  4082. dataOffset += dataLength;
  4083. width *= 0.5;
  4084. height *= 0.5;
  4085. width = Math.max(1.0, width);
  4086. height = Math.max(1.0, height);
  4087. }
  4088. }
  4089. };
  4090. return DDSTools;
  4091. })();
  4092. Internals.DDSTools = DDSTools;
  4093. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4094. })(BABYLON || (BABYLON = {}));
  4095. var BABYLON;
  4096. (function (BABYLON) {
  4097. var SmartArray = (function () {
  4098. function SmartArray(capacity) {
  4099. this.length = 0;
  4100. this._duplicateId = 0;
  4101. this.data = new Array(capacity);
  4102. this._id = SmartArray._GlobalId++;
  4103. }
  4104. SmartArray.prototype.push = function (value) {
  4105. this.data[this.length++] = value;
  4106. if (this.length > this.data.length) {
  4107. this.data.length *= 2;
  4108. }
  4109. if (!value.__smartArrayFlags) {
  4110. value.__smartArrayFlags = {};
  4111. }
  4112. value.__smartArrayFlags[this._id] = this._duplicateId;
  4113. };
  4114. SmartArray.prototype.pushNoDuplicate = function (value) {
  4115. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4116. return;
  4117. }
  4118. this.push(value);
  4119. };
  4120. SmartArray.prototype.sort = function (compareFn) {
  4121. this.data.sort(compareFn);
  4122. };
  4123. SmartArray.prototype.reset = function () {
  4124. this.length = 0;
  4125. this._duplicateId++;
  4126. };
  4127. SmartArray.prototype.concat = function (array) {
  4128. if (array.length === 0) {
  4129. return;
  4130. }
  4131. if (this.length + array.length > this.data.length) {
  4132. this.data.length = (this.length + array.length) * 2;
  4133. }
  4134. for (var index = 0; index < array.length; index++) {
  4135. this.data[this.length++] = (array.data || array)[index];
  4136. }
  4137. };
  4138. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4139. if (array.length === 0) {
  4140. return;
  4141. }
  4142. if (this.length + array.length > this.data.length) {
  4143. this.data.length = (this.length + array.length) * 2;
  4144. }
  4145. for (var index = 0; index < array.length; index++) {
  4146. var item = (array.data || array)[index];
  4147. this.pushNoDuplicate(item);
  4148. }
  4149. };
  4150. SmartArray.prototype.indexOf = function (value) {
  4151. var position = this.data.indexOf(value);
  4152. if (position >= this.length) {
  4153. return -1;
  4154. }
  4155. return position;
  4156. };
  4157. // Statics
  4158. SmartArray._GlobalId = 0;
  4159. return SmartArray;
  4160. })();
  4161. BABYLON.SmartArray = SmartArray;
  4162. })(BABYLON || (BABYLON = {}));
  4163. var BABYLON;
  4164. (function (BABYLON) {
  4165. var SmartCollection = (function () {
  4166. function SmartCollection(capacity) {
  4167. if (capacity === void 0) { capacity = 10; }
  4168. this.count = 0;
  4169. this._initialCapacity = capacity;
  4170. this.items = {};
  4171. this._keys = new Array(this._initialCapacity);
  4172. }
  4173. SmartCollection.prototype.add = function (key, item) {
  4174. if (this.items[key] != undefined) {
  4175. return -1;
  4176. }
  4177. this.items[key] = item;
  4178. //literal keys are always strings, but we keep source type of key in _keys array
  4179. this._keys[this.count++] = key;
  4180. if (this.count > this._keys.length) {
  4181. this._keys.length *= 2;
  4182. }
  4183. return this.count;
  4184. };
  4185. SmartCollection.prototype.remove = function (key) {
  4186. if (this.items[key] == undefined) {
  4187. return -1;
  4188. }
  4189. return this.removeItemOfIndex(this.indexOf(key));
  4190. };
  4191. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4192. if (index < this.count && index > -1) {
  4193. delete this.items[this._keys[index]];
  4194. //here, shifting by hand is better optimised than .splice
  4195. while (index < this.count) {
  4196. this._keys[index] = this._keys[index + 1];
  4197. index++;
  4198. }
  4199. }
  4200. else {
  4201. return -1;
  4202. }
  4203. return --this.count;
  4204. };
  4205. SmartCollection.prototype.indexOf = function (key) {
  4206. for (var i = 0; i !== this.count; i++) {
  4207. if (this._keys[i] === key) {
  4208. return i;
  4209. }
  4210. }
  4211. return -1;
  4212. };
  4213. SmartCollection.prototype.item = function (key) {
  4214. return this.items[key];
  4215. };
  4216. SmartCollection.prototype.getAllKeys = function () {
  4217. if (this.count > 0) {
  4218. var keys = new Array(this.count);
  4219. for (var i = 0; i < this.count; i++) {
  4220. keys[i] = this._keys[i];
  4221. }
  4222. return keys;
  4223. }
  4224. else {
  4225. return undefined;
  4226. }
  4227. };
  4228. SmartCollection.prototype.getKeyByIndex = function (index) {
  4229. if (index < this.count && index > -1) {
  4230. return this._keys[index];
  4231. }
  4232. else {
  4233. return undefined;
  4234. }
  4235. };
  4236. SmartCollection.prototype.getItemByIndex = function (index) {
  4237. if (index < this.count && index > -1) {
  4238. return this.items[this._keys[index]];
  4239. }
  4240. else {
  4241. return undefined;
  4242. }
  4243. };
  4244. SmartCollection.prototype.empty = function () {
  4245. if (this.count > 0) {
  4246. this.count = 0;
  4247. this.items = {};
  4248. this._keys = new Array(this._initialCapacity);
  4249. }
  4250. };
  4251. SmartCollection.prototype.forEach = function (block) {
  4252. var key;
  4253. for (key in this.items) {
  4254. if (this.items.hasOwnProperty(key)) {
  4255. block(this.items[key]);
  4256. }
  4257. }
  4258. };
  4259. return SmartCollection;
  4260. })();
  4261. BABYLON.SmartCollection = SmartCollection;
  4262. })(BABYLON || (BABYLON = {}));
  4263. var BABYLON;
  4264. (function (BABYLON) {
  4265. // Screenshots
  4266. var screenshotCanvas;
  4267. var cloneValue = function (source, destinationObject) {
  4268. if (!source)
  4269. return null;
  4270. if (source instanceof BABYLON.Mesh) {
  4271. return null;
  4272. }
  4273. if (source instanceof BABYLON.SubMesh) {
  4274. return source.clone(destinationObject);
  4275. }
  4276. else if (source.clone) {
  4277. return source.clone();
  4278. }
  4279. return null;
  4280. };
  4281. var Tools = (function () {
  4282. function Tools() {
  4283. }
  4284. Tools.ToHex = function (i) {
  4285. var str = i.toString(16);
  4286. if (i <= 15) {
  4287. return ("0" + str).toUpperCase();
  4288. }
  4289. return str.toUpperCase();
  4290. };
  4291. Tools.SetImmediate = function (action) {
  4292. if (window.setImmediate) {
  4293. window.setImmediate(action);
  4294. }
  4295. else {
  4296. setTimeout(action, 1);
  4297. }
  4298. };
  4299. Tools.IsExponentOfTwo = function (value) {
  4300. var count = 1;
  4301. do {
  4302. count *= 2;
  4303. } while (count < value);
  4304. return count === value;
  4305. };
  4306. Tools.GetExponentOfTwo = function (value, max) {
  4307. var count = 1;
  4308. do {
  4309. count *= 2;
  4310. } while (count < value);
  4311. if (count > max)
  4312. count = max;
  4313. return count;
  4314. };
  4315. Tools.GetFilename = function (path) {
  4316. var index = path.lastIndexOf("/");
  4317. if (index < 0)
  4318. return path;
  4319. return path.substring(index + 1);
  4320. };
  4321. Tools.GetDOMTextContent = function (element) {
  4322. var result = "";
  4323. var child = element.firstChild;
  4324. while (child) {
  4325. if (child.nodeType === 3) {
  4326. result += child.textContent;
  4327. }
  4328. child = child.nextSibling;
  4329. }
  4330. return result;
  4331. };
  4332. Tools.ToDegrees = function (angle) {
  4333. return angle * 180 / Math.PI;
  4334. };
  4335. Tools.ToRadians = function (angle) {
  4336. return angle * Math.PI / 180;
  4337. };
  4338. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4339. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4340. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4341. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4342. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4343. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4344. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4345. }
  4346. return {
  4347. minimum: minimum,
  4348. maximum: maximum
  4349. };
  4350. };
  4351. Tools.ExtractMinAndMax = function (positions, start, count) {
  4352. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4353. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4354. for (var index = start; index < start + count; index++) {
  4355. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4356. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4357. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4358. }
  4359. return {
  4360. minimum: minimum,
  4361. maximum: maximum
  4362. };
  4363. };
  4364. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4365. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4366. return undefined;
  4367. return Array.isArray(obj) ? obj : [obj];
  4368. };
  4369. // Misc.
  4370. Tools.GetPointerPrefix = function () {
  4371. var eventPrefix = "pointer";
  4372. // Check if hand.js is referenced or if the browser natively supports pointer events
  4373. if (!navigator.pointerEnabled) {
  4374. eventPrefix = "mouse";
  4375. }
  4376. return eventPrefix;
  4377. };
  4378. Tools.QueueNewFrame = function (func) {
  4379. if (window.requestAnimationFrame)
  4380. window.requestAnimationFrame(func);
  4381. else if (window.msRequestAnimationFrame)
  4382. window.msRequestAnimationFrame(func);
  4383. else if (window.webkitRequestAnimationFrame)
  4384. window.webkitRequestAnimationFrame(func);
  4385. else if (window.mozRequestAnimationFrame)
  4386. window.mozRequestAnimationFrame(func);
  4387. else if (window.oRequestAnimationFrame)
  4388. window.oRequestAnimationFrame(func);
  4389. else {
  4390. window.setTimeout(func, 16);
  4391. }
  4392. };
  4393. Tools.RequestFullscreen = function (element) {
  4394. if (element.requestFullscreen)
  4395. element.requestFullscreen();
  4396. else if (element.msRequestFullscreen)
  4397. element.msRequestFullscreen();
  4398. else if (element.webkitRequestFullscreen)
  4399. element.webkitRequestFullscreen();
  4400. else if (element.mozRequestFullScreen)
  4401. element.mozRequestFullScreen();
  4402. };
  4403. Tools.ExitFullscreen = function () {
  4404. if (document.exitFullscreen) {
  4405. document.exitFullscreen();
  4406. }
  4407. else if (document.mozCancelFullScreen) {
  4408. document.mozCancelFullScreen();
  4409. }
  4410. else if (document.webkitCancelFullScreen) {
  4411. document.webkitCancelFullScreen();
  4412. }
  4413. else if (document.msCancelFullScreen) {
  4414. document.msCancelFullScreen();
  4415. }
  4416. };
  4417. // External files
  4418. Tools.CleanUrl = function (url) {
  4419. url = url.replace(/#/mg, "%23");
  4420. return url;
  4421. };
  4422. Tools.LoadImage = function (url, onload, onerror, database) {
  4423. url = Tools.CleanUrl(url);
  4424. var img = new Image();
  4425. if (url.substr(0, 5) !== "data:")
  4426. img.crossOrigin = 'anonymous';
  4427. img.onload = function () {
  4428. onload(img);
  4429. };
  4430. img.onerror = function (err) {
  4431. Tools.Error("Error while trying to load texture: " + url);
  4432. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4433. onload(img);
  4434. };
  4435. var noIndexedDB = function () {
  4436. img.src = url;
  4437. };
  4438. var loadFromIndexedDB = function () {
  4439. database.loadImageFromDB(url, img);
  4440. };
  4441. //ANY database to do!
  4442. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4444. }
  4445. else {
  4446. if (url.indexOf("file:") === -1) {
  4447. noIndexedDB();
  4448. }
  4449. else {
  4450. try {
  4451. var textureName = url.substring(5);
  4452. var blobURL;
  4453. try {
  4454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4455. }
  4456. catch (ex) {
  4457. // Chrome doesn't support oneTimeOnly parameter
  4458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4459. }
  4460. img.src = blobURL;
  4461. }
  4462. catch (e) {
  4463. img.src = null;
  4464. }
  4465. }
  4466. }
  4467. return img;
  4468. };
  4469. //ANY
  4470. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4471. url = Tools.CleanUrl(url);
  4472. var noIndexedDB = function () {
  4473. var request = new XMLHttpRequest();
  4474. var loadUrl = Tools.BaseUrl + url;
  4475. request.open('GET', loadUrl, true);
  4476. if (useArrayBuffer) {
  4477. request.responseType = "arraybuffer";
  4478. }
  4479. request.onprogress = progressCallBack;
  4480. request.onreadystatechange = function () {
  4481. if (request.readyState === 4) {
  4482. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4483. callback(!useArrayBuffer ? request.responseText : request.response);
  4484. }
  4485. else {
  4486. if (onError) {
  4487. onError();
  4488. }
  4489. else {
  4490. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4491. }
  4492. }
  4493. }
  4494. };
  4495. request.send(null);
  4496. };
  4497. var loadFromIndexedDB = function () {
  4498. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4499. };
  4500. if (url.indexOf("file:") !== -1) {
  4501. var fileName = url.substring(5);
  4502. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4503. }
  4504. else {
  4505. // Caching all files
  4506. if (database && database.enableSceneOffline) {
  4507. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4508. }
  4509. else {
  4510. noIndexedDB();
  4511. }
  4512. }
  4513. };
  4514. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4515. var reader = new FileReader();
  4516. reader.onload = function (e) {
  4517. //target doesn't have result from ts 1.3
  4518. callback(e.target['result']);
  4519. };
  4520. reader.onprogress = progressCallback;
  4521. reader.readAsDataURL(fileToLoad);
  4522. };
  4523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4524. var reader = new FileReader();
  4525. reader.onerror = function (e) {
  4526. Tools.Log("Error while reading file: " + fileToLoad.name);
  4527. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4528. };
  4529. reader.onload = function (e) {
  4530. //target doesn't have result from ts 1.3
  4531. callback(e.target['result']);
  4532. };
  4533. reader.onprogress = progressCallBack;
  4534. if (!useArrayBuffer) {
  4535. // Asynchronous read
  4536. reader.readAsText(fileToLoad);
  4537. }
  4538. else {
  4539. reader.readAsArrayBuffer(fileToLoad);
  4540. }
  4541. };
  4542. //returns a downloadable url to a file content.
  4543. Tools.FileAsURL = function (content) {
  4544. var fileBlob = new Blob([content]);
  4545. var url = window.URL || window.webkitURL;
  4546. var link = url.createObjectURL(fileBlob);
  4547. return link;
  4548. };
  4549. // Misc.
  4550. Tools.Clamp = function (value, min, max) {
  4551. if (min === void 0) { min = 0; }
  4552. if (max === void 0) { max = 1; }
  4553. return Math.min(max, Math.max(min, value));
  4554. };
  4555. // Returns -1 when value is a negative number and
  4556. // +1 when value is a positive number.
  4557. Tools.Sign = function (value) {
  4558. value = +value; // convert to a number
  4559. if (value === 0 || isNaN(value))
  4560. return value;
  4561. return value > 0 ? 1 : -1;
  4562. };
  4563. Tools.Format = function (value, decimals) {
  4564. if (decimals === void 0) { decimals = 2; }
  4565. return value.toFixed(decimals);
  4566. };
  4567. Tools.CheckExtends = function (v, min, max) {
  4568. if (v.x < min.x)
  4569. min.x = v.x;
  4570. if (v.y < min.y)
  4571. min.y = v.y;
  4572. if (v.z < min.z)
  4573. min.z = v.z;
  4574. if (v.x > max.x)
  4575. max.x = v.x;
  4576. if (v.y > max.y)
  4577. max.y = v.y;
  4578. if (v.z > max.z)
  4579. max.z = v.z;
  4580. };
  4581. Tools.WithinEpsilon = function (a, b, epsilon) {
  4582. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4583. var num = a - b;
  4584. return -epsilon <= num && num <= epsilon;
  4585. };
  4586. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4587. for (var prop in source) {
  4588. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4589. continue;
  4590. }
  4591. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4592. continue;
  4593. }
  4594. var sourceValue = source[prop];
  4595. var typeOfSourceValue = typeof sourceValue;
  4596. if (typeOfSourceValue === "function") {
  4597. continue;
  4598. }
  4599. if (typeOfSourceValue === "object") {
  4600. if (sourceValue instanceof Array) {
  4601. destination[prop] = [];
  4602. if (sourceValue.length > 0) {
  4603. if (typeof sourceValue[0] == "object") {
  4604. for (var index = 0; index < sourceValue.length; index++) {
  4605. var clonedValue = cloneValue(sourceValue[index], destination);
  4606. if (destination[prop].indexOf(clonedValue) === -1) {
  4607. destination[prop].push(clonedValue);
  4608. }
  4609. }
  4610. }
  4611. else {
  4612. destination[prop] = sourceValue.slice(0);
  4613. }
  4614. }
  4615. }
  4616. else {
  4617. destination[prop] = cloneValue(sourceValue, destination);
  4618. }
  4619. }
  4620. else {
  4621. destination[prop] = sourceValue;
  4622. }
  4623. }
  4624. };
  4625. Tools.IsEmpty = function (obj) {
  4626. for (var i in obj) {
  4627. return false;
  4628. }
  4629. return true;
  4630. };
  4631. Tools.RegisterTopRootEvents = function (events) {
  4632. for (var index = 0; index < events.length; index++) {
  4633. var event = events[index];
  4634. window.addEventListener(event.name, event.handler, false);
  4635. try {
  4636. if (window.parent) {
  4637. window.parent.addEventListener(event.name, event.handler, false);
  4638. }
  4639. }
  4640. catch (e) {
  4641. }
  4642. }
  4643. };
  4644. Tools.UnregisterTopRootEvents = function (events) {
  4645. for (var index = 0; index < events.length; index++) {
  4646. var event = events[index];
  4647. window.removeEventListener(event.name, event.handler);
  4648. try {
  4649. if (window.parent) {
  4650. window.parent.removeEventListener(event.name, event.handler);
  4651. }
  4652. }
  4653. catch (e) {
  4654. }
  4655. }
  4656. };
  4657. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4658. // Read the contents of the framebuffer
  4659. var numberOfChannelsByLine = width * 4;
  4660. var halfHeight = height / 2;
  4661. //Reading datas from WebGL
  4662. var data = engine.readPixels(0, 0, width, height);
  4663. //To flip image on Y axis.
  4664. for (var i = 0; i < halfHeight; i++) {
  4665. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4666. var currentCell = j + i * numberOfChannelsByLine;
  4667. var targetLine = height - i - 1;
  4668. var targetCell = j + targetLine * numberOfChannelsByLine;
  4669. var temp = data[currentCell];
  4670. data[currentCell] = data[targetCell];
  4671. data[targetCell] = temp;
  4672. }
  4673. }
  4674. // Create a 2D canvas to store the result
  4675. if (!screenshotCanvas) {
  4676. screenshotCanvas = document.createElement('canvas');
  4677. }
  4678. screenshotCanvas.width = width;
  4679. screenshotCanvas.height = height;
  4680. var context = screenshotCanvas.getContext('2d');
  4681. // Copy the pixels to a 2D canvas
  4682. var imageData = context.createImageData(width, height);
  4683. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4684. var castData = imageData.data;
  4685. castData.set(data);
  4686. context.putImageData(imageData, 0, 0);
  4687. var base64Image = screenshotCanvas.toDataURL();
  4688. if (successCallback) {
  4689. successCallback(base64Image);
  4690. }
  4691. else {
  4692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4693. if (("download" in document.createElement("a"))) {
  4694. var a = window.document.createElement("a");
  4695. a.href = base64Image;
  4696. var date = new Date();
  4697. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4698. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4699. window.document.body.appendChild(a);
  4700. a.addEventListener("click", function () {
  4701. a.parentElement.removeChild(a);
  4702. });
  4703. a.click();
  4704. }
  4705. else {
  4706. var newWindow = window.open("");
  4707. var img = newWindow.document.createElement("img");
  4708. img.src = base64Image;
  4709. newWindow.document.body.appendChild(img);
  4710. }
  4711. }
  4712. };
  4713. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4714. var width;
  4715. var height;
  4716. //If a precision value is specified
  4717. if (size.precision) {
  4718. width = Math.round(engine.getRenderWidth() * size.precision);
  4719. height = Math.round(width / engine.getAspectRatio(camera));
  4720. size = { width: width, height: height };
  4721. }
  4722. else if (size.width && size.height) {
  4723. width = size.width;
  4724. height = size.height;
  4725. }
  4726. else if (size.width && !size.height) {
  4727. width = size.width;
  4728. height = Math.round(width / engine.getAspectRatio(camera));
  4729. size = { width: width, height: height };
  4730. }
  4731. else if (size.height && !size.width) {
  4732. height = size.height;
  4733. width = Math.round(height * engine.getAspectRatio(camera));
  4734. size = { width: width, height: height };
  4735. }
  4736. else if (!isNaN(size)) {
  4737. height = size;
  4738. width = size;
  4739. }
  4740. else {
  4741. Tools.Error("Invalid 'size' parameter !");
  4742. return;
  4743. }
  4744. var scene = camera.getScene();
  4745. var previousCamera = null;
  4746. if (scene.activeCamera !== camera) {
  4747. previousCamera = scene.activeCamera;
  4748. scene.activeCamera = camera;
  4749. }
  4750. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4751. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4752. texture.renderList = scene.meshes;
  4753. texture.onAfterRender = function () {
  4754. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4755. };
  4756. scene.incrementRenderId();
  4757. texture.render(true);
  4758. texture.dispose();
  4759. if (previousCamera) {
  4760. scene.activeCamera = previousCamera;
  4761. }
  4762. };
  4763. // XHR response validator for local file scenario
  4764. Tools.ValidateXHRData = function (xhr, dataType) {
  4765. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4766. if (dataType === void 0) { dataType = 7; }
  4767. try {
  4768. if (dataType & 1) {
  4769. if (xhr.responseText && xhr.responseText.length > 0) {
  4770. return true;
  4771. }
  4772. else if (dataType === 1) {
  4773. return false;
  4774. }
  4775. }
  4776. if (dataType & 2) {
  4777. // Check header width and height since there is no "TGA" magic number
  4778. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4779. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4780. return true;
  4781. }
  4782. else if (dataType === 2) {
  4783. return false;
  4784. }
  4785. }
  4786. if (dataType & 4) {
  4787. // Check for the "DDS" magic number
  4788. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4789. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4790. return true;
  4791. }
  4792. else {
  4793. return false;
  4794. }
  4795. }
  4796. }
  4797. catch (e) {
  4798. }
  4799. return false;
  4800. };
  4801. Object.defineProperty(Tools, "NoneLogLevel", {
  4802. get: function () {
  4803. return Tools._NoneLogLevel;
  4804. },
  4805. enumerable: true,
  4806. configurable: true
  4807. });
  4808. Object.defineProperty(Tools, "MessageLogLevel", {
  4809. get: function () {
  4810. return Tools._MessageLogLevel;
  4811. },
  4812. enumerable: true,
  4813. configurable: true
  4814. });
  4815. Object.defineProperty(Tools, "WarningLogLevel", {
  4816. get: function () {
  4817. return Tools._WarningLogLevel;
  4818. },
  4819. enumerable: true,
  4820. configurable: true
  4821. });
  4822. Object.defineProperty(Tools, "ErrorLogLevel", {
  4823. get: function () {
  4824. return Tools._ErrorLogLevel;
  4825. },
  4826. enumerable: true,
  4827. configurable: true
  4828. });
  4829. Object.defineProperty(Tools, "AllLogLevel", {
  4830. get: function () {
  4831. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. Tools._AddLogEntry = function (entry) {
  4837. Tools._LogCache = entry + Tools._LogCache;
  4838. if (Tools.OnNewCacheEntry) {
  4839. Tools.OnNewCacheEntry(entry);
  4840. }
  4841. };
  4842. Tools._FormatMessage = function (message) {
  4843. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4844. var date = new Date();
  4845. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4846. };
  4847. Tools._LogDisabled = function (message) {
  4848. // nothing to do
  4849. };
  4850. Tools._LogEnabled = function (message) {
  4851. var formattedMessage = Tools._FormatMessage(message);
  4852. console.log("BJS - " + formattedMessage);
  4853. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4854. Tools._AddLogEntry(entry);
  4855. };
  4856. Tools._WarnDisabled = function (message) {
  4857. // nothing to do
  4858. };
  4859. Tools._WarnEnabled = function (message) {
  4860. var formattedMessage = Tools._FormatMessage(message);
  4861. console.warn("BJS - " + formattedMessage);
  4862. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4863. Tools._AddLogEntry(entry);
  4864. };
  4865. Tools._ErrorDisabled = function (message) {
  4866. // nothing to do
  4867. };
  4868. Tools._ErrorEnabled = function (message) {
  4869. Tools.errorsCount++;
  4870. var formattedMessage = Tools._FormatMessage(message);
  4871. console.error("BJS - " + formattedMessage);
  4872. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4873. Tools._AddLogEntry(entry);
  4874. };
  4875. Object.defineProperty(Tools, "LogCache", {
  4876. get: function () {
  4877. return Tools._LogCache;
  4878. },
  4879. enumerable: true,
  4880. configurable: true
  4881. });
  4882. Tools.ClearLogCache = function () {
  4883. Tools._LogCache = "";
  4884. Tools.errorsCount = 0;
  4885. };
  4886. Object.defineProperty(Tools, "LogLevels", {
  4887. set: function (level) {
  4888. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4889. Tools.Log = Tools._LogEnabled;
  4890. }
  4891. else {
  4892. Tools.Log = Tools._LogDisabled;
  4893. }
  4894. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4895. Tools.Warn = Tools._WarnEnabled;
  4896. }
  4897. else {
  4898. Tools.Warn = Tools._WarnDisabled;
  4899. }
  4900. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4901. Tools.Error = Tools._ErrorEnabled;
  4902. }
  4903. else {
  4904. Tools.Error = Tools._ErrorDisabled;
  4905. }
  4906. },
  4907. enumerable: true,
  4908. configurable: true
  4909. });
  4910. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4911. get: function () {
  4912. return Tools._PerformanceNoneLogLevel;
  4913. },
  4914. enumerable: true,
  4915. configurable: true
  4916. });
  4917. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4918. get: function () {
  4919. return Tools._PerformanceUserMarkLogLevel;
  4920. },
  4921. enumerable: true,
  4922. configurable: true
  4923. });
  4924. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4925. get: function () {
  4926. return Tools._PerformanceConsoleLogLevel;
  4927. },
  4928. enumerable: true,
  4929. configurable: true
  4930. });
  4931. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4932. set: function (level) {
  4933. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4934. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4935. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4936. return;
  4937. }
  4938. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4939. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4940. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4941. return;
  4942. }
  4943. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4944. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4950. };
  4951. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4952. };
  4953. Tools._StartUserMark = function (counterName, condition) {
  4954. if (condition === void 0) { condition = true; }
  4955. if (!condition || !Tools._performance.mark) {
  4956. return;
  4957. }
  4958. Tools._performance.mark(counterName + "-Begin");
  4959. };
  4960. Tools._EndUserMark = function (counterName, condition) {
  4961. if (condition === void 0) { condition = true; }
  4962. if (!condition || !Tools._performance.mark) {
  4963. return;
  4964. }
  4965. Tools._performance.mark(counterName + "-End");
  4966. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4967. };
  4968. Tools._StartPerformanceConsole = function (counterName, condition) {
  4969. if (condition === void 0) { condition = true; }
  4970. if (!condition) {
  4971. return;
  4972. }
  4973. Tools._StartUserMark(counterName, condition);
  4974. if (console.time) {
  4975. console.time(counterName);
  4976. }
  4977. };
  4978. Tools._EndPerformanceConsole = function (counterName, condition) {
  4979. if (condition === void 0) { condition = true; }
  4980. if (!condition) {
  4981. return;
  4982. }
  4983. Tools._EndUserMark(counterName, condition);
  4984. if (console.time) {
  4985. console.timeEnd(counterName);
  4986. }
  4987. };
  4988. Object.defineProperty(Tools, "Now", {
  4989. get: function () {
  4990. if (window.performance && window.performance.now) {
  4991. return window.performance.now();
  4992. }
  4993. return new Date().getTime();
  4994. },
  4995. enumerable: true,
  4996. configurable: true
  4997. });
  4998. // Deprecated
  4999. Tools.GetFps = function () {
  5000. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  5001. return 0;
  5002. };
  5003. Tools.BaseUrl = "";
  5004. // Logs
  5005. Tools._NoneLogLevel = 0;
  5006. Tools._MessageLogLevel = 1;
  5007. Tools._WarningLogLevel = 2;
  5008. Tools._ErrorLogLevel = 4;
  5009. Tools._LogCache = "";
  5010. Tools.errorsCount = 0;
  5011. Tools.Log = Tools._LogEnabled;
  5012. Tools.Warn = Tools._WarnEnabled;
  5013. Tools.Error = Tools._ErrorEnabled;
  5014. // Performances
  5015. Tools._PerformanceNoneLogLevel = 0;
  5016. Tools._PerformanceUserMarkLogLevel = 1;
  5017. Tools._PerformanceConsoleLogLevel = 2;
  5018. Tools._performance = window.performance;
  5019. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5020. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5021. return Tools;
  5022. })();
  5023. BABYLON.Tools = Tools;
  5024. /**
  5025. * An implementation of a loop for asynchronous functions.
  5026. */
  5027. var AsyncLoop = (function () {
  5028. /**
  5029. * Constroctor.
  5030. * @param iterations the number of iterations.
  5031. * @param _fn the function to run each iteration
  5032. * @param _successCallback the callback that will be called upon succesful execution
  5033. * @param offset starting offset.
  5034. */
  5035. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5036. if (offset === void 0) { offset = 0; }
  5037. this.iterations = iterations;
  5038. this._fn = _fn;
  5039. this._successCallback = _successCallback;
  5040. this.index = offset - 1;
  5041. this._done = false;
  5042. }
  5043. /**
  5044. * Execute the next iteration. Must be called after the last iteration was finished.
  5045. */
  5046. AsyncLoop.prototype.executeNext = function () {
  5047. if (!this._done) {
  5048. if (this.index + 1 < this.iterations) {
  5049. ++this.index;
  5050. this._fn(this);
  5051. }
  5052. else {
  5053. this.breakLoop();
  5054. }
  5055. }
  5056. };
  5057. /**
  5058. * Break the loop and run the success callback.
  5059. */
  5060. AsyncLoop.prototype.breakLoop = function () {
  5061. this._done = true;
  5062. this._successCallback();
  5063. };
  5064. /**
  5065. * Helper function
  5066. */
  5067. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5068. if (offset === void 0) { offset = 0; }
  5069. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5070. loop.executeNext();
  5071. return loop;
  5072. };
  5073. /**
  5074. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5075. * @param iterations total number of iterations
  5076. * @param syncedIterations number of synchronous iterations in each async iteration.
  5077. * @param fn the function to call each iteration.
  5078. * @param callback a success call back that will be called when iterating stops.
  5079. * @param breakFunction a break condition (optional)
  5080. * @param timeout timeout settings for the setTimeout function. default - 0.
  5081. * @constructor
  5082. */
  5083. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5084. if (timeout === void 0) { timeout = 0; }
  5085. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5086. if (breakFunction && breakFunction())
  5087. loop.breakLoop();
  5088. else {
  5089. setTimeout(function () {
  5090. for (var i = 0; i < syncedIterations; ++i) {
  5091. var iteration = (loop.index * syncedIterations) + i;
  5092. if (iteration >= iterations)
  5093. break;
  5094. fn(iteration);
  5095. if (breakFunction && breakFunction()) {
  5096. loop.breakLoop();
  5097. break;
  5098. }
  5099. }
  5100. loop.executeNext();
  5101. }, timeout);
  5102. }
  5103. }, callback);
  5104. };
  5105. return AsyncLoop;
  5106. })();
  5107. BABYLON.AsyncLoop = AsyncLoop;
  5108. })(BABYLON || (BABYLON = {}));
  5109. var BABYLON;
  5110. (function (BABYLON) {
  5111. var _DepthCullingState = (function () {
  5112. function _DepthCullingState() {
  5113. this._isDepthTestDirty = false;
  5114. this._isDepthMaskDirty = false;
  5115. this._isDepthFuncDirty = false;
  5116. this._isCullFaceDirty = false;
  5117. this._isCullDirty = false;
  5118. this._isZOffsetDirty = false;
  5119. }
  5120. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5121. get: function () {
  5122. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5123. },
  5124. enumerable: true,
  5125. configurable: true
  5126. });
  5127. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5128. get: function () {
  5129. return this._zOffset;
  5130. },
  5131. set: function (value) {
  5132. if (this._zOffset === value) {
  5133. return;
  5134. }
  5135. this._zOffset = value;
  5136. this._isZOffsetDirty = true;
  5137. },
  5138. enumerable: true,
  5139. configurable: true
  5140. });
  5141. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5142. get: function () {
  5143. return this._cullFace;
  5144. },
  5145. set: function (value) {
  5146. if (this._cullFace === value) {
  5147. return;
  5148. }
  5149. this._cullFace = value;
  5150. this._isCullFaceDirty = true;
  5151. },
  5152. enumerable: true,
  5153. configurable: true
  5154. });
  5155. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5156. get: function () {
  5157. return this._cull;
  5158. },
  5159. set: function (value) {
  5160. if (this._cull === value) {
  5161. return;
  5162. }
  5163. this._cull = value;
  5164. this._isCullDirty = true;
  5165. },
  5166. enumerable: true,
  5167. configurable: true
  5168. });
  5169. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5170. get: function () {
  5171. return this._depthFunc;
  5172. },
  5173. set: function (value) {
  5174. if (this._depthFunc === value) {
  5175. return;
  5176. }
  5177. this._depthFunc = value;
  5178. this._isDepthFuncDirty = true;
  5179. },
  5180. enumerable: true,
  5181. configurable: true
  5182. });
  5183. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5184. get: function () {
  5185. return this._depthMask;
  5186. },
  5187. set: function (value) {
  5188. if (this._depthMask === value) {
  5189. return;
  5190. }
  5191. this._depthMask = value;
  5192. this._isDepthMaskDirty = true;
  5193. },
  5194. enumerable: true,
  5195. configurable: true
  5196. });
  5197. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5198. get: function () {
  5199. return this._depthTest;
  5200. },
  5201. set: function (value) {
  5202. if (this._depthTest === value) {
  5203. return;
  5204. }
  5205. this._depthTest = value;
  5206. this._isDepthTestDirty = true;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. _DepthCullingState.prototype.reset = function () {
  5212. this._depthMask = true;
  5213. this._depthTest = true;
  5214. this._depthFunc = null;
  5215. this._cull = null;
  5216. this._cullFace = null;
  5217. this._zOffset = 0;
  5218. this._isDepthTestDirty = true;
  5219. this._isDepthMaskDirty = true;
  5220. this._isDepthFuncDirty = false;
  5221. this._isCullFaceDirty = false;
  5222. this._isCullDirty = false;
  5223. this._isZOffsetDirty = false;
  5224. };
  5225. _DepthCullingState.prototype.apply = function (gl) {
  5226. if (!this.isDirty) {
  5227. return;
  5228. }
  5229. // Cull
  5230. if (this._isCullDirty) {
  5231. if (this.cull) {
  5232. gl.enable(gl.CULL_FACE);
  5233. }
  5234. else {
  5235. gl.disable(gl.CULL_FACE);
  5236. }
  5237. this._isCullDirty = false;
  5238. }
  5239. // Cull face
  5240. if (this._isCullFaceDirty) {
  5241. gl.cullFace(this.cullFace);
  5242. this._isCullFaceDirty = false;
  5243. }
  5244. // Depth mask
  5245. if (this._isDepthMaskDirty) {
  5246. gl.depthMask(this.depthMask);
  5247. this._isDepthMaskDirty = false;
  5248. }
  5249. // Depth test
  5250. if (this._isDepthTestDirty) {
  5251. if (this.depthTest) {
  5252. gl.enable(gl.DEPTH_TEST);
  5253. }
  5254. else {
  5255. gl.disable(gl.DEPTH_TEST);
  5256. }
  5257. this._isDepthTestDirty = false;
  5258. }
  5259. // Depth func
  5260. if (this._isDepthFuncDirty) {
  5261. gl.depthFunc(this.depthFunc);
  5262. this._isDepthFuncDirty = false;
  5263. }
  5264. // zOffset
  5265. if (this._isZOffsetDirty) {
  5266. if (this.zOffset) {
  5267. gl.enable(gl.POLYGON_OFFSET_FILL);
  5268. gl.polygonOffset(this.zOffset, 0);
  5269. }
  5270. else {
  5271. gl.disable(gl.POLYGON_OFFSET_FILL);
  5272. }
  5273. this._isZOffsetDirty = false;
  5274. }
  5275. };
  5276. return _DepthCullingState;
  5277. })();
  5278. BABYLON._DepthCullingState = _DepthCullingState;
  5279. var _AlphaState = (function () {
  5280. function _AlphaState() {
  5281. this._isAlphaBlendDirty = false;
  5282. this._isBlendFunctionParametersDirty = false;
  5283. this._alphaBlend = false;
  5284. this._blendFunctionParameters = new Array(4);
  5285. }
  5286. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5287. get: function () {
  5288. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5289. },
  5290. enumerable: true,
  5291. configurable: true
  5292. });
  5293. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5294. get: function () {
  5295. return this._alphaBlend;
  5296. },
  5297. set: function (value) {
  5298. if (this._alphaBlend === value) {
  5299. return;
  5300. }
  5301. this._alphaBlend = value;
  5302. this._isAlphaBlendDirty = true;
  5303. },
  5304. enumerable: true,
  5305. configurable: true
  5306. });
  5307. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5308. if (this._blendFunctionParameters[0] === value0 &&
  5309. this._blendFunctionParameters[1] === value1 &&
  5310. this._blendFunctionParameters[2] === value2 &&
  5311. this._blendFunctionParameters[3] === value3) {
  5312. return;
  5313. }
  5314. this._blendFunctionParameters[0] = value0;
  5315. this._blendFunctionParameters[1] = value1;
  5316. this._blendFunctionParameters[2] = value2;
  5317. this._blendFunctionParameters[3] = value3;
  5318. this._isBlendFunctionParametersDirty = true;
  5319. };
  5320. _AlphaState.prototype.reset = function () {
  5321. this._alphaBlend = false;
  5322. this._blendFunctionParameters[0] = null;
  5323. this._blendFunctionParameters[1] = null;
  5324. this._blendFunctionParameters[2] = null;
  5325. this._blendFunctionParameters[3] = null;
  5326. this._isAlphaBlendDirty = true;
  5327. this._isBlendFunctionParametersDirty = false;
  5328. };
  5329. _AlphaState.prototype.apply = function (gl) {
  5330. if (!this.isDirty) {
  5331. return;
  5332. }
  5333. // Alpha blend
  5334. if (this._isAlphaBlendDirty) {
  5335. if (this._alphaBlend) {
  5336. gl.enable(gl.BLEND);
  5337. }
  5338. else {
  5339. gl.disable(gl.BLEND);
  5340. }
  5341. this._isAlphaBlendDirty = false;
  5342. }
  5343. // Alpha function
  5344. if (this._isBlendFunctionParametersDirty) {
  5345. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5346. this._isBlendFunctionParametersDirty = false;
  5347. }
  5348. };
  5349. return _AlphaState;
  5350. })();
  5351. BABYLON._AlphaState = _AlphaState;
  5352. var compileShader = function (gl, source, type, defines) {
  5353. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5354. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5355. gl.compileShader(shader);
  5356. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5357. throw new Error(gl.getShaderInfoLog(shader));
  5358. }
  5359. return shader;
  5360. };
  5361. var getWebGLTextureType = function (gl, type) {
  5362. var textureType = gl.UNSIGNED_BYTE;
  5363. if (type === Engine.TEXTURETYPE_FLOAT)
  5364. textureType = gl.FLOAT;
  5365. return textureType;
  5366. };
  5367. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5368. var magFilter = gl.NEAREST;
  5369. var minFilter = gl.NEAREST;
  5370. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5371. magFilter = gl.LINEAR;
  5372. if (generateMipMaps) {
  5373. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5374. }
  5375. else {
  5376. minFilter = gl.LINEAR;
  5377. }
  5378. }
  5379. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5380. magFilter = gl.LINEAR;
  5381. if (generateMipMaps) {
  5382. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5383. }
  5384. else {
  5385. minFilter = gl.LINEAR;
  5386. }
  5387. }
  5388. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5389. magFilter = gl.NEAREST;
  5390. if (generateMipMaps) {
  5391. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5392. }
  5393. else {
  5394. minFilter = gl.NEAREST;
  5395. }
  5396. }
  5397. return {
  5398. min: minFilter,
  5399. mag: magFilter
  5400. };
  5401. };
  5402. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5404. var engine = scene.getEngine();
  5405. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5406. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5407. gl.bindTexture(gl.TEXTURE_2D, texture);
  5408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5409. texture._baseWidth = width;
  5410. texture._baseHeight = height;
  5411. texture._width = potWidth;
  5412. texture._height = potHeight;
  5413. texture.isReady = true;
  5414. processFunction(potWidth, potHeight);
  5415. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5418. if (!noMipmap && !isCompressed) {
  5419. gl.generateMipmap(gl.TEXTURE_2D);
  5420. }
  5421. gl.bindTexture(gl.TEXTURE_2D, null);
  5422. engine._activeTexturesCache = [];
  5423. scene._removePendingData(texture);
  5424. };
  5425. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5426. var onload = function () {
  5427. loadedImages[index] = img;
  5428. loadedImages._internalCount++;
  5429. scene._removePendingData(img);
  5430. if (loadedImages._internalCount === 6) {
  5431. onfinish(loadedImages);
  5432. }
  5433. };
  5434. var onerror = function () {
  5435. scene._removePendingData(img);
  5436. };
  5437. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5438. scene._addPendingData(img);
  5439. };
  5440. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5441. var loadedImages = [];
  5442. loadedImages._internalCount = 0;
  5443. for (var index = 0; index < 6; index++) {
  5444. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5445. }
  5446. };
  5447. var EngineCapabilities = (function () {
  5448. function EngineCapabilities() {
  5449. }
  5450. return EngineCapabilities;
  5451. })();
  5452. BABYLON.EngineCapabilities = EngineCapabilities;
  5453. /**
  5454. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5455. */
  5456. var Engine = (function () {
  5457. /**
  5458. * @constructor
  5459. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5460. * @param {boolean} [antialias] - enable antialias
  5461. * @param options - further options to be sent to the getContext function
  5462. */
  5463. function Engine(canvas, antialias, options) {
  5464. var _this = this;
  5465. // Public members
  5466. this.isFullscreen = false;
  5467. this.isPointerLock = false;
  5468. this.cullBackFaces = true;
  5469. this.renderEvenInBackground = true;
  5470. // To enable/disable IDB support and avoid XHR on .manifest
  5471. this.enableOfflineSupport = true;
  5472. this.scenes = new Array();
  5473. this._windowIsBackground = false;
  5474. this._drawCalls = 0;
  5475. this._renderingQueueLaunched = false;
  5476. this._activeRenderLoops = [];
  5477. // FPS
  5478. this.fpsRange = 60;
  5479. this.previousFramesDuration = [];
  5480. this.fps = 60;
  5481. this.deltaTime = 0;
  5482. // States
  5483. this._depthCullingState = new _DepthCullingState();
  5484. this._alphaState = new _AlphaState();
  5485. this._alphaMode = Engine.ALPHA_DISABLE;
  5486. // Cache
  5487. this._loadedTexturesCache = new Array();
  5488. this._activeTexturesCache = new Array();
  5489. this._compiledEffects = {};
  5490. this._uintIndicesCurrentlySet = false;
  5491. this._renderingCanvas = canvas;
  5492. options = options || {};
  5493. options.antialias = antialias;
  5494. if (options.preserveDrawingBuffer === undefined) {
  5495. options.preserveDrawingBuffer = false;
  5496. }
  5497. // GL
  5498. try {
  5499. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5500. }
  5501. catch (e) {
  5502. throw new Error("WebGL not supported");
  5503. }
  5504. if (!this._gl) {
  5505. throw new Error("WebGL not supported");
  5506. }
  5507. this._onBlur = function () {
  5508. _this._windowIsBackground = true;
  5509. };
  5510. this._onFocus = function () {
  5511. _this._windowIsBackground = false;
  5512. };
  5513. window.addEventListener("blur", this._onBlur);
  5514. window.addEventListener("focus", this._onFocus);
  5515. // Viewport
  5516. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5517. this.resize();
  5518. // Caps
  5519. this._caps = new EngineCapabilities();
  5520. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5521. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5522. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5523. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5524. // Infos
  5525. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5526. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5527. if (rendererInfo != null) {
  5528. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5529. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5530. }
  5531. if (!this._glVendor) {
  5532. this._glVendor = "Unknown vendor";
  5533. }
  5534. if (!this._glRenderer) {
  5535. this._glRenderer = "Unknown renderer";
  5536. }
  5537. // Extensions
  5538. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5539. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5540. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5541. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5542. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5543. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5544. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5545. this._caps.highPrecisionShaderSupported = true;
  5546. if (this._gl.getShaderPrecisionFormat) {
  5547. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5548. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5549. }
  5550. // Depth buffer
  5551. this.setDepthBuffer(true);
  5552. this.setDepthFunctionToLessOrEqual();
  5553. this.setDepthWrite(true);
  5554. // Fullscreen
  5555. this._onFullscreenChange = function () {
  5556. if (document.fullscreen !== undefined) {
  5557. _this.isFullscreen = document.fullscreen;
  5558. }
  5559. else if (document.mozFullScreen !== undefined) {
  5560. _this.isFullscreen = document.mozFullScreen;
  5561. }
  5562. else if (document.webkitIsFullScreen !== undefined) {
  5563. _this.isFullscreen = document.webkitIsFullScreen;
  5564. }
  5565. else if (document.msIsFullScreen !== undefined) {
  5566. _this.isFullscreen = document.msIsFullScreen;
  5567. }
  5568. // Pointer lock
  5569. if (_this.isFullscreen && _this._pointerLockRequested) {
  5570. canvas.requestPointerLock = canvas.requestPointerLock ||
  5571. canvas.msRequestPointerLock ||
  5572. canvas.mozRequestPointerLock ||
  5573. canvas.webkitRequestPointerLock;
  5574. if (canvas.requestPointerLock) {
  5575. canvas.requestPointerLock();
  5576. }
  5577. }
  5578. };
  5579. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5580. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5581. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5582. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5583. // Pointer lock
  5584. this._onPointerLockChange = function () {
  5585. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5586. document.webkitPointerLockElement === canvas ||
  5587. document.msPointerLockElement === canvas ||
  5588. document.pointerLockElement === canvas);
  5589. };
  5590. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5591. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5592. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5593. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5594. if (!Engine.audioEngine) {
  5595. Engine.audioEngine = new BABYLON.AudioEngine();
  5596. }
  5597. //default loading screen
  5598. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5599. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5600. }
  5601. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5602. get: function () {
  5603. return Engine._ALPHA_DISABLE;
  5604. },
  5605. enumerable: true,
  5606. configurable: true
  5607. });
  5608. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5609. get: function () {
  5610. return Engine._ALPHA_ONEONE;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(Engine, "ALPHA_ADD", {
  5616. get: function () {
  5617. return Engine._ALPHA_ADD;
  5618. },
  5619. enumerable: true,
  5620. configurable: true
  5621. });
  5622. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5623. get: function () {
  5624. return Engine._ALPHA_COMBINE;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5630. get: function () {
  5631. return Engine._ALPHA_SUBTRACT;
  5632. },
  5633. enumerable: true,
  5634. configurable: true
  5635. });
  5636. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5637. get: function () {
  5638. return Engine._ALPHA_MULTIPLY;
  5639. },
  5640. enumerable: true,
  5641. configurable: true
  5642. });
  5643. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5644. get: function () {
  5645. return Engine._ALPHA_MAXIMIZED;
  5646. },
  5647. enumerable: true,
  5648. configurable: true
  5649. });
  5650. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5651. get: function () {
  5652. return Engine._DELAYLOADSTATE_NONE;
  5653. },
  5654. enumerable: true,
  5655. configurable: true
  5656. });
  5657. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5658. get: function () {
  5659. return Engine._DELAYLOADSTATE_LOADED;
  5660. },
  5661. enumerable: true,
  5662. configurable: true
  5663. });
  5664. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5665. get: function () {
  5666. return Engine._DELAYLOADSTATE_LOADING;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5672. get: function () {
  5673. return Engine._DELAYLOADSTATE_NOTLOADED;
  5674. },
  5675. enumerable: true,
  5676. configurable: true
  5677. });
  5678. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5679. get: function () {
  5680. return Engine._TEXTUREFORMAT_ALPHA;
  5681. },
  5682. enumerable: true,
  5683. configurable: true
  5684. });
  5685. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5686. get: function () {
  5687. return Engine._TEXTUREFORMAT_LUMINANCE;
  5688. },
  5689. enumerable: true,
  5690. configurable: true
  5691. });
  5692. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5693. get: function () {
  5694. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5695. },
  5696. enumerable: true,
  5697. configurable: true
  5698. });
  5699. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5700. get: function () {
  5701. return Engine._TEXTUREFORMAT_RGB;
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5707. get: function () {
  5708. return Engine._TEXTUREFORMAT_RGBA;
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5714. get: function () {
  5715. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5716. },
  5717. enumerable: true,
  5718. configurable: true
  5719. });
  5720. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5721. get: function () {
  5722. return Engine._TEXTURETYPE_FLOAT;
  5723. },
  5724. enumerable: true,
  5725. configurable: true
  5726. });
  5727. Object.defineProperty(Engine, "Version", {
  5728. get: function () {
  5729. return "2.3.0-alpha";
  5730. },
  5731. enumerable: true,
  5732. configurable: true
  5733. });
  5734. Engine.prototype._prepareWorkingCanvas = function () {
  5735. if (this._workingCanvas) {
  5736. return;
  5737. }
  5738. this._workingCanvas = document.createElement("canvas");
  5739. this._workingContext = this._workingCanvas.getContext("2d");
  5740. };
  5741. Engine.prototype.getGlInfo = function () {
  5742. return {
  5743. vendor: this._glVendor,
  5744. renderer: this._glRenderer,
  5745. version: this._glVersion
  5746. };
  5747. };
  5748. Engine.prototype.getAspectRatio = function (camera) {
  5749. var viewport = camera.viewport;
  5750. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5751. };
  5752. Engine.prototype.getRenderWidth = function () {
  5753. if (this._currentRenderTarget) {
  5754. return this._currentRenderTarget._width;
  5755. }
  5756. return this._renderingCanvas.width;
  5757. };
  5758. Engine.prototype.getRenderHeight = function () {
  5759. if (this._currentRenderTarget) {
  5760. return this._currentRenderTarget._height;
  5761. }
  5762. return this._renderingCanvas.height;
  5763. };
  5764. Engine.prototype.getRenderingCanvas = function () {
  5765. return this._renderingCanvas;
  5766. };
  5767. Engine.prototype.getRenderingCanvasClientRect = function () {
  5768. return this._renderingCanvas.getBoundingClientRect();
  5769. };
  5770. Engine.prototype.setHardwareScalingLevel = function (level) {
  5771. this._hardwareScalingLevel = level;
  5772. this.resize();
  5773. };
  5774. Engine.prototype.getHardwareScalingLevel = function () {
  5775. return this._hardwareScalingLevel;
  5776. };
  5777. Engine.prototype.getLoadedTexturesCache = function () {
  5778. return this._loadedTexturesCache;
  5779. };
  5780. Engine.prototype.getCaps = function () {
  5781. return this._caps;
  5782. };
  5783. Object.defineProperty(Engine.prototype, "drawCalls", {
  5784. get: function () {
  5785. return this._drawCalls;
  5786. },
  5787. enumerable: true,
  5788. configurable: true
  5789. });
  5790. // Methods
  5791. Engine.prototype.resetDrawCalls = function () {
  5792. this._drawCalls = 0;
  5793. };
  5794. Engine.prototype.setDepthFunctionToGreater = function () {
  5795. this._depthCullingState.depthFunc = this._gl.GREATER;
  5796. };
  5797. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5798. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5799. };
  5800. Engine.prototype.setDepthFunctionToLess = function () {
  5801. this._depthCullingState.depthFunc = this._gl.LESS;
  5802. };
  5803. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5804. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5805. };
  5806. /**
  5807. * stop executing a render loop function and remove it from the execution array
  5808. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5809. */
  5810. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5811. if (!renderFunction) {
  5812. this._activeRenderLoops = [];
  5813. return;
  5814. }
  5815. var index = this._activeRenderLoops.indexOf(renderFunction);
  5816. if (index >= 0) {
  5817. this._activeRenderLoops.splice(index, 1);
  5818. }
  5819. };
  5820. Engine.prototype._renderLoop = function () {
  5821. var _this = this;
  5822. var shouldRender = true;
  5823. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5824. shouldRender = false;
  5825. }
  5826. if (shouldRender) {
  5827. // Start new frame
  5828. this.beginFrame();
  5829. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5830. var renderFunction = this._activeRenderLoops[index];
  5831. renderFunction();
  5832. }
  5833. // Present
  5834. this.endFrame();
  5835. }
  5836. if (this._activeRenderLoops.length > 0) {
  5837. // Register new frame
  5838. BABYLON.Tools.QueueNewFrame(function () {
  5839. _this._renderLoop();
  5840. });
  5841. }
  5842. else {
  5843. this._renderingQueueLaunched = false;
  5844. }
  5845. };
  5846. /**
  5847. * Register and execute a render loop. The engine can have more than one render function.
  5848. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5849. * @example
  5850. * engine.runRenderLoop(function () {
  5851. * scene.render()
  5852. * })
  5853. */
  5854. Engine.prototype.runRenderLoop = function (renderFunction) {
  5855. var _this = this;
  5856. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5857. return;
  5858. }
  5859. this._activeRenderLoops.push(renderFunction);
  5860. if (!this._renderingQueueLaunched) {
  5861. this._renderingQueueLaunched = true;
  5862. BABYLON.Tools.QueueNewFrame(function () {
  5863. _this._renderLoop();
  5864. });
  5865. }
  5866. };
  5867. /**
  5868. * Toggle full screen mode.
  5869. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5870. */
  5871. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5872. if (this.isFullscreen) {
  5873. BABYLON.Tools.ExitFullscreen();
  5874. }
  5875. else {
  5876. this._pointerLockRequested = requestPointerLock;
  5877. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5878. }
  5879. };
  5880. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5881. this.applyStates();
  5882. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5883. if (this._depthCullingState.depthMask) {
  5884. this._gl.clearDepth(1.0);
  5885. }
  5886. var mode = 0;
  5887. if (backBuffer)
  5888. mode |= this._gl.COLOR_BUFFER_BIT;
  5889. if (depthStencil && this._depthCullingState.depthMask)
  5890. mode |= this._gl.DEPTH_BUFFER_BIT;
  5891. this._gl.clear(mode);
  5892. };
  5893. /**
  5894. * Set the WebGL's viewport
  5895. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5896. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5897. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5898. */
  5899. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5900. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5901. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5902. var x = viewport.x || 0;
  5903. var y = viewport.y || 0;
  5904. this._cachedViewport = viewport;
  5905. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5906. };
  5907. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5908. this._cachedViewport = null;
  5909. this._gl.viewport(x, y, width, height);
  5910. };
  5911. Engine.prototype.beginFrame = function () {
  5912. this._measureFps();
  5913. };
  5914. Engine.prototype.endFrame = function () {
  5915. //this.flushFramebuffer();
  5916. };
  5917. /**
  5918. * resize the view according to the canvas' size.
  5919. * @example
  5920. * window.addEventListener("resize", function () {
  5921. * engine.resize();
  5922. * });
  5923. */
  5924. Engine.prototype.resize = function () {
  5925. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5926. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5927. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5928. };
  5929. /**
  5930. * force a specific size of the canvas
  5931. * @param {number} width - the new canvas' width
  5932. * @param {number} height - the new canvas' height
  5933. */
  5934. Engine.prototype.setSize = function (width, height) {
  5935. this._renderingCanvas.width = width;
  5936. this._renderingCanvas.height = height;
  5937. for (var index = 0; index < this.scenes.length; index++) {
  5938. var scene = this.scenes[index];
  5939. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5940. var cam = scene.cameras[camIndex];
  5941. cam._currentRenderId = 0;
  5942. }
  5943. }
  5944. };
  5945. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5946. this._currentRenderTarget = texture;
  5947. var gl = this._gl;
  5948. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5949. if (texture.isCube) {
  5950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5951. }
  5952. else {
  5953. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5954. }
  5955. this._gl.viewport(0, 0, texture._width, texture._height);
  5956. this.wipeCaches();
  5957. };
  5958. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5959. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5960. this._currentRenderTarget = null;
  5961. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5962. var gl = this._gl;
  5963. gl.bindTexture(gl.TEXTURE_2D, texture);
  5964. gl.generateMipmap(gl.TEXTURE_2D);
  5965. gl.bindTexture(gl.TEXTURE_2D, null);
  5966. }
  5967. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5968. };
  5969. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5970. if (texture.generateMipMaps) {
  5971. var gl = this._gl;
  5972. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5973. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5974. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5975. }
  5976. };
  5977. Engine.prototype.flushFramebuffer = function () {
  5978. this._gl.flush();
  5979. };
  5980. Engine.prototype.restoreDefaultFramebuffer = function () {
  5981. this._currentRenderTarget = null;
  5982. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5983. this.setViewport(this._cachedViewport);
  5984. this.wipeCaches();
  5985. };
  5986. // VBOs
  5987. Engine.prototype._resetVertexBufferBinding = function () {
  5988. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5989. this._cachedVertexBuffers = null;
  5990. };
  5991. Engine.prototype.createVertexBuffer = function (vertices) {
  5992. var vbo = this._gl.createBuffer();
  5993. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5994. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5995. this._resetVertexBufferBinding();
  5996. vbo.references = 1;
  5997. return vbo;
  5998. };
  5999. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6000. var vbo = this._gl.createBuffer();
  6001. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6002. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6003. this._resetVertexBufferBinding();
  6004. vbo.references = 1;
  6005. return vbo;
  6006. };
  6007. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6008. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6009. if (offset === undefined) {
  6010. offset = 0;
  6011. }
  6012. if (vertices instanceof Float32Array) {
  6013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6014. }
  6015. else {
  6016. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6017. }
  6018. this._resetVertexBufferBinding();
  6019. };
  6020. Engine.prototype._resetIndexBufferBinding = function () {
  6021. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6022. this._cachedIndexBuffer = null;
  6023. };
  6024. Engine.prototype.createIndexBuffer = function (indices) {
  6025. var vbo = this._gl.createBuffer();
  6026. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6027. // Check for 32 bits indices
  6028. var arrayBuffer;
  6029. var need32Bits = false;
  6030. if (this._caps.uintIndices) {
  6031. for (var index = 0; index < indices.length; index++) {
  6032. if (indices[index] > 65535) {
  6033. need32Bits = true;
  6034. break;
  6035. }
  6036. }
  6037. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6038. }
  6039. else {
  6040. arrayBuffer = new Uint16Array(indices);
  6041. }
  6042. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6043. this._resetIndexBufferBinding();
  6044. vbo.references = 1;
  6045. vbo.is32Bits = need32Bits;
  6046. return vbo;
  6047. };
  6048. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6049. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6050. this._cachedVertexBuffers = vertexBuffer;
  6051. this._cachedEffectForVertexBuffers = effect;
  6052. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6053. var offset = 0;
  6054. for (var index = 0; index < vertexDeclaration.length; index++) {
  6055. var order = effect.getAttributeLocation(index);
  6056. if (order >= 0) {
  6057. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6058. }
  6059. offset += vertexDeclaration[index] * 4;
  6060. }
  6061. }
  6062. if (this._cachedIndexBuffer !== indexBuffer) {
  6063. this._cachedIndexBuffer = indexBuffer;
  6064. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6065. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6066. }
  6067. };
  6068. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6069. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6070. this._cachedVertexBuffers = vertexBuffers;
  6071. this._cachedEffectForVertexBuffers = effect;
  6072. var attributes = effect.getAttributesNames();
  6073. for (var index = 0; index < attributes.length; index++) {
  6074. var order = effect.getAttributeLocation(index);
  6075. if (order >= 0) {
  6076. var vertexBuffer = vertexBuffers[attributes[index]];
  6077. if (!vertexBuffer) {
  6078. continue;
  6079. }
  6080. var stride = vertexBuffer.getStrideSize();
  6081. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6082. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6083. }
  6084. }
  6085. }
  6086. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6087. this._cachedIndexBuffer = indexBuffer;
  6088. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6089. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6090. }
  6091. };
  6092. Engine.prototype._releaseBuffer = function (buffer) {
  6093. buffer.references--;
  6094. if (buffer.references === 0) {
  6095. this._gl.deleteBuffer(buffer);
  6096. return true;
  6097. }
  6098. return false;
  6099. };
  6100. Engine.prototype.createInstancesBuffer = function (capacity) {
  6101. var buffer = this._gl.createBuffer();
  6102. buffer.capacity = capacity;
  6103. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6104. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6105. return buffer;
  6106. };
  6107. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6108. this._gl.deleteBuffer(buffer);
  6109. };
  6110. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6111. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6113. for (var index = 0; index < 4; index++) {
  6114. var offsetLocation = offsetLocations[index];
  6115. this._gl.enableVertexAttribArray(offsetLocation);
  6116. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6117. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6118. }
  6119. };
  6120. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6121. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6122. for (var index = 0; index < 4; index++) {
  6123. var offsetLocation = offsetLocations[index];
  6124. this._gl.disableVertexAttribArray(offsetLocation);
  6125. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6126. }
  6127. };
  6128. Engine.prototype.applyStates = function () {
  6129. this._depthCullingState.apply(this._gl);
  6130. this._alphaState.apply(this._gl);
  6131. };
  6132. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6133. // Apply states
  6134. this.applyStates();
  6135. this._drawCalls++;
  6136. // Render
  6137. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6138. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6139. if (instancesCount) {
  6140. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6141. return;
  6142. }
  6143. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6144. };
  6145. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6146. // Apply states
  6147. this.applyStates();
  6148. this._drawCalls++;
  6149. if (instancesCount) {
  6150. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6151. return;
  6152. }
  6153. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6154. };
  6155. // Shaders
  6156. Engine.prototype._releaseEffect = function (effect) {
  6157. if (this._compiledEffects[effect._key]) {
  6158. delete this._compiledEffects[effect._key];
  6159. if (effect.getProgram()) {
  6160. this._gl.deleteProgram(effect.getProgram());
  6161. }
  6162. }
  6163. };
  6164. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6165. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6166. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6167. var name = vertex + "+" + fragment + "@" + defines;
  6168. if (this._compiledEffects[name]) {
  6169. return this._compiledEffects[name];
  6170. }
  6171. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6172. effect._key = name;
  6173. this._compiledEffects[name] = effect;
  6174. return effect;
  6175. };
  6176. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6177. if (uniformsNames === void 0) { uniformsNames = []; }
  6178. if (samplers === void 0) { samplers = []; }
  6179. if (defines === void 0) { defines = ""; }
  6180. return this.createEffect({
  6181. vertex: "particles",
  6182. fragmentElement: fragmentName
  6183. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6184. };
  6185. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6186. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6187. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6188. var shaderProgram = this._gl.createProgram();
  6189. this._gl.attachShader(shaderProgram, vertexShader);
  6190. this._gl.attachShader(shaderProgram, fragmentShader);
  6191. this._gl.linkProgram(shaderProgram);
  6192. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6193. if (!linked) {
  6194. var error = this._gl.getProgramInfoLog(shaderProgram);
  6195. if (error) {
  6196. throw new Error(error);
  6197. }
  6198. }
  6199. this._gl.deleteShader(vertexShader);
  6200. this._gl.deleteShader(fragmentShader);
  6201. return shaderProgram;
  6202. };
  6203. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6204. var results = [];
  6205. for (var index = 0; index < uniformsNames.length; index++) {
  6206. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6207. }
  6208. return results;
  6209. };
  6210. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6211. var results = [];
  6212. for (var index = 0; index < attributesNames.length; index++) {
  6213. try {
  6214. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6215. }
  6216. catch (e) {
  6217. results.push(-1);
  6218. }
  6219. }
  6220. return results;
  6221. };
  6222. Engine.prototype.enableEffect = function (effect) {
  6223. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6224. if (effect && effect.onBind) {
  6225. effect.onBind(effect);
  6226. }
  6227. return;
  6228. }
  6229. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6230. // Use program
  6231. this._gl.useProgram(effect.getProgram());
  6232. for (var i in this._vertexAttribArrays) {
  6233. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6234. continue;
  6235. }
  6236. this._vertexAttribArrays[i] = false;
  6237. this._gl.disableVertexAttribArray(i);
  6238. }
  6239. var attributesCount = effect.getAttributesCount();
  6240. for (var index = 0; index < attributesCount; index++) {
  6241. // Attributes
  6242. var order = effect.getAttributeLocation(index);
  6243. if (order >= 0) {
  6244. this._vertexAttribArrays[order] = true;
  6245. this._gl.enableVertexAttribArray(order);
  6246. }
  6247. }
  6248. this._currentEffect = effect;
  6249. if (effect.onBind) {
  6250. effect.onBind(effect);
  6251. }
  6252. };
  6253. Engine.prototype.setArray = function (uniform, array) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniform1fv(uniform, array);
  6257. };
  6258. Engine.prototype.setArray2 = function (uniform, array) {
  6259. if (!uniform || array.length % 2 !== 0)
  6260. return;
  6261. this._gl.uniform2fv(uniform, array);
  6262. };
  6263. Engine.prototype.setArray3 = function (uniform, array) {
  6264. if (!uniform || array.length % 3 !== 0)
  6265. return;
  6266. this._gl.uniform3fv(uniform, array);
  6267. };
  6268. Engine.prototype.setArray4 = function (uniform, array) {
  6269. if (!uniform || array.length % 4 !== 0)
  6270. return;
  6271. this._gl.uniform4fv(uniform, array);
  6272. };
  6273. Engine.prototype.setMatrices = function (uniform, matrices) {
  6274. if (!uniform)
  6275. return;
  6276. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6277. };
  6278. Engine.prototype.setMatrix = function (uniform, matrix) {
  6279. if (!uniform)
  6280. return;
  6281. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6282. };
  6283. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6284. if (!uniform)
  6285. return;
  6286. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6287. };
  6288. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6289. if (!uniform)
  6290. return;
  6291. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6292. };
  6293. Engine.prototype.setFloat = function (uniform, value) {
  6294. if (!uniform)
  6295. return;
  6296. this._gl.uniform1f(uniform, value);
  6297. };
  6298. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6299. if (!uniform)
  6300. return;
  6301. this._gl.uniform2f(uniform, x, y);
  6302. };
  6303. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6304. if (!uniform)
  6305. return;
  6306. this._gl.uniform3f(uniform, x, y, z);
  6307. };
  6308. Engine.prototype.setBool = function (uniform, bool) {
  6309. if (!uniform)
  6310. return;
  6311. this._gl.uniform1i(uniform, bool);
  6312. };
  6313. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6314. if (!uniform)
  6315. return;
  6316. this._gl.uniform4f(uniform, x, y, z, w);
  6317. };
  6318. Engine.prototype.setColor3 = function (uniform, color3) {
  6319. if (!uniform)
  6320. return;
  6321. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6322. };
  6323. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6324. if (!uniform)
  6325. return;
  6326. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6327. };
  6328. // States
  6329. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6330. if (zOffset === void 0) { zOffset = 0; }
  6331. if (reverseSide === void 0) { reverseSide = false; }
  6332. // Culling
  6333. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6334. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6335. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6336. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6337. if (culling) {
  6338. this._depthCullingState.cullFace = cullFace;
  6339. this._depthCullingState.cull = true;
  6340. }
  6341. else {
  6342. this._depthCullingState.cull = false;
  6343. }
  6344. }
  6345. // Z offset
  6346. this._depthCullingState.zOffset = zOffset;
  6347. };
  6348. Engine.prototype.setDepthBuffer = function (enable) {
  6349. this._depthCullingState.depthTest = enable;
  6350. };
  6351. Engine.prototype.getDepthWrite = function () {
  6352. return this._depthCullingState.depthMask;
  6353. };
  6354. Engine.prototype.setDepthWrite = function (enable) {
  6355. this._depthCullingState.depthMask = enable;
  6356. };
  6357. Engine.prototype.setColorWrite = function (enable) {
  6358. this._gl.colorMask(enable, enable, enable, enable);
  6359. };
  6360. Engine.prototype.setAlphaMode = function (mode) {
  6361. if (this._alphaMode === mode) {
  6362. return;
  6363. }
  6364. switch (mode) {
  6365. case Engine.ALPHA_DISABLE:
  6366. this.setDepthWrite(true);
  6367. this._alphaState.alphaBlend = false;
  6368. break;
  6369. case Engine.ALPHA_COMBINE:
  6370. this.setDepthWrite(false);
  6371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6372. this._alphaState.alphaBlend = true;
  6373. break;
  6374. case Engine.ALPHA_ONEONE:
  6375. this.setDepthWrite(false);
  6376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6377. this._alphaState.alphaBlend = true;
  6378. break;
  6379. case Engine.ALPHA_ADD:
  6380. this.setDepthWrite(false);
  6381. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6382. this._alphaState.alphaBlend = true;
  6383. break;
  6384. case Engine.ALPHA_SUBTRACT:
  6385. this.setDepthWrite(false);
  6386. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6387. this._alphaState.alphaBlend = true;
  6388. break;
  6389. case Engine.ALPHA_MULTIPLY:
  6390. this.setDepthWrite(false);
  6391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6392. this._alphaState.alphaBlend = true;
  6393. break;
  6394. case Engine.ALPHA_MAXIMIZED:
  6395. this.setDepthWrite(false);
  6396. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6397. this._alphaState.alphaBlend = true;
  6398. break;
  6399. }
  6400. this._alphaMode = mode;
  6401. };
  6402. Engine.prototype.getAlphaMode = function () {
  6403. return this._alphaMode;
  6404. };
  6405. Engine.prototype.setAlphaTesting = function (enable) {
  6406. this._alphaTest = enable;
  6407. };
  6408. Engine.prototype.getAlphaTesting = function () {
  6409. return this._alphaTest;
  6410. };
  6411. // Textures
  6412. Engine.prototype.wipeCaches = function () {
  6413. this._activeTexturesCache = [];
  6414. this._currentEffect = null;
  6415. this._depthCullingState.reset();
  6416. this._alphaState.reset();
  6417. this._cachedVertexBuffers = null;
  6418. this._cachedIndexBuffer = null;
  6419. this._cachedEffectForVertexBuffers = null;
  6420. };
  6421. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6422. var gl = this._gl;
  6423. gl.bindTexture(gl.TEXTURE_2D, texture);
  6424. var magFilter = gl.NEAREST;
  6425. var minFilter = gl.NEAREST;
  6426. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6427. magFilter = gl.LINEAR;
  6428. minFilter = gl.LINEAR;
  6429. }
  6430. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6431. magFilter = gl.LINEAR;
  6432. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6433. }
  6434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6436. gl.bindTexture(gl.TEXTURE_2D, null);
  6437. texture.samplingMode = samplingMode;
  6438. };
  6439. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6440. var _this = this;
  6441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6442. if (onLoad === void 0) { onLoad = null; }
  6443. if (onError === void 0) { onError = null; }
  6444. if (buffer === void 0) { buffer = null; }
  6445. var texture = this._gl.createTexture();
  6446. var extension;
  6447. var fromData = false;
  6448. if (url.substr(0, 5) === "data:") {
  6449. fromData = true;
  6450. }
  6451. if (!fromData)
  6452. extension = url.substr(url.length - 4, 4).toLowerCase();
  6453. else {
  6454. var oldUrl = url;
  6455. fromData = oldUrl.split(':');
  6456. url = oldUrl;
  6457. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6458. }
  6459. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6460. var isTGA = (extension === ".tga");
  6461. scene._addPendingData(texture);
  6462. texture.url = url;
  6463. texture.noMipmap = noMipmap;
  6464. texture.references = 1;
  6465. texture.samplingMode = samplingMode;
  6466. this._loadedTexturesCache.push(texture);
  6467. var onerror = function () {
  6468. scene._removePendingData(texture);
  6469. if (onError) {
  6470. onError();
  6471. }
  6472. };
  6473. var callback;
  6474. if (isTGA) {
  6475. callback = function (arrayBuffer) {
  6476. var data = new Uint8Array(arrayBuffer);
  6477. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6478. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6479. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6480. if (onLoad) {
  6481. onLoad();
  6482. }
  6483. }, samplingMode);
  6484. };
  6485. if (!(fromData instanceof Array))
  6486. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6487. callback(arrayBuffer);
  6488. }, onerror, scene.database, true);
  6489. else
  6490. callback(buffer);
  6491. }
  6492. else if (isDDS) {
  6493. callback = function (data) {
  6494. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6495. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6496. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6497. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6498. if (onLoad) {
  6499. onLoad();
  6500. }
  6501. }, samplingMode);
  6502. };
  6503. if (!(fromData instanceof Array))
  6504. BABYLON.Tools.LoadFile(url, function (data) {
  6505. callback(data);
  6506. }, onerror, scene.database, true);
  6507. else
  6508. callback(buffer);
  6509. }
  6510. else {
  6511. var onload = function (img) {
  6512. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6513. var isPot = (img.width === potWidth && img.height === potHeight);
  6514. if (!isPot) {
  6515. _this._prepareWorkingCanvas();
  6516. _this._workingCanvas.width = potWidth;
  6517. _this._workingCanvas.height = potHeight;
  6518. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6519. _this._workingContext.imageSmoothingEnabled = false;
  6520. _this._workingContext.mozImageSmoothingEnabled = false;
  6521. _this._workingContext.oImageSmoothingEnabled = false;
  6522. _this._workingContext.webkitImageSmoothingEnabled = false;
  6523. _this._workingContext.msImageSmoothingEnabled = false;
  6524. }
  6525. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6526. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6527. _this._workingContext.imageSmoothingEnabled = true;
  6528. _this._workingContext.mozImageSmoothingEnabled = true;
  6529. _this._workingContext.oImageSmoothingEnabled = true;
  6530. _this._workingContext.webkitImageSmoothingEnabled = true;
  6531. _this._workingContext.msImageSmoothingEnabled = true;
  6532. }
  6533. }
  6534. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6535. if (onLoad) {
  6536. onLoad();
  6537. }
  6538. }, samplingMode);
  6539. };
  6540. if (!(fromData instanceof Array))
  6541. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6542. else
  6543. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6544. }
  6545. return texture;
  6546. };
  6547. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6548. if (compression === void 0) { compression = null; }
  6549. var internalFormat = this._gl.RGBA;
  6550. switch (format) {
  6551. case Engine.TEXTUREFORMAT_ALPHA:
  6552. internalFormat = this._gl.ALPHA;
  6553. break;
  6554. case Engine.TEXTUREFORMAT_LUMINANCE:
  6555. internalFormat = this._gl.LUMINANCE;
  6556. break;
  6557. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6558. internalFormat = this._gl.LUMINANCE_ALPHA;
  6559. break;
  6560. case Engine.TEXTUREFORMAT_RGB:
  6561. internalFormat = this._gl.RGB;
  6562. break;
  6563. case Engine.TEXTUREFORMAT_RGBA:
  6564. internalFormat = this._gl.RGBA;
  6565. break;
  6566. }
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6568. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6569. if (compression) {
  6570. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6571. }
  6572. else {
  6573. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6574. }
  6575. if (texture.generateMipMaps) {
  6576. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6577. }
  6578. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6579. this._activeTexturesCache = [];
  6580. texture.isReady = true;
  6581. };
  6582. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6583. if (compression === void 0) { compression = null; }
  6584. var texture = this._gl.createTexture();
  6585. texture._baseWidth = width;
  6586. texture._baseHeight = height;
  6587. texture._width = width;
  6588. texture._height = height;
  6589. texture.references = 1;
  6590. this.updateRawTexture(texture, data, format, invertY, compression);
  6591. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6592. // Filters
  6593. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6597. texture.samplingMode = samplingMode;
  6598. this._loadedTexturesCache.push(texture);
  6599. return texture;
  6600. };
  6601. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6602. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6603. var texture = this._gl.createTexture();
  6604. texture._baseWidth = width;
  6605. texture._baseHeight = height;
  6606. if (forceExponantOfTwo) {
  6607. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6608. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6609. }
  6610. this._activeTexturesCache = [];
  6611. texture._width = width;
  6612. texture._height = height;
  6613. texture.isReady = false;
  6614. texture.generateMipMaps = generateMipMaps;
  6615. texture.references = 1;
  6616. texture.samplingMode = samplingMode;
  6617. this.updateTextureSamplingMode(samplingMode, texture);
  6618. this._loadedTexturesCache.push(texture);
  6619. return texture;
  6620. };
  6621. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6622. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6623. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6626. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6627. };
  6628. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6629. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6630. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6631. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6632. if (texture.generateMipMaps) {
  6633. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6634. }
  6635. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6636. this._activeTexturesCache = [];
  6637. texture.isReady = true;
  6638. };
  6639. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6640. if (texture._isDisabled) {
  6641. return;
  6642. }
  6643. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6644. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6645. try {
  6646. // Testing video texture support
  6647. if (this._videoTextureSupported === undefined) {
  6648. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6649. if (this._gl.getError() !== 0) {
  6650. this._videoTextureSupported = false;
  6651. }
  6652. else {
  6653. this._videoTextureSupported = true;
  6654. }
  6655. }
  6656. // Copy video through the current working canvas if video texture is not supported
  6657. if (!this._videoTextureSupported) {
  6658. if (!texture._workingCanvas) {
  6659. texture._workingCanvas = document.createElement("canvas");
  6660. texture._workingContext = texture._workingCanvas.getContext("2d");
  6661. texture._workingCanvas.width = texture._width;
  6662. texture._workingCanvas.height = texture._height;
  6663. }
  6664. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6665. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6666. }
  6667. else {
  6668. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6669. }
  6670. if (texture.generateMipMaps) {
  6671. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6672. }
  6673. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6674. this._activeTexturesCache = [];
  6675. texture.isReady = true;
  6676. }
  6677. catch (ex) {
  6678. // Something unexpected
  6679. // Let's disable the texture
  6680. texture._isDisabled = true;
  6681. }
  6682. };
  6683. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6684. // old version had a "generateMipMaps" arg instead of options.
  6685. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6686. // in the same way, generateDepthBuffer is defaulted to true
  6687. var generateMipMaps = false;
  6688. var generateDepthBuffer = true;
  6689. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6690. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6691. if (options !== undefined) {
  6692. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6693. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6694. type = options.type === undefined ? type : options.type;
  6695. if (options.samplingMode !== undefined) {
  6696. samplingMode = options.samplingMode;
  6697. }
  6698. if (type === Engine.TEXTURETYPE_FLOAT) {
  6699. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6700. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6701. }
  6702. }
  6703. var gl = this._gl;
  6704. var texture = gl.createTexture();
  6705. gl.bindTexture(gl.TEXTURE_2D, texture);
  6706. var width = size.width || size;
  6707. var height = size.height || size;
  6708. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6709. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6710. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6711. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6712. }
  6713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6717. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6718. var depthBuffer;
  6719. // Create the depth buffer
  6720. if (generateDepthBuffer) {
  6721. depthBuffer = gl.createRenderbuffer();
  6722. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6723. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6724. }
  6725. // Create the framebuffer
  6726. var framebuffer = gl.createFramebuffer();
  6727. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6728. if (generateDepthBuffer) {
  6729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6730. }
  6731. if (generateMipMaps) {
  6732. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6733. }
  6734. // Unbind
  6735. gl.bindTexture(gl.TEXTURE_2D, null);
  6736. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6737. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6738. texture._framebuffer = framebuffer;
  6739. if (generateDepthBuffer) {
  6740. texture._depthBuffer = depthBuffer;
  6741. }
  6742. texture._width = width;
  6743. texture._height = height;
  6744. texture.isReady = true;
  6745. texture.generateMipMaps = generateMipMaps;
  6746. texture.references = 1;
  6747. texture.samplingMode = samplingMode;
  6748. this._activeTexturesCache = [];
  6749. this._loadedTexturesCache.push(texture);
  6750. return texture;
  6751. };
  6752. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6753. var gl = this._gl;
  6754. var texture = gl.createTexture();
  6755. var generateMipMaps = true;
  6756. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6757. if (options !== undefined) {
  6758. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6759. if (options.samplingMode !== undefined) {
  6760. samplingMode = options.samplingMode;
  6761. }
  6762. }
  6763. texture.isCube = true;
  6764. texture.references = 1;
  6765. texture.generateMipMaps = generateMipMaps;
  6766. texture.references = 1;
  6767. texture.samplingMode = samplingMode;
  6768. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6769. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6770. for (var face = 0; face < 6; face++) {
  6771. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6772. }
  6773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6777. // Create the depth buffer
  6778. var depthBuffer = gl.createRenderbuffer();
  6779. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6780. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6781. // Create the framebuffer
  6782. var framebuffer = gl.createFramebuffer();
  6783. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6784. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6785. // Unbind
  6786. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6787. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6788. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6789. texture._framebuffer = framebuffer;
  6790. texture._depthBuffer = depthBuffer;
  6791. this._activeTexturesCache = [];
  6792. texture._width = size;
  6793. texture._height = size;
  6794. texture.isReady = true;
  6795. return texture;
  6796. };
  6797. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6798. var _this = this;
  6799. var gl = this._gl;
  6800. var texture = gl.createTexture();
  6801. texture.isCube = true;
  6802. texture.url = rootUrl;
  6803. texture.references = 1;
  6804. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6805. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6806. if (isDDS) {
  6807. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6808. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6809. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6810. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6811. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6812. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6813. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6814. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6815. }
  6816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6820. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6821. _this._activeTexturesCache = [];
  6822. texture._width = info.width;
  6823. texture._height = info.height;
  6824. texture.isReady = true;
  6825. }, null, null, true);
  6826. }
  6827. else {
  6828. cascadeLoad(rootUrl, scene, function (imgs) {
  6829. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6830. var height = width;
  6831. _this._prepareWorkingCanvas();
  6832. _this._workingCanvas.width = width;
  6833. _this._workingCanvas.height = height;
  6834. var faces = [
  6835. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6836. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6837. ];
  6838. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6839. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6840. for (var index = 0; index < faces.length; index++) {
  6841. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6842. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6843. }
  6844. if (!noMipmap) {
  6845. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6846. }
  6847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6851. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6852. _this._activeTexturesCache = [];
  6853. texture._width = width;
  6854. texture._height = height;
  6855. texture.isReady = true;
  6856. }, extensions);
  6857. }
  6858. return texture;
  6859. };
  6860. Engine.prototype._releaseTexture = function (texture) {
  6861. var gl = this._gl;
  6862. if (texture._framebuffer) {
  6863. gl.deleteFramebuffer(texture._framebuffer);
  6864. }
  6865. if (texture._depthBuffer) {
  6866. gl.deleteRenderbuffer(texture._depthBuffer);
  6867. }
  6868. gl.deleteTexture(texture);
  6869. // Unbind channels
  6870. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6871. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6872. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6873. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6874. this._activeTexturesCache[channel] = null;
  6875. }
  6876. var index = this._loadedTexturesCache.indexOf(texture);
  6877. if (index !== -1) {
  6878. this._loadedTexturesCache.splice(index, 1);
  6879. }
  6880. };
  6881. Engine.prototype.bindSamplers = function (effect) {
  6882. this._gl.useProgram(effect.getProgram());
  6883. var samplers = effect.getSamplers();
  6884. for (var index = 0; index < samplers.length; index++) {
  6885. var uniform = effect.getUniform(samplers[index]);
  6886. this._gl.uniform1i(uniform, index);
  6887. }
  6888. this._currentEffect = null;
  6889. };
  6890. Engine.prototype._bindTexture = function (channel, texture) {
  6891. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6892. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6893. this._activeTexturesCache[channel] = null;
  6894. };
  6895. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6896. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6897. };
  6898. Engine.prototype.setTexture = function (channel, texture) {
  6899. if (channel < 0) {
  6900. return;
  6901. }
  6902. // Not ready?
  6903. if (!texture || !texture.isReady()) {
  6904. if (this._activeTexturesCache[channel] != null) {
  6905. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6906. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6907. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6908. this._activeTexturesCache[channel] = null;
  6909. }
  6910. return;
  6911. }
  6912. // Video
  6913. if (texture instanceof BABYLON.VideoTexture) {
  6914. if (texture.update()) {
  6915. this._activeTexturesCache[channel] = null;
  6916. }
  6917. }
  6918. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6919. texture.delayLoad();
  6920. return;
  6921. }
  6922. if (this._activeTexturesCache[channel] === texture) {
  6923. return;
  6924. }
  6925. this._activeTexturesCache[channel] = texture;
  6926. var internalTexture = texture.getInternalTexture();
  6927. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6928. if (internalTexture.isCube) {
  6929. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6930. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6931. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6932. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6933. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6934. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6935. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6936. }
  6937. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6938. }
  6939. else {
  6940. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6941. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6942. internalTexture._cachedWrapU = texture.wrapU;
  6943. switch (texture.wrapU) {
  6944. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6945. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6946. break;
  6947. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6948. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6949. break;
  6950. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6951. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6952. break;
  6953. }
  6954. }
  6955. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6956. internalTexture._cachedWrapV = texture.wrapV;
  6957. switch (texture.wrapV) {
  6958. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6959. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6960. break;
  6961. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6962. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6963. break;
  6964. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6965. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6966. break;
  6967. }
  6968. }
  6969. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6970. }
  6971. };
  6972. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6973. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6974. var value = texture.anisotropicFilteringLevel;
  6975. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6976. value = 1;
  6977. }
  6978. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6979. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6980. texture._cachedAnisotropicFilteringLevel = value;
  6981. }
  6982. };
  6983. Engine.prototype.readPixels = function (x, y, width, height) {
  6984. var data = new Uint8Array(height * width * 4);
  6985. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6986. return data;
  6987. };
  6988. Engine.prototype.releaseInternalTexture = function (texture) {
  6989. if (!texture) {
  6990. return;
  6991. }
  6992. texture.references--;
  6993. // Final reference ?
  6994. if (texture.references === 0) {
  6995. var texturesCache = this.getLoadedTexturesCache();
  6996. var index = texturesCache.indexOf(texture);
  6997. if (index > -1) {
  6998. texturesCache.splice(index, 1);
  6999. }
  7000. this._releaseTexture(texture);
  7001. }
  7002. };
  7003. // Dispose
  7004. Engine.prototype.dispose = function () {
  7005. this.hideLoadingUI();
  7006. this.stopRenderLoop();
  7007. // Release scenes
  7008. while (this.scenes.length) {
  7009. this.scenes[0].dispose();
  7010. }
  7011. // Release audio engine
  7012. Engine.audioEngine.dispose();
  7013. // Release effects
  7014. for (var name in this._compiledEffects) {
  7015. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7016. }
  7017. // Unbind
  7018. for (var i in this._vertexAttribArrays) {
  7019. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  7020. continue;
  7021. }
  7022. this._gl.disableVertexAttribArray(i);
  7023. }
  7024. this._gl = null;
  7025. // Events
  7026. window.removeEventListener("blur", this._onBlur);
  7027. window.removeEventListener("focus", this._onFocus);
  7028. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7029. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7030. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7031. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7032. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7033. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7034. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7035. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7036. };
  7037. // Loading screen
  7038. Engine.prototype.displayLoadingUI = function () {
  7039. this._loadingScreen.displayLoadingUI();
  7040. };
  7041. Engine.prototype.hideLoadingUI = function () {
  7042. this._loadingScreen.hideLoadingUI();
  7043. };
  7044. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7045. get: function () {
  7046. return this._loadingScreen;
  7047. },
  7048. set: function (loadingScreen) {
  7049. this._loadingScreen = loadingScreen;
  7050. },
  7051. enumerable: true,
  7052. configurable: true
  7053. });
  7054. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7055. set: function (text) {
  7056. this._loadingScreen.loadingUIText = text;
  7057. },
  7058. enumerable: true,
  7059. configurable: true
  7060. });
  7061. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7062. set: function (color) {
  7063. this._loadingScreen.loadingUIBackgroundColor = color;
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. // FPS
  7069. Engine.prototype.getFps = function () {
  7070. return this.fps;
  7071. };
  7072. Engine.prototype.getDeltaTime = function () {
  7073. return this.deltaTime;
  7074. };
  7075. Engine.prototype._measureFps = function () {
  7076. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7077. var length = this.previousFramesDuration.length;
  7078. if (length >= 2) {
  7079. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7080. }
  7081. if (length >= this.fpsRange) {
  7082. if (length > this.fpsRange) {
  7083. this.previousFramesDuration.splice(0, 1);
  7084. length = this.previousFramesDuration.length;
  7085. }
  7086. var sum = 0;
  7087. for (var id = 0; id < length - 1; id++) {
  7088. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7089. }
  7090. this.fps = 1000.0 / (sum / (length - 1));
  7091. }
  7092. };
  7093. // Statics
  7094. Engine.isSupported = function () {
  7095. try {
  7096. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7097. if (navigator.isCocoonJS) {
  7098. return true;
  7099. }
  7100. var tempcanvas = document.createElement("canvas");
  7101. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7102. return gl != null && !!window.WebGLRenderingContext;
  7103. }
  7104. catch (e) {
  7105. return false;
  7106. }
  7107. };
  7108. // Const statics
  7109. Engine._ALPHA_DISABLE = 0;
  7110. Engine._ALPHA_ADD = 1;
  7111. Engine._ALPHA_COMBINE = 2;
  7112. Engine._ALPHA_SUBTRACT = 3;
  7113. Engine._ALPHA_MULTIPLY = 4;
  7114. Engine._ALPHA_MAXIMIZED = 5;
  7115. Engine._ALPHA_ONEONE = 6;
  7116. Engine._DELAYLOADSTATE_NONE = 0;
  7117. Engine._DELAYLOADSTATE_LOADED = 1;
  7118. Engine._DELAYLOADSTATE_LOADING = 2;
  7119. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7120. Engine._TEXTUREFORMAT_ALPHA = 0;
  7121. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7122. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7123. Engine._TEXTUREFORMAT_RGB = 4;
  7124. Engine._TEXTUREFORMAT_RGBA = 5;
  7125. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7126. Engine._TEXTURETYPE_FLOAT = 1;
  7127. // Updatable statics so stick with vars here
  7128. Engine.Epsilon = 0.001;
  7129. Engine.CollisionsEpsilon = 0.001;
  7130. Engine.CodeRepository = "src/";
  7131. Engine.ShadersRepository = "src/Shaders/";
  7132. return Engine;
  7133. })();
  7134. BABYLON.Engine = Engine;
  7135. })(BABYLON || (BABYLON = {}));
  7136. var BABYLON;
  7137. (function (BABYLON) {
  7138. /**
  7139. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7140. */
  7141. var Node = (function () {
  7142. /**
  7143. * @constructor
  7144. * @param {string} name - the name and id to be given to this node
  7145. * @param {BABYLON.Scene} the scene this node will be added to
  7146. */
  7147. function Node(name, scene) {
  7148. this.state = "";
  7149. this.animations = new Array();
  7150. this._childrenFlag = -1;
  7151. this._isEnabled = true;
  7152. this._isReady = true;
  7153. this._currentRenderId = -1;
  7154. this._parentRenderId = -1;
  7155. this.name = name;
  7156. this.id = name;
  7157. this._scene = scene;
  7158. this._initCache();
  7159. }
  7160. Node.prototype.getScene = function () {
  7161. return this._scene;
  7162. };
  7163. Node.prototype.getEngine = function () {
  7164. return this._scene.getEngine();
  7165. };
  7166. // override it in derived class
  7167. Node.prototype.getWorldMatrix = function () {
  7168. return BABYLON.Matrix.Identity();
  7169. };
  7170. // override it in derived class if you add new variables to the cache
  7171. // and call the parent class method
  7172. Node.prototype._initCache = function () {
  7173. this._cache = {};
  7174. this._cache.parent = undefined;
  7175. };
  7176. Node.prototype.updateCache = function (force) {
  7177. if (!force && this.isSynchronized())
  7178. return;
  7179. this._cache.parent = this.parent;
  7180. this._updateCache();
  7181. };
  7182. // override it in derived class if you add new variables to the cache
  7183. // and call the parent class method if !ignoreParentClass
  7184. Node.prototype._updateCache = function (ignoreParentClass) {
  7185. };
  7186. // override it in derived class if you add new variables to the cache
  7187. Node.prototype._isSynchronized = function () {
  7188. return true;
  7189. };
  7190. Node.prototype._markSyncedWithParent = function () {
  7191. this._parentRenderId = this.parent._currentRenderId;
  7192. };
  7193. Node.prototype.isSynchronizedWithParent = function () {
  7194. if (!this.parent) {
  7195. return true;
  7196. }
  7197. if (this._parentRenderId !== this.parent._currentRenderId) {
  7198. return false;
  7199. }
  7200. return this.parent.isSynchronized();
  7201. };
  7202. Node.prototype.isSynchronized = function (updateCache) {
  7203. var check = this.hasNewParent();
  7204. check = check || !this.isSynchronizedWithParent();
  7205. check = check || !this._isSynchronized();
  7206. if (updateCache)
  7207. this.updateCache(true);
  7208. return !check;
  7209. };
  7210. Node.prototype.hasNewParent = function (update) {
  7211. if (this._cache.parent === this.parent)
  7212. return false;
  7213. if (update)
  7214. this._cache.parent = this.parent;
  7215. return true;
  7216. };
  7217. /**
  7218. * Is this node ready to be used/rendered
  7219. * @return {boolean} is it ready
  7220. */
  7221. Node.prototype.isReady = function () {
  7222. return this._isReady;
  7223. };
  7224. /**
  7225. * Is this node enabled.
  7226. * If the node has a parent and is enabled, the parent will be inspected as well.
  7227. * @return {boolean} whether this node (and its parent) is enabled.
  7228. * @see setEnabled
  7229. */
  7230. Node.prototype.isEnabled = function () {
  7231. if (!this._isEnabled) {
  7232. return false;
  7233. }
  7234. if (this.parent) {
  7235. return this.parent.isEnabled();
  7236. }
  7237. return true;
  7238. };
  7239. /**
  7240. * Set the enabled state of this node.
  7241. * @param {boolean} value - the new enabled state
  7242. * @see isEnabled
  7243. */
  7244. Node.prototype.setEnabled = function (value) {
  7245. this._isEnabled = value;
  7246. };
  7247. /**
  7248. * Is this node a descendant of the given node.
  7249. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7250. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7251. * @see parent
  7252. */
  7253. Node.prototype.isDescendantOf = function (ancestor) {
  7254. if (this.parent) {
  7255. if (this.parent === ancestor) {
  7256. return true;
  7257. }
  7258. return this.parent.isDescendantOf(ancestor);
  7259. }
  7260. return false;
  7261. };
  7262. Node.prototype._getDescendants = function (list, results) {
  7263. for (var index = 0; index < list.length; index++) {
  7264. var item = list[index];
  7265. if (item.isDescendantOf(this)) {
  7266. results.push(item);
  7267. }
  7268. }
  7269. };
  7270. /**
  7271. * Will return all nodes that have this node as parent.
  7272. * @return {BABYLON.Node[]} all children nodes of all types.
  7273. */
  7274. Node.prototype.getDescendants = function () {
  7275. var results = [];
  7276. this._getDescendants(this._scene.meshes, results);
  7277. this._getDescendants(this._scene.lights, results);
  7278. this._getDescendants(this._scene.cameras, results);
  7279. return results;
  7280. };
  7281. Node.prototype._setReady = function (state) {
  7282. if (state == this._isReady) {
  7283. return;
  7284. }
  7285. if (!state) {
  7286. this._isReady = false;
  7287. return;
  7288. }
  7289. this._isReady = true;
  7290. if (this.onReady) {
  7291. this.onReady(this);
  7292. }
  7293. };
  7294. return Node;
  7295. })();
  7296. BABYLON.Node = Node;
  7297. })(BABYLON || (BABYLON = {}));
  7298. var BABYLON;
  7299. (function (BABYLON) {
  7300. var FilesInput = (function () {
  7301. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7302. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7303. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7304. this._engine = p_engine;
  7305. this._canvas = p_canvas;
  7306. this._currentScene = p_scene;
  7307. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7308. this._progressCallback = p_progressCallback;
  7309. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7310. this._textureLoadingCallback = p_textureLoadingCallback;
  7311. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7312. }
  7313. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7314. var _this = this;
  7315. if (p_elementToMonitor) {
  7316. this._elementToMonitor = p_elementToMonitor;
  7317. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7318. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7319. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7320. }
  7321. };
  7322. FilesInput.prototype.renderFunction = function () {
  7323. if (this._additionnalRenderLoopLogicCallback) {
  7324. this._additionnalRenderLoopLogicCallback();
  7325. }
  7326. if (this._currentScene) {
  7327. if (this._textureLoadingCallback) {
  7328. var remaining = this._currentScene.getWaitingItemsCount();
  7329. if (remaining > 0) {
  7330. this._textureLoadingCallback(remaining);
  7331. }
  7332. }
  7333. this._currentScene.render();
  7334. }
  7335. };
  7336. FilesInput.prototype.drag = function (e) {
  7337. e.stopPropagation();
  7338. e.preventDefault();
  7339. };
  7340. FilesInput.prototype.drop = function (eventDrop) {
  7341. eventDrop.stopPropagation();
  7342. eventDrop.preventDefault();
  7343. this.loadFiles(eventDrop);
  7344. };
  7345. FilesInput.prototype.loadFiles = function (event) {
  7346. if (this._startingProcessingFilesCallback)
  7347. this._startingProcessingFilesCallback();
  7348. // Handling data transfer via drag'n'drop
  7349. if (event && event.dataTransfer && event.dataTransfer.files) {
  7350. this._filesToLoad = event.dataTransfer.files;
  7351. }
  7352. // Handling files from input files
  7353. if (event && event.target && event.target.files) {
  7354. this._filesToLoad = event.target.files;
  7355. }
  7356. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7357. for (var i = 0; i < this._filesToLoad.length; i++) {
  7358. switch (this._filesToLoad[i].type) {
  7359. case "image/jpeg":
  7360. case "image/png":
  7361. case "image/bmp":
  7362. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7363. break;
  7364. case "image/targa":
  7365. case "image/vnd.ms-dds":
  7366. case "audio/wav":
  7367. case "audio/x-wav":
  7368. case "audio/mp3":
  7369. case "audio/mpeg":
  7370. case "audio/mpeg3":
  7371. case "audio/x-mpeg-3":
  7372. case "audio/ogg":
  7373. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7374. break;
  7375. default:
  7376. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7377. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7378. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7379. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7380. this._sceneFileToLoad = this._filesToLoad[i];
  7381. }
  7382. break;
  7383. }
  7384. }
  7385. this.reload();
  7386. }
  7387. };
  7388. FilesInput.prototype.reload = function () {
  7389. var _this = this;
  7390. var that = this;
  7391. // If a ".babylon" file has been provided
  7392. if (this._sceneFileToLoad) {
  7393. if (this._currentScene) {
  7394. if (BABYLON.Tools.errorsCount > 0) {
  7395. BABYLON.Tools.ClearLogCache();
  7396. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7397. }
  7398. this._engine.stopRenderLoop();
  7399. this._currentScene.dispose();
  7400. }
  7401. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7402. that._currentScene = newScene;
  7403. // Wait for textures and shaders to be ready
  7404. that._currentScene.executeWhenReady(function () {
  7405. // Attach camera to canvas inputs
  7406. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7407. that._currentScene.createDefaultCameraOrLight();
  7408. }
  7409. that._currentScene.activeCamera.attachControl(that._canvas);
  7410. if (that._sceneLoadedCallback) {
  7411. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7412. }
  7413. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7414. });
  7415. }, function (progress) {
  7416. if (_this._progressCallback) {
  7417. _this._progressCallback(progress);
  7418. }
  7419. });
  7420. }
  7421. else {
  7422. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7423. }
  7424. };
  7425. FilesInput.FilesTextures = new Array();
  7426. FilesInput.FilesToLoad = new Array();
  7427. return FilesInput;
  7428. })();
  7429. BABYLON.FilesInput = FilesInput;
  7430. })(BABYLON || (BABYLON = {}));
  7431. var BABYLON;
  7432. (function (BABYLON) {
  7433. var IntersectionInfo = (function () {
  7434. function IntersectionInfo(bu, bv, distance) {
  7435. this.bu = bu;
  7436. this.bv = bv;
  7437. this.distance = distance;
  7438. this.faceId = 0;
  7439. this.subMeshId = 0;
  7440. }
  7441. return IntersectionInfo;
  7442. })();
  7443. BABYLON.IntersectionInfo = IntersectionInfo;
  7444. var PickingInfo = (function () {
  7445. function PickingInfo() {
  7446. this.hit = false;
  7447. this.distance = 0;
  7448. this.pickedPoint = null;
  7449. this.pickedMesh = null;
  7450. this.bu = 0;
  7451. this.bv = 0;
  7452. this.faceId = -1;
  7453. this.subMeshId = 0;
  7454. }
  7455. // Methods
  7456. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7457. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7458. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7459. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7460. return null;
  7461. }
  7462. var indices = this.pickedMesh.getIndices();
  7463. var result;
  7464. if (useVerticesNormals) {
  7465. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7466. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7467. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7468. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7469. normal0 = normal0.scale(this.bu);
  7470. normal1 = normal1.scale(this.bv);
  7471. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7472. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7473. }
  7474. else {
  7475. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7476. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7477. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7478. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7479. var p1p2 = vertex1.subtract(vertex2);
  7480. var p3p2 = vertex3.subtract(vertex2);
  7481. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7482. }
  7483. if (useWorldCoordinates) {
  7484. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7485. }
  7486. return BABYLON.Vector3.Normalize(result);
  7487. };
  7488. PickingInfo.prototype.getTextureCoordinates = function () {
  7489. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7490. return null;
  7491. }
  7492. var indices = this.pickedMesh.getIndices();
  7493. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7494. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7495. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7496. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7497. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7498. uv1 = uv1.scale(this.bu);
  7499. uv2 = uv2.scale(this.bv);
  7500. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7501. };
  7502. return PickingInfo;
  7503. })();
  7504. BABYLON.PickingInfo = PickingInfo;
  7505. })(BABYLON || (BABYLON = {}));
  7506. var BABYLON;
  7507. (function (BABYLON) {
  7508. var BoundingSphere = (function () {
  7509. function BoundingSphere(minimum, maximum) {
  7510. this.minimum = minimum;
  7511. this.maximum = maximum;
  7512. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7513. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7514. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7515. this.radius = distance * 0.5;
  7516. this.centerWorld = BABYLON.Vector3.Zero();
  7517. this._update(BABYLON.Matrix.Identity());
  7518. }
  7519. // Methods
  7520. BoundingSphere.prototype._update = function (world) {
  7521. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7522. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7523. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7524. };
  7525. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7526. for (var i = 0; i < 6; i++) {
  7527. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7528. return false;
  7529. }
  7530. return true;
  7531. };
  7532. BoundingSphere.prototype.intersectsPoint = function (point) {
  7533. var x = this.centerWorld.x - point.x;
  7534. var y = this.centerWorld.y - point.y;
  7535. var z = this.centerWorld.z - point.z;
  7536. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7537. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7538. return false;
  7539. return true;
  7540. };
  7541. // Statics
  7542. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7543. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7544. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7545. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7546. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7547. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7548. return false;
  7549. return true;
  7550. };
  7551. return BoundingSphere;
  7552. })();
  7553. BABYLON.BoundingSphere = BoundingSphere;
  7554. })(BABYLON || (BABYLON = {}));
  7555. var BABYLON;
  7556. (function (BABYLON) {
  7557. var BoundingBox = (function () {
  7558. function BoundingBox(minimum, maximum) {
  7559. this.minimum = minimum;
  7560. this.maximum = maximum;
  7561. this.vectors = new Array();
  7562. this.vectorsWorld = new Array();
  7563. // Bounding vectors
  7564. this.vectors.push(this.minimum.clone());
  7565. this.vectors.push(this.maximum.clone());
  7566. this.vectors.push(this.minimum.clone());
  7567. this.vectors[2].x = this.maximum.x;
  7568. this.vectors.push(this.minimum.clone());
  7569. this.vectors[3].y = this.maximum.y;
  7570. this.vectors.push(this.minimum.clone());
  7571. this.vectors[4].z = this.maximum.z;
  7572. this.vectors.push(this.maximum.clone());
  7573. this.vectors[5].z = this.minimum.z;
  7574. this.vectors.push(this.maximum.clone());
  7575. this.vectors[6].x = this.minimum.x;
  7576. this.vectors.push(this.maximum.clone());
  7577. this.vectors[7].y = this.minimum.y;
  7578. // OBB
  7579. this.center = this.maximum.add(this.minimum).scale(0.5);
  7580. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7581. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7582. // World
  7583. for (var index = 0; index < this.vectors.length; index++) {
  7584. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7585. }
  7586. this.minimumWorld = BABYLON.Vector3.Zero();
  7587. this.maximumWorld = BABYLON.Vector3.Zero();
  7588. this._update(BABYLON.Matrix.Identity());
  7589. }
  7590. // Methods
  7591. BoundingBox.prototype.getWorldMatrix = function () {
  7592. return this._worldMatrix;
  7593. };
  7594. BoundingBox.prototype._update = function (world) {
  7595. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7596. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7597. for (var index = 0; index < this.vectors.length; index++) {
  7598. var v = this.vectorsWorld[index];
  7599. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7600. if (v.x < this.minimumWorld.x)
  7601. this.minimumWorld.x = v.x;
  7602. if (v.y < this.minimumWorld.y)
  7603. this.minimumWorld.y = v.y;
  7604. if (v.z < this.minimumWorld.z)
  7605. this.minimumWorld.z = v.z;
  7606. if (v.x > this.maximumWorld.x)
  7607. this.maximumWorld.x = v.x;
  7608. if (v.y > this.maximumWorld.y)
  7609. this.maximumWorld.y = v.y;
  7610. if (v.z > this.maximumWorld.z)
  7611. this.maximumWorld.z = v.z;
  7612. }
  7613. // OBB
  7614. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7615. this.center.scaleInPlace(0.5);
  7616. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7617. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7618. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7619. this._worldMatrix = world;
  7620. };
  7621. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7622. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7623. };
  7624. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7625. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7626. };
  7627. BoundingBox.prototype.intersectsPoint = function (point) {
  7628. var delta = -BABYLON.Engine.Epsilon;
  7629. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7630. return false;
  7631. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7632. return false;
  7633. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7634. return false;
  7635. return true;
  7636. };
  7637. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7638. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7639. };
  7640. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7641. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7642. return false;
  7643. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7644. return false;
  7645. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7646. return false;
  7647. return true;
  7648. };
  7649. // Statics
  7650. BoundingBox.Intersects = function (box0, box1) {
  7651. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7652. return false;
  7653. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7654. return false;
  7655. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7656. return false;
  7657. return true;
  7658. };
  7659. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7660. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7661. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7662. return (num <= (sphereRadius * sphereRadius));
  7663. };
  7664. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7665. for (var p = 0; p < 6; p++) {
  7666. for (var i = 0; i < 8; i++) {
  7667. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7668. return false;
  7669. }
  7670. }
  7671. }
  7672. return true;
  7673. };
  7674. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7675. for (var p = 0; p < 6; p++) {
  7676. var inCount = 8;
  7677. for (var i = 0; i < 8; i++) {
  7678. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7679. --inCount;
  7680. }
  7681. else {
  7682. break;
  7683. }
  7684. }
  7685. if (inCount === 0)
  7686. return false;
  7687. }
  7688. return true;
  7689. };
  7690. return BoundingBox;
  7691. })();
  7692. BABYLON.BoundingBox = BoundingBox;
  7693. })(BABYLON || (BABYLON = {}));
  7694. var BABYLON;
  7695. (function (BABYLON) {
  7696. var computeBoxExtents = function (axis, box) {
  7697. var p = BABYLON.Vector3.Dot(box.center, axis);
  7698. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7699. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7700. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7701. var r = r0 + r1 + r2;
  7702. return {
  7703. min: p - r,
  7704. max: p + r
  7705. };
  7706. };
  7707. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7708. var axisOverlap = function (axis, box0, box1) {
  7709. var result0 = computeBoxExtents(axis, box0);
  7710. var result1 = computeBoxExtents(axis, box1);
  7711. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7712. };
  7713. var BoundingInfo = (function () {
  7714. function BoundingInfo(minimum, maximum) {
  7715. this.minimum = minimum;
  7716. this.maximum = maximum;
  7717. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7718. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7719. }
  7720. // Methods
  7721. BoundingInfo.prototype._update = function (world) {
  7722. this.boundingBox._update(world);
  7723. this.boundingSphere._update(world);
  7724. };
  7725. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7726. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7727. return false;
  7728. return this.boundingBox.isInFrustum(frustumPlanes);
  7729. };
  7730. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7731. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7732. };
  7733. BoundingInfo.prototype._checkCollision = function (collider) {
  7734. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7735. };
  7736. BoundingInfo.prototype.intersectsPoint = function (point) {
  7737. if (!this.boundingSphere.centerWorld) {
  7738. return false;
  7739. }
  7740. if (!this.boundingSphere.intersectsPoint(point)) {
  7741. return false;
  7742. }
  7743. if (!this.boundingBox.intersectsPoint(point)) {
  7744. return false;
  7745. }
  7746. return true;
  7747. };
  7748. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7749. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7750. return false;
  7751. }
  7752. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7753. return false;
  7754. }
  7755. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7756. return false;
  7757. }
  7758. if (!precise) {
  7759. return true;
  7760. }
  7761. var box0 = this.boundingBox;
  7762. var box1 = boundingInfo.boundingBox;
  7763. if (!axisOverlap(box0.directions[0], box0, box1))
  7764. return false;
  7765. if (!axisOverlap(box0.directions[1], box0, box1))
  7766. return false;
  7767. if (!axisOverlap(box0.directions[2], box0, box1))
  7768. return false;
  7769. if (!axisOverlap(box1.directions[0], box0, box1))
  7770. return false;
  7771. if (!axisOverlap(box1.directions[1], box0, box1))
  7772. return false;
  7773. if (!axisOverlap(box1.directions[2], box0, box1))
  7774. return false;
  7775. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7776. return false;
  7777. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7778. return false;
  7779. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7780. return false;
  7781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7782. return false;
  7783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7784. return false;
  7785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7786. return false;
  7787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7788. return false;
  7789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7790. return false;
  7791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7792. return false;
  7793. return true;
  7794. };
  7795. return BoundingInfo;
  7796. })();
  7797. BABYLON.BoundingInfo = BoundingInfo;
  7798. })(BABYLON || (BABYLON = {}));
  7799. var BABYLON;
  7800. (function (BABYLON) {
  7801. var AbstractMesh = (function (_super) {
  7802. __extends(AbstractMesh, _super);
  7803. function AbstractMesh(name, scene) {
  7804. var _this = this;
  7805. _super.call(this, name, scene);
  7806. // Properties
  7807. this.definedFacingForward = true; // orientation for POV movement & rotation
  7808. this.position = new BABYLON.Vector3(0, 0, 0);
  7809. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7810. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7811. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7812. this.visibility = 1.0;
  7813. this.alphaIndex = Number.MAX_VALUE;
  7814. this.infiniteDistance = false;
  7815. this.isVisible = true;
  7816. this.isPickable = true;
  7817. this.showBoundingBox = false;
  7818. this.showSubMeshesBoundingBox = false;
  7819. this.onDispose = null;
  7820. this.isBlocker = false;
  7821. this.renderingGroupId = 0;
  7822. this.receiveShadows = false;
  7823. this.renderOutline = false;
  7824. this.outlineColor = BABYLON.Color3.Red();
  7825. this.outlineWidth = 0.02;
  7826. this.renderOverlay = false;
  7827. this.overlayColor = BABYLON.Color3.Red();
  7828. this.overlayAlpha = 0.5;
  7829. this.hasVertexAlpha = false;
  7830. this.useVertexColors = true;
  7831. this.applyFog = true;
  7832. this.computeBonesUsingShaders = true;
  7833. this.scalingDeterminant = 1;
  7834. this.useOctreeForRenderingSelection = true;
  7835. this.useOctreeForPicking = true;
  7836. this.useOctreeForCollisions = true;
  7837. this.layerMask = 0x0FFFFFFF;
  7838. this.alwaysSelectAsActiveMesh = false;
  7839. // Physics
  7840. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7841. // Collisions
  7842. this._checkCollisions = false;
  7843. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7844. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7845. this._collider = new BABYLON.Collider();
  7846. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7847. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7848. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7849. // Edges
  7850. this.edgesWidth = 1;
  7851. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7852. // Cache
  7853. this._localScaling = BABYLON.Matrix.Zero();
  7854. this._localRotation = BABYLON.Matrix.Zero();
  7855. this._localTranslation = BABYLON.Matrix.Zero();
  7856. this._localBillboard = BABYLON.Matrix.Zero();
  7857. this._localPivotScaling = BABYLON.Matrix.Zero();
  7858. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7859. this._localWorld = BABYLON.Matrix.Zero();
  7860. this._worldMatrix = BABYLON.Matrix.Zero();
  7861. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7862. this._absolutePosition = BABYLON.Vector3.Zero();
  7863. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7864. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7865. this._isDirty = false;
  7866. this._pivotMatrix = BABYLON.Matrix.Identity();
  7867. this._isDisposed = false;
  7868. this._renderId = 0;
  7869. this._intersectionsInProgress = new Array();
  7870. this._onAfterWorldMatrixUpdate = new Array();
  7871. this._isWorldMatrixFrozen = false;
  7872. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7873. if (collidedMesh === void 0) { collidedMesh = null; }
  7874. //TODO move this to the collision coordinator!
  7875. if (_this.getScene().workerCollisions)
  7876. newPosition.multiplyInPlace(_this._collider.radius);
  7877. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7878. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7879. _this.position.addInPlace(_this._diffPositionForCollisions);
  7880. }
  7881. if (_this.onCollide && collidedMesh) {
  7882. _this.onCollide(collidedMesh);
  7883. }
  7884. };
  7885. scene.addMesh(this);
  7886. }
  7887. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7888. get: function () {
  7889. return AbstractMesh._BILLBOARDMODE_NONE;
  7890. },
  7891. enumerable: true,
  7892. configurable: true
  7893. });
  7894. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7895. get: function () {
  7896. return AbstractMesh._BILLBOARDMODE_X;
  7897. },
  7898. enumerable: true,
  7899. configurable: true
  7900. });
  7901. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7902. get: function () {
  7903. return AbstractMesh._BILLBOARDMODE_Y;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7909. get: function () {
  7910. return AbstractMesh._BILLBOARDMODE_Z;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7916. get: function () {
  7917. return AbstractMesh._BILLBOARDMODE_ALL;
  7918. },
  7919. enumerable: true,
  7920. configurable: true
  7921. });
  7922. // Methods
  7923. AbstractMesh.prototype.disableEdgesRendering = function () {
  7924. if (this._edgesRenderer !== undefined) {
  7925. this._edgesRenderer.dispose();
  7926. this._edgesRenderer = undefined;
  7927. }
  7928. };
  7929. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7930. if (epsilon === void 0) { epsilon = 0.95; }
  7931. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7932. this.disableEdgesRendering();
  7933. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7934. };
  7935. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7936. get: function () {
  7937. return false;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. AbstractMesh.prototype.getLOD = function (camera) {
  7943. return this;
  7944. };
  7945. AbstractMesh.prototype.getTotalVertices = function () {
  7946. return 0;
  7947. };
  7948. AbstractMesh.prototype.getIndices = function () {
  7949. return null;
  7950. };
  7951. AbstractMesh.prototype.getVerticesData = function (kind) {
  7952. return null;
  7953. };
  7954. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7955. return false;
  7956. };
  7957. AbstractMesh.prototype.getBoundingInfo = function () {
  7958. if (this._masterMesh) {
  7959. return this._masterMesh.getBoundingInfo();
  7960. }
  7961. if (!this._boundingInfo) {
  7962. this._updateBoundingInfo();
  7963. }
  7964. return this._boundingInfo;
  7965. };
  7966. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7967. get: function () {
  7968. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. AbstractMesh.prototype._preActivate = function () {
  7974. };
  7975. AbstractMesh.prototype._activate = function (renderId) {
  7976. this._renderId = renderId;
  7977. };
  7978. AbstractMesh.prototype.getWorldMatrix = function () {
  7979. if (this._masterMesh) {
  7980. return this._masterMesh.getWorldMatrix();
  7981. }
  7982. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7983. this.computeWorldMatrix();
  7984. }
  7985. return this._worldMatrix;
  7986. };
  7987. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7988. get: function () {
  7989. return this._worldMatrix;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7995. get: function () {
  7996. return this._absolutePosition;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8002. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8003. this.computeWorldMatrix(true);
  8004. this._isWorldMatrixFrozen = true;
  8005. };
  8006. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8007. this._isWorldMatrixFrozen = false;
  8008. this.computeWorldMatrix(true);
  8009. };
  8010. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8011. get: function () {
  8012. return this._isWorldMatrixFrozen;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8018. axis.normalize();
  8019. if (!this.rotationQuaternion) {
  8020. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8021. this.rotation = BABYLON.Vector3.Zero();
  8022. }
  8023. var rotationQuaternion;
  8024. if (!space || space === BABYLON.Space.LOCAL) {
  8025. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8026. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8027. }
  8028. else {
  8029. if (this.parent) {
  8030. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8031. invertParentWorldMatrix.invert();
  8032. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8033. }
  8034. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8035. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8036. }
  8037. };
  8038. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8039. var displacementVector = axis.scale(distance);
  8040. if (!space || space === BABYLON.Space.LOCAL) {
  8041. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8042. this.setPositionWithLocalVector(tempV3);
  8043. }
  8044. else {
  8045. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8046. }
  8047. };
  8048. AbstractMesh.prototype.getAbsolutePosition = function () {
  8049. this.computeWorldMatrix();
  8050. return this._absolutePosition;
  8051. };
  8052. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8053. if (!absolutePosition) {
  8054. return;
  8055. }
  8056. var absolutePositionX;
  8057. var absolutePositionY;
  8058. var absolutePositionZ;
  8059. if (absolutePosition.x === undefined) {
  8060. if (arguments.length < 3) {
  8061. return;
  8062. }
  8063. absolutePositionX = arguments[0];
  8064. absolutePositionY = arguments[1];
  8065. absolutePositionZ = arguments[2];
  8066. }
  8067. else {
  8068. absolutePositionX = absolutePosition.x;
  8069. absolutePositionY = absolutePosition.y;
  8070. absolutePositionZ = absolutePosition.z;
  8071. }
  8072. if (this.parent) {
  8073. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8074. invertParentWorldMatrix.invert();
  8075. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8076. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8077. }
  8078. else {
  8079. this.position.x = absolutePositionX;
  8080. this.position.y = absolutePositionY;
  8081. this.position.z = absolutePositionZ;
  8082. }
  8083. };
  8084. // ================================== Point of View Movement =================================
  8085. /**
  8086. * Perform relative position change from the point of view of behind the front of the mesh.
  8087. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8088. * Supports definition of mesh facing forward or backward.
  8089. * @param {number} amountRight
  8090. * @param {number} amountUp
  8091. * @param {number} amountForward
  8092. */
  8093. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8094. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8095. };
  8096. /**
  8097. * Calculate relative position change from the point of view of behind the front of the mesh.
  8098. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8099. * Supports definition of mesh facing forward or backward.
  8100. * @param {number} amountRight
  8101. * @param {number} amountUp
  8102. * @param {number} amountForward
  8103. */
  8104. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8105. var rotMatrix = new BABYLON.Matrix();
  8106. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8107. rotQuaternion.toRotationMatrix(rotMatrix);
  8108. var translationDelta = BABYLON.Vector3.Zero();
  8109. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8111. return translationDelta;
  8112. };
  8113. // ================================== Point of View Rotation =================================
  8114. /**
  8115. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8116. * Supports definition of mesh facing forward or backward.
  8117. * @param {number} flipBack
  8118. * @param {number} twirlClockwise
  8119. * @param {number} tiltRight
  8120. */
  8121. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8122. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8123. };
  8124. /**
  8125. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8126. * Supports definition of mesh facing forward or backward.
  8127. * @param {number} flipBack
  8128. * @param {number} twirlClockwise
  8129. * @param {number} tiltRight
  8130. */
  8131. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8132. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8133. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8134. };
  8135. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8136. this._pivotMatrix = matrix;
  8137. this._cache.pivotMatrixUpdated = true;
  8138. };
  8139. AbstractMesh.prototype.getPivotMatrix = function () {
  8140. return this._pivotMatrix;
  8141. };
  8142. AbstractMesh.prototype._isSynchronized = function () {
  8143. if (this._isDirty) {
  8144. return false;
  8145. }
  8146. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8147. return false;
  8148. if (this._cache.pivotMatrixUpdated) {
  8149. return false;
  8150. }
  8151. if (this.infiniteDistance) {
  8152. return false;
  8153. }
  8154. if (!this._cache.position.equals(this.position))
  8155. return false;
  8156. if (this.rotationQuaternion) {
  8157. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8158. return false;
  8159. }
  8160. else {
  8161. if (!this._cache.rotation.equals(this.rotation))
  8162. return false;
  8163. }
  8164. if (!this._cache.scaling.equals(this.scaling))
  8165. return false;
  8166. return true;
  8167. };
  8168. AbstractMesh.prototype._initCache = function () {
  8169. _super.prototype._initCache.call(this);
  8170. this._cache.localMatrixUpdated = false;
  8171. this._cache.position = BABYLON.Vector3.Zero();
  8172. this._cache.scaling = BABYLON.Vector3.Zero();
  8173. this._cache.rotation = BABYLON.Vector3.Zero();
  8174. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8175. };
  8176. AbstractMesh.prototype.markAsDirty = function (property) {
  8177. if (property === "rotation") {
  8178. this.rotationQuaternion = null;
  8179. }
  8180. this._currentRenderId = Number.MAX_VALUE;
  8181. this._isDirty = true;
  8182. };
  8183. AbstractMesh.prototype._updateBoundingInfo = function () {
  8184. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8185. this._boundingInfo._update(this.worldMatrixFromCache);
  8186. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8187. };
  8188. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8189. if (!this.subMeshes) {
  8190. return;
  8191. }
  8192. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8193. var subMesh = this.subMeshes[subIndex];
  8194. subMesh.updateBoundingInfo(matrix);
  8195. }
  8196. };
  8197. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8198. if (this._isWorldMatrixFrozen) {
  8199. return this._worldMatrix;
  8200. }
  8201. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8202. return this._worldMatrix;
  8203. }
  8204. this._cache.position.copyFrom(this.position);
  8205. this._cache.scaling.copyFrom(this.scaling);
  8206. this._cache.pivotMatrixUpdated = false;
  8207. this._currentRenderId = this.getScene().getRenderId();
  8208. this._isDirty = false;
  8209. // Scaling
  8210. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  8211. // Rotation
  8212. if (this.rotationQuaternion) {
  8213. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8214. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8215. }
  8216. else {
  8217. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8218. this._cache.rotation.copyFrom(this.rotation);
  8219. }
  8220. // Translation
  8221. if (this.infiniteDistance && !this.parent) {
  8222. var camera = this.getScene().activeCamera;
  8223. if (camera) {
  8224. var cameraWorldMatrix = camera.getWorldMatrix();
  8225. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8226. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8227. }
  8228. }
  8229. else {
  8230. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8231. }
  8232. // Composing transformations
  8233. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8234. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8235. // Billboarding
  8236. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8237. var localPosition = this.position.clone();
  8238. var zero = this.getScene().activeCamera.globalPosition.clone();
  8239. if (this.parent && this.parent.position) {
  8240. localPosition.addInPlace(this.parent.position);
  8241. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8242. }
  8243. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8244. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8245. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8246. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8247. zero.y = localPosition.y + 0.001;
  8248. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8249. zero.z = localPosition.z + 0.001;
  8250. }
  8251. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8252. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8253. this._localBillboard.invert();
  8254. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8255. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8256. }
  8257. // Local world
  8258. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8259. // Parent
  8260. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8261. this._markSyncedWithParent();
  8262. if (this._meshToBoneReferal) {
  8263. if (!this._localMeshReferalTransform) {
  8264. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8265. }
  8266. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8267. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8268. }
  8269. else {
  8270. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8271. }
  8272. }
  8273. else {
  8274. this._worldMatrix.copyFrom(this._localWorld);
  8275. }
  8276. // Bounding info
  8277. this._updateBoundingInfo();
  8278. // Absolute position
  8279. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8280. // Callbacks
  8281. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8282. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8283. }
  8284. return this._worldMatrix;
  8285. };
  8286. /**
  8287. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8288. * @param func: callback function to add
  8289. */
  8290. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8291. this._onAfterWorldMatrixUpdate.push(func);
  8292. };
  8293. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8294. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8295. if (index > -1) {
  8296. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8297. }
  8298. };
  8299. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8300. this.computeWorldMatrix();
  8301. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8302. };
  8303. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8304. this.computeWorldMatrix();
  8305. var invLocalWorldMatrix = this._localWorld.clone();
  8306. invLocalWorldMatrix.invert();
  8307. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8308. };
  8309. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8310. this.computeWorldMatrix(true);
  8311. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8312. };
  8313. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8314. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8315. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8316. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8317. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8318. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8319. /// <returns>Mesh oriented towards targetMesh</returns>
  8320. yawCor = yawCor || 0; // default to zero if undefined
  8321. pitchCor = pitchCor || 0;
  8322. rollCor = rollCor || 0;
  8323. var dv = targetPoint.subtract(this.position);
  8324. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8325. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8326. var pitch = Math.atan2(dv.y, len);
  8327. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8328. };
  8329. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8330. this._meshToBoneReferal = affectedMesh;
  8331. this.parent = bone;
  8332. if (bone.getWorldMatrix().determinant() < 0) {
  8333. this.scalingDeterminant *= -1;
  8334. }
  8335. };
  8336. AbstractMesh.prototype.detachFromBone = function () {
  8337. if (this.parent.getWorldMatrix().determinant() < 0) {
  8338. this.scalingDeterminant *= -1;
  8339. }
  8340. this._meshToBoneReferal = null;
  8341. this.parent = null;
  8342. };
  8343. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8344. return this._boundingInfo.isInFrustum(frustumPlanes);
  8345. };
  8346. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8347. if (!camera) {
  8348. camera = this.getScene().activeCamera;
  8349. }
  8350. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8351. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8352. return false;
  8353. }
  8354. return true;
  8355. };
  8356. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8357. if (!this._boundingInfo || !mesh._boundingInfo) {
  8358. return false;
  8359. }
  8360. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8361. };
  8362. AbstractMesh.prototype.intersectsPoint = function (point) {
  8363. if (!this._boundingInfo) {
  8364. return false;
  8365. }
  8366. return this._boundingInfo.intersectsPoint(point);
  8367. };
  8368. // Physics
  8369. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8370. var physicsEngine = this.getScene().getPhysicsEngine();
  8371. if (!physicsEngine) {
  8372. return null;
  8373. }
  8374. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8375. if (impostor.impostor) {
  8376. // Old API
  8377. options = impostor;
  8378. impostor = impostor.impostor;
  8379. }
  8380. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8381. physicsEngine._unregisterMesh(this);
  8382. return null;
  8383. }
  8384. if (!options) {
  8385. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8386. }
  8387. else {
  8388. if (!options.mass && options.mass !== 0)
  8389. options.mass = 0;
  8390. if (!options.friction && options.friction !== 0)
  8391. options.friction = 0.2;
  8392. if (!options.restitution && options.restitution !== 0)
  8393. options.restitution = 0.2;
  8394. }
  8395. this._physicImpostor = impostor;
  8396. this._physicsMass = options.mass;
  8397. this._physicsFriction = options.friction;
  8398. this._physicRestitution = options.restitution;
  8399. return physicsEngine._registerMesh(this, impostor, options);
  8400. };
  8401. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8402. if (!this._physicImpostor) {
  8403. return BABYLON.PhysicsEngine.NoImpostor;
  8404. }
  8405. return this._physicImpostor;
  8406. };
  8407. AbstractMesh.prototype.getPhysicsMass = function () {
  8408. if (!this._physicsMass) {
  8409. return 0;
  8410. }
  8411. return this._physicsMass;
  8412. };
  8413. AbstractMesh.prototype.getPhysicsFriction = function () {
  8414. if (!this._physicsFriction) {
  8415. return 0;
  8416. }
  8417. return this._physicsFriction;
  8418. };
  8419. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8420. if (!this._physicRestitution) {
  8421. return 0;
  8422. }
  8423. return this._physicRestitution;
  8424. };
  8425. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8426. if (!camera) {
  8427. camera = this.getScene().activeCamera;
  8428. }
  8429. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8430. };
  8431. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8432. if (!camera) {
  8433. camera = this.getScene().activeCamera;
  8434. }
  8435. return this.absolutePosition.subtract(camera.position).length();
  8436. };
  8437. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8438. if (!this._physicImpostor) {
  8439. return;
  8440. }
  8441. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8442. };
  8443. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8444. if (!this._physicImpostor) {
  8445. return;
  8446. }
  8447. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8448. };
  8449. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8450. if (!this._physicImpostor) {
  8451. return;
  8452. }
  8453. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8454. };
  8455. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8456. // Collisions
  8457. get: function () {
  8458. return this._checkCollisions;
  8459. },
  8460. set: function (collisionEnabled) {
  8461. this._checkCollisions = collisionEnabled;
  8462. if (this.getScene().workerCollisions) {
  8463. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8464. }
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8470. var globalPosition = this.getAbsolutePosition();
  8471. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8472. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8473. this._collider.radius = this.ellipsoid;
  8474. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8475. };
  8476. // Submeshes octree
  8477. /**
  8478. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8479. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8480. */
  8481. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8482. if (maxCapacity === void 0) { maxCapacity = 64; }
  8483. if (maxDepth === void 0) { maxDepth = 2; }
  8484. if (!this._submeshesOctree) {
  8485. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8486. }
  8487. this.computeWorldMatrix(true);
  8488. // Update octree
  8489. var bbox = this.getBoundingInfo().boundingBox;
  8490. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8491. return this._submeshesOctree;
  8492. };
  8493. // Collisions
  8494. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8495. this._generatePointsArray();
  8496. // Transformation
  8497. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8498. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8499. subMesh._lastColliderWorldVertices = [];
  8500. subMesh._trianglePlanes = [];
  8501. var start = subMesh.verticesStart;
  8502. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8503. for (var i = start; i < end; i++) {
  8504. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8505. }
  8506. }
  8507. // Collide
  8508. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8509. if (collider.collisionFound) {
  8510. collider.collidedMesh = this;
  8511. }
  8512. };
  8513. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8514. var subMeshes;
  8515. var len;
  8516. // Octrees
  8517. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8518. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8519. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8520. len = intersections.length;
  8521. subMeshes = intersections.data;
  8522. }
  8523. else {
  8524. subMeshes = this.subMeshes;
  8525. len = subMeshes.length;
  8526. }
  8527. for (var index = 0; index < len; index++) {
  8528. var subMesh = subMeshes[index];
  8529. // Bounding test
  8530. if (len > 1 && !subMesh._checkCollision(collider))
  8531. continue;
  8532. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8533. }
  8534. };
  8535. AbstractMesh.prototype._checkCollision = function (collider) {
  8536. // Bounding box test
  8537. if (!this._boundingInfo._checkCollision(collider))
  8538. return;
  8539. // Transformation matrix
  8540. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8541. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8542. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8543. };
  8544. // Picking
  8545. AbstractMesh.prototype._generatePointsArray = function () {
  8546. return false;
  8547. };
  8548. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8549. var pickingInfo = new BABYLON.PickingInfo();
  8550. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8551. return pickingInfo;
  8552. }
  8553. if (!this._generatePointsArray()) {
  8554. return pickingInfo;
  8555. }
  8556. var intersectInfo = null;
  8557. // Octrees
  8558. var subMeshes;
  8559. var len;
  8560. if (this._submeshesOctree && this.useOctreeForPicking) {
  8561. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8562. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8563. len = intersections.length;
  8564. subMeshes = intersections.data;
  8565. }
  8566. else {
  8567. subMeshes = this.subMeshes;
  8568. len = subMeshes.length;
  8569. }
  8570. for (var index = 0; index < len; index++) {
  8571. var subMesh = subMeshes[index];
  8572. // Bounding test
  8573. if (len > 1 && !subMesh.canIntersects(ray))
  8574. continue;
  8575. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8576. if (currentIntersectInfo) {
  8577. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8578. intersectInfo = currentIntersectInfo;
  8579. intersectInfo.subMeshId = index;
  8580. if (fastCheck) {
  8581. break;
  8582. }
  8583. }
  8584. }
  8585. }
  8586. if (intersectInfo) {
  8587. // Get picked point
  8588. var world = this.getWorldMatrix();
  8589. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8590. var direction = ray.direction.clone();
  8591. direction = direction.scale(intersectInfo.distance);
  8592. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8593. var pickedPoint = worldOrigin.add(worldDirection);
  8594. // Return result
  8595. pickingInfo.hit = true;
  8596. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8597. pickingInfo.pickedPoint = pickedPoint;
  8598. pickingInfo.pickedMesh = this;
  8599. pickingInfo.bu = intersectInfo.bu;
  8600. pickingInfo.bv = intersectInfo.bv;
  8601. pickingInfo.faceId = intersectInfo.faceId;
  8602. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8603. return pickingInfo;
  8604. }
  8605. return pickingInfo;
  8606. };
  8607. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8608. return null;
  8609. };
  8610. AbstractMesh.prototype.releaseSubMeshes = function () {
  8611. if (this.subMeshes) {
  8612. while (this.subMeshes.length) {
  8613. this.subMeshes[0].dispose();
  8614. }
  8615. }
  8616. else {
  8617. this.subMeshes = new Array();
  8618. }
  8619. };
  8620. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8621. var index;
  8622. // Physics
  8623. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8624. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8625. }
  8626. // Intersections in progress
  8627. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8628. var other = this._intersectionsInProgress[index];
  8629. var pos = other._intersectionsInProgress.indexOf(this);
  8630. other._intersectionsInProgress.splice(pos, 1);
  8631. }
  8632. this._intersectionsInProgress = [];
  8633. // Edges
  8634. if (this._edgesRenderer) {
  8635. this._edgesRenderer.dispose();
  8636. this._edgesRenderer = null;
  8637. }
  8638. // SubMeshes
  8639. this.releaseSubMeshes();
  8640. // Remove from scene
  8641. this.getScene().removeMesh(this);
  8642. if (!doNotRecurse) {
  8643. // Particles
  8644. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8645. if (this.getScene().particleSystems[index].emitter === this) {
  8646. this.getScene().particleSystems[index].dispose();
  8647. index--;
  8648. }
  8649. }
  8650. // Children
  8651. var objects = this.getScene().meshes.slice(0);
  8652. for (index = 0; index < objects.length; index++) {
  8653. if (objects[index].parent === this) {
  8654. objects[index].dispose();
  8655. }
  8656. }
  8657. }
  8658. else {
  8659. for (index = 0; index < this.getScene().meshes.length; index++) {
  8660. var obj = this.getScene().meshes[index];
  8661. if (obj.parent === this) {
  8662. obj.parent = null;
  8663. obj.computeWorldMatrix(true);
  8664. }
  8665. }
  8666. }
  8667. this._onAfterWorldMatrixUpdate = [];
  8668. this._isDisposed = true;
  8669. // Callback
  8670. if (this.onDispose) {
  8671. this.onDispose();
  8672. }
  8673. };
  8674. // Statics
  8675. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8676. AbstractMesh._BILLBOARDMODE_X = 1;
  8677. AbstractMesh._BILLBOARDMODE_Y = 2;
  8678. AbstractMesh._BILLBOARDMODE_Z = 4;
  8679. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8680. return AbstractMesh;
  8681. })(BABYLON.Node);
  8682. BABYLON.AbstractMesh = AbstractMesh;
  8683. })(BABYLON || (BABYLON = {}));
  8684. var BABYLON;
  8685. (function (BABYLON) {
  8686. var Light = (function (_super) {
  8687. __extends(Light, _super);
  8688. function Light(name, scene) {
  8689. _super.call(this, name, scene);
  8690. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8691. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8692. this.intensity = 1.0;
  8693. this.range = Number.MAX_VALUE;
  8694. this.includeOnlyWithLayerMask = 0;
  8695. this.includedOnlyMeshes = new Array();
  8696. this.excludedMeshes = new Array();
  8697. this.excludeWithLayerMask = 0;
  8698. this._excludedMeshesIds = new Array();
  8699. this._includedOnlyMeshesIds = new Array();
  8700. scene.addLight(this);
  8701. }
  8702. Light.prototype.getShadowGenerator = function () {
  8703. return this._shadowGenerator;
  8704. };
  8705. Light.prototype.getAbsolutePosition = function () {
  8706. return BABYLON.Vector3.Zero();
  8707. };
  8708. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8709. };
  8710. Light.prototype._getWorldMatrix = function () {
  8711. return BABYLON.Matrix.Identity();
  8712. };
  8713. Light.prototype.canAffectMesh = function (mesh) {
  8714. if (!mesh) {
  8715. return true;
  8716. }
  8717. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8718. return false;
  8719. }
  8720. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8721. return false;
  8722. }
  8723. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8724. return false;
  8725. }
  8726. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8727. return false;
  8728. }
  8729. return true;
  8730. };
  8731. Light.prototype.getWorldMatrix = function () {
  8732. this._currentRenderId = this.getScene().getRenderId();
  8733. var worldMatrix = this._getWorldMatrix();
  8734. if (this.parent && this.parent.getWorldMatrix) {
  8735. if (!this._parentedWorldMatrix) {
  8736. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8737. }
  8738. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8739. this._markSyncedWithParent();
  8740. return this._parentedWorldMatrix;
  8741. }
  8742. return worldMatrix;
  8743. };
  8744. Light.prototype.dispose = function () {
  8745. if (this._shadowGenerator) {
  8746. this._shadowGenerator.dispose();
  8747. this._shadowGenerator = null;
  8748. }
  8749. // Remove from scene
  8750. this.getScene().removeLight(this);
  8751. };
  8752. return Light;
  8753. })(BABYLON.Node);
  8754. BABYLON.Light = Light;
  8755. })(BABYLON || (BABYLON = {}));
  8756. var BABYLON;
  8757. (function (BABYLON) {
  8758. var PointLight = (function (_super) {
  8759. __extends(PointLight, _super);
  8760. function PointLight(name, position, scene) {
  8761. _super.call(this, name, scene);
  8762. this.position = position;
  8763. }
  8764. PointLight.prototype.getAbsolutePosition = function () {
  8765. return this._transformedPosition ? this._transformedPosition : this.position;
  8766. };
  8767. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8768. if (this.parent && this.parent.getWorldMatrix) {
  8769. if (!this._transformedPosition) {
  8770. this._transformedPosition = BABYLON.Vector3.Zero();
  8771. }
  8772. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8773. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8774. return;
  8775. }
  8776. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8777. };
  8778. PointLight.prototype.getShadowGenerator = function () {
  8779. return null;
  8780. };
  8781. PointLight.prototype._getWorldMatrix = function () {
  8782. if (!this._worldMatrix) {
  8783. this._worldMatrix = BABYLON.Matrix.Identity();
  8784. }
  8785. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8786. return this._worldMatrix;
  8787. };
  8788. return PointLight;
  8789. })(BABYLON.Light);
  8790. BABYLON.PointLight = PointLight;
  8791. })(BABYLON || (BABYLON = {}));
  8792. var BABYLON;
  8793. (function (BABYLON) {
  8794. var SpotLight = (function (_super) {
  8795. __extends(SpotLight, _super);
  8796. function SpotLight(name, position, direction, angle, exponent, scene) {
  8797. _super.call(this, name, scene);
  8798. this.position = position;
  8799. this.direction = direction;
  8800. this.angle = angle;
  8801. this.exponent = exponent;
  8802. }
  8803. SpotLight.prototype.getAbsolutePosition = function () {
  8804. return this.transformedPosition ? this.transformedPosition : this.position;
  8805. };
  8806. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8807. var activeCamera = this.getScene().activeCamera;
  8808. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8809. };
  8810. SpotLight.prototype.supportsVSM = function () {
  8811. return true;
  8812. };
  8813. SpotLight.prototype.needRefreshPerFrame = function () {
  8814. return false;
  8815. };
  8816. SpotLight.prototype.setDirectionToTarget = function (target) {
  8817. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8818. return this.direction;
  8819. };
  8820. SpotLight.prototype.computeTransformedPosition = function () {
  8821. if (this.parent && this.parent.getWorldMatrix) {
  8822. if (!this.transformedPosition) {
  8823. this.transformedPosition = BABYLON.Vector3.Zero();
  8824. }
  8825. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8826. return true;
  8827. }
  8828. return false;
  8829. };
  8830. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8831. var normalizeDirection;
  8832. if (this.parent && this.parent.getWorldMatrix) {
  8833. if (!this._transformedDirection) {
  8834. this._transformedDirection = BABYLON.Vector3.Zero();
  8835. }
  8836. this.computeTransformedPosition();
  8837. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8838. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8839. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8840. }
  8841. else {
  8842. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8843. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8844. }
  8845. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8846. };
  8847. SpotLight.prototype._getWorldMatrix = function () {
  8848. if (!this._worldMatrix) {
  8849. this._worldMatrix = BABYLON.Matrix.Identity();
  8850. }
  8851. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8852. return this._worldMatrix;
  8853. };
  8854. return SpotLight;
  8855. })(BABYLON.Light);
  8856. BABYLON.SpotLight = SpotLight;
  8857. })(BABYLON || (BABYLON = {}));
  8858. var BABYLON;
  8859. (function (BABYLON) {
  8860. var HemisphericLight = (function (_super) {
  8861. __extends(HemisphericLight, _super);
  8862. function HemisphericLight(name, direction, scene) {
  8863. _super.call(this, name, scene);
  8864. this.direction = direction;
  8865. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8866. }
  8867. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8868. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8869. return this.direction;
  8870. };
  8871. HemisphericLight.prototype.getShadowGenerator = function () {
  8872. return null;
  8873. };
  8874. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8875. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8876. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8877. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8878. };
  8879. HemisphericLight.prototype._getWorldMatrix = function () {
  8880. if (!this._worldMatrix) {
  8881. this._worldMatrix = BABYLON.Matrix.Identity();
  8882. }
  8883. return this._worldMatrix;
  8884. };
  8885. return HemisphericLight;
  8886. })(BABYLON.Light);
  8887. BABYLON.HemisphericLight = HemisphericLight;
  8888. })(BABYLON || (BABYLON = {}));
  8889. var BABYLON;
  8890. (function (BABYLON) {
  8891. var DirectionalLight = (function (_super) {
  8892. __extends(DirectionalLight, _super);
  8893. function DirectionalLight(name, direction, scene) {
  8894. _super.call(this, name, scene);
  8895. this.direction = direction;
  8896. this.shadowOrthoScale = 0.5;
  8897. this.position = direction.scale(-1);
  8898. }
  8899. DirectionalLight.prototype.getAbsolutePosition = function () {
  8900. return this.transformedPosition ? this.transformedPosition : this.position;
  8901. };
  8902. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8903. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8904. return this.direction;
  8905. };
  8906. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8907. var orthoLeft = Number.MAX_VALUE;
  8908. var orthoRight = Number.MIN_VALUE;
  8909. var orthoTop = Number.MIN_VALUE;
  8910. var orthoBottom = Number.MAX_VALUE;
  8911. var tempVector3 = BABYLON.Vector3.Zero();
  8912. var activeCamera = this.getScene().activeCamera;
  8913. // Check extends
  8914. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8915. var mesh = renderList[meshIndex];
  8916. if (!mesh) {
  8917. continue;
  8918. }
  8919. var boundingInfo = mesh.getBoundingInfo();
  8920. if (!boundingInfo) {
  8921. continue;
  8922. }
  8923. var boundingBox = boundingInfo.boundingBox;
  8924. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8925. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8926. if (tempVector3.x < orthoLeft)
  8927. orthoLeft = tempVector3.x;
  8928. if (tempVector3.y < orthoBottom)
  8929. orthoBottom = tempVector3.y;
  8930. if (tempVector3.x > orthoRight)
  8931. orthoRight = tempVector3.x;
  8932. if (tempVector3.y > orthoTop)
  8933. orthoTop = tempVector3.y;
  8934. }
  8935. }
  8936. var xOffset = orthoRight - orthoLeft;
  8937. var yOffset = orthoTop - orthoBottom;
  8938. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8939. };
  8940. DirectionalLight.prototype.supportsVSM = function () {
  8941. return true;
  8942. };
  8943. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8944. return true;
  8945. };
  8946. DirectionalLight.prototype.computeTransformedPosition = function () {
  8947. if (this.parent && this.parent.getWorldMatrix) {
  8948. if (!this.transformedPosition) {
  8949. this.transformedPosition = BABYLON.Vector3.Zero();
  8950. }
  8951. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8952. return true;
  8953. }
  8954. return false;
  8955. };
  8956. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8957. if (this.parent && this.parent.getWorldMatrix) {
  8958. if (!this._transformedDirection) {
  8959. this._transformedDirection = BABYLON.Vector3.Zero();
  8960. }
  8961. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8962. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8963. return;
  8964. }
  8965. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8966. };
  8967. DirectionalLight.prototype._getWorldMatrix = function () {
  8968. if (!this._worldMatrix) {
  8969. this._worldMatrix = BABYLON.Matrix.Identity();
  8970. }
  8971. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8972. return this._worldMatrix;
  8973. };
  8974. return DirectionalLight;
  8975. })(BABYLON.Light);
  8976. BABYLON.DirectionalLight = DirectionalLight;
  8977. })(BABYLON || (BABYLON = {}));
  8978. var BABYLON;
  8979. (function (BABYLON) {
  8980. var ShadowGenerator = (function () {
  8981. function ShadowGenerator(mapSize, light) {
  8982. var _this = this;
  8983. // Members
  8984. this._filter = ShadowGenerator.FILTER_NONE;
  8985. this.blurScale = 2;
  8986. this._blurBoxOffset = 0;
  8987. this._bias = 0.00005;
  8988. this._lightDirection = BABYLON.Vector3.Zero();
  8989. this._darkness = 0;
  8990. this._transparencyShadow = false;
  8991. this._viewMatrix = BABYLON.Matrix.Zero();
  8992. this._projectionMatrix = BABYLON.Matrix.Zero();
  8993. this._transformMatrix = BABYLON.Matrix.Zero();
  8994. this._worldViewProjection = BABYLON.Matrix.Zero();
  8995. this._light = light;
  8996. this._scene = light.getScene();
  8997. this._mapSize = mapSize;
  8998. light._shadowGenerator = this;
  8999. // Render target
  9000. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  9001. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9002. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9003. this._shadowMap.anisotropicFilteringLevel = 1;
  9004. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9005. this._shadowMap.renderParticles = false;
  9006. this._shadowMap.onAfterUnbind = function () {
  9007. if (!_this.useBlurVarianceShadowMap) {
  9008. return;
  9009. }
  9010. if (!_this._shadowMap2) {
  9011. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9012. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9013. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9014. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9015. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9016. _this._downSamplePostprocess.onApply = function (effect) {
  9017. effect.setTexture("textureSampler", _this._shadowMap);
  9018. };
  9019. _this.blurBoxOffset = 1;
  9020. }
  9021. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9022. };
  9023. // Custom render function
  9024. var renderSubMesh = function (subMesh) {
  9025. var mesh = subMesh.getRenderingMesh();
  9026. var scene = _this._scene;
  9027. var engine = scene.getEngine();
  9028. // Culling
  9029. engine.setState(subMesh.getMaterial().backFaceCulling);
  9030. // Managing instances
  9031. var batch = mesh._getInstancesRenderList(subMesh._id);
  9032. if (batch.mustReturn) {
  9033. return;
  9034. }
  9035. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  9036. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9037. engine.enableEffect(_this._effect);
  9038. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9039. var material = subMesh.getMaterial();
  9040. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9041. // Alpha test
  9042. if (material && material.needAlphaTesting()) {
  9043. var alphaTexture = material.getAlphaTestTexture();
  9044. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9045. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9046. }
  9047. // Bones
  9048. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9049. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  9050. }
  9051. // Draw
  9052. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9053. }
  9054. else {
  9055. // Need to reset refresh rate of the shadowMap
  9056. _this._shadowMap.resetRefreshCounter();
  9057. }
  9058. };
  9059. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9060. var index;
  9061. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9062. renderSubMesh(opaqueSubMeshes.data[index]);
  9063. }
  9064. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9065. renderSubMesh(alphaTestSubMeshes.data[index]);
  9066. }
  9067. if (_this._transparencyShadow) {
  9068. for (index = 0; index < transparentSubMeshes.length; index++) {
  9069. renderSubMesh(transparentSubMeshes.data[index]);
  9070. }
  9071. }
  9072. };
  9073. this._shadowMap.onClear = function (engine) {
  9074. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9075. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9076. }
  9077. else {
  9078. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9079. }
  9080. };
  9081. }
  9082. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9083. // Static
  9084. get: function () {
  9085. return ShadowGenerator._FILTER_NONE;
  9086. },
  9087. enumerable: true,
  9088. configurable: true
  9089. });
  9090. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9091. get: function () {
  9092. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9093. },
  9094. enumerable: true,
  9095. configurable: true
  9096. });
  9097. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9098. get: function () {
  9099. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9100. },
  9101. enumerable: true,
  9102. configurable: true
  9103. });
  9104. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9105. get: function () {
  9106. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9107. },
  9108. enumerable: true,
  9109. configurable: true
  9110. });
  9111. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9112. get: function () {
  9113. return this._bias;
  9114. },
  9115. set: function (bias) {
  9116. this._bias = bias;
  9117. },
  9118. enumerable: true,
  9119. configurable: true
  9120. });
  9121. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9122. get: function () {
  9123. return this._blurBoxOffset;
  9124. },
  9125. set: function (value) {
  9126. var _this = this;
  9127. if (this._blurBoxOffset === value) {
  9128. return;
  9129. }
  9130. this._blurBoxOffset = value;
  9131. if (this._boxBlurPostprocess) {
  9132. this._boxBlurPostprocess.dispose();
  9133. }
  9134. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9135. this._boxBlurPostprocess.onApply = function (effect) {
  9136. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9137. };
  9138. },
  9139. enumerable: true,
  9140. configurable: true
  9141. });
  9142. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9143. get: function () {
  9144. return this._filter;
  9145. },
  9146. set: function (value) {
  9147. if (this._filter === value) {
  9148. return;
  9149. }
  9150. this._filter = value;
  9151. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9152. this._shadowMap.anisotropicFilteringLevel = 16;
  9153. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9154. }
  9155. else {
  9156. this._shadowMap.anisotropicFilteringLevel = 1;
  9157. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9158. }
  9159. },
  9160. enumerable: true,
  9161. configurable: true
  9162. });
  9163. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9164. get: function () {
  9165. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9166. },
  9167. set: function (value) {
  9168. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9169. },
  9170. enumerable: true,
  9171. configurable: true
  9172. });
  9173. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9174. get: function () {
  9175. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9176. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9177. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9178. },
  9179. set: function (value) {
  9180. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9181. },
  9182. enumerable: true,
  9183. configurable: true
  9184. });
  9185. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9186. get: function () {
  9187. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9188. },
  9189. set: function (value) {
  9190. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9191. },
  9192. enumerable: true,
  9193. configurable: true
  9194. });
  9195. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9196. var defines = [];
  9197. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9198. defines.push("#define VSM");
  9199. }
  9200. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9201. var mesh = subMesh.getMesh();
  9202. var material = subMesh.getMaterial();
  9203. // Alpha test
  9204. if (material && material.needAlphaTesting()) {
  9205. defines.push("#define ALPHATEST");
  9206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9207. attribs.push(BABYLON.VertexBuffer.UVKind);
  9208. defines.push("#define UV1");
  9209. }
  9210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9212. defines.push("#define UV2");
  9213. }
  9214. }
  9215. // Bones
  9216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9219. defines.push("#define BONES");
  9220. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9221. }
  9222. // Instances
  9223. if (useInstances) {
  9224. defines.push("#define INSTANCES");
  9225. attribs.push("world0");
  9226. attribs.push("world1");
  9227. attribs.push("world2");
  9228. attribs.push("world3");
  9229. }
  9230. // Get correct effect
  9231. var join = defines.join("\n");
  9232. if (this._cachedDefines !== join) {
  9233. this._cachedDefines = join;
  9234. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9235. }
  9236. return this._effect.isReady();
  9237. };
  9238. ShadowGenerator.prototype.getShadowMap = function () {
  9239. return this._shadowMap;
  9240. };
  9241. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9242. if (this._shadowMap2) {
  9243. return this._shadowMap2;
  9244. }
  9245. return this._shadowMap;
  9246. };
  9247. ShadowGenerator.prototype.getLight = function () {
  9248. return this._light;
  9249. };
  9250. // Methods
  9251. ShadowGenerator.prototype.getTransformMatrix = function () {
  9252. var scene = this._scene;
  9253. if (this._currentRenderID === scene.getRenderId()) {
  9254. return this._transformMatrix;
  9255. }
  9256. this._currentRenderID = scene.getRenderId();
  9257. var lightPosition = this._light.position;
  9258. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9259. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9260. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9261. }
  9262. if (this._light.computeTransformedPosition()) {
  9263. lightPosition = this._light.transformedPosition;
  9264. }
  9265. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9266. this._cachedPosition = lightPosition.clone();
  9267. this._cachedDirection = this._lightDirection.clone();
  9268. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9269. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9270. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9271. }
  9272. return this._transformMatrix;
  9273. };
  9274. ShadowGenerator.prototype.getDarkness = function () {
  9275. return this._darkness;
  9276. };
  9277. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9278. if (darkness >= 1.0)
  9279. this._darkness = 1.0;
  9280. else if (darkness <= 0.0)
  9281. this._darkness = 0.0;
  9282. else
  9283. this._darkness = darkness;
  9284. };
  9285. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9286. this._transparencyShadow = hasShadow;
  9287. };
  9288. ShadowGenerator.prototype._packHalf = function (depth) {
  9289. var scale = depth * 255.0;
  9290. var fract = scale - Math.floor(scale);
  9291. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9292. };
  9293. ShadowGenerator.prototype.dispose = function () {
  9294. this._shadowMap.dispose();
  9295. if (this._shadowMap2) {
  9296. this._shadowMap2.dispose();
  9297. }
  9298. if (this._downSamplePostprocess) {
  9299. this._downSamplePostprocess.dispose();
  9300. }
  9301. if (this._boxBlurPostprocess) {
  9302. this._boxBlurPostprocess.dispose();
  9303. }
  9304. };
  9305. ShadowGenerator._FILTER_NONE = 0;
  9306. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9307. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9308. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9309. return ShadowGenerator;
  9310. })();
  9311. BABYLON.ShadowGenerator = ShadowGenerator;
  9312. })(BABYLON || (BABYLON = {}));
  9313. var BABYLON;
  9314. (function (BABYLON) {
  9315. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9316. if (boxMin.x > sphereCenter.x + sphereRadius)
  9317. return false;
  9318. if (sphereCenter.x - sphereRadius > boxMax.x)
  9319. return false;
  9320. if (boxMin.y > sphereCenter.y + sphereRadius)
  9321. return false;
  9322. if (sphereCenter.y - sphereRadius > boxMax.y)
  9323. return false;
  9324. if (boxMin.z > sphereCenter.z + sphereRadius)
  9325. return false;
  9326. if (sphereCenter.z - sphereRadius > boxMax.z)
  9327. return false;
  9328. return true;
  9329. };
  9330. var getLowestRoot = function (a, b, c, maxR) {
  9331. var determinant = b * b - 4.0 * a * c;
  9332. var result = { root: 0, found: false };
  9333. if (determinant < 0)
  9334. return result;
  9335. var sqrtD = Math.sqrt(determinant);
  9336. var r1 = (-b - sqrtD) / (2.0 * a);
  9337. var r2 = (-b + sqrtD) / (2.0 * a);
  9338. if (r1 > r2) {
  9339. var temp = r2;
  9340. r2 = r1;
  9341. r1 = temp;
  9342. }
  9343. if (r1 > 0 && r1 < maxR) {
  9344. result.root = r1;
  9345. result.found = true;
  9346. return result;
  9347. }
  9348. if (r2 > 0 && r2 < maxR) {
  9349. result.root = r2;
  9350. result.found = true;
  9351. return result;
  9352. }
  9353. return result;
  9354. };
  9355. var Collider = (function () {
  9356. function Collider() {
  9357. this.radius = new BABYLON.Vector3(1, 1, 1);
  9358. this.retry = 0;
  9359. this.basePointWorld = BABYLON.Vector3.Zero();
  9360. this.velocityWorld = BABYLON.Vector3.Zero();
  9361. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9362. this._collisionPoint = BABYLON.Vector3.Zero();
  9363. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9364. this._tempVector = BABYLON.Vector3.Zero();
  9365. this._tempVector2 = BABYLON.Vector3.Zero();
  9366. this._tempVector3 = BABYLON.Vector3.Zero();
  9367. this._tempVector4 = BABYLON.Vector3.Zero();
  9368. this._edge = BABYLON.Vector3.Zero();
  9369. this._baseToVertex = BABYLON.Vector3.Zero();
  9370. this._destinationPoint = BABYLON.Vector3.Zero();
  9371. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9372. this._displacementVector = BABYLON.Vector3.Zero();
  9373. }
  9374. // Methods
  9375. Collider.prototype._initialize = function (source, dir, e) {
  9376. this.velocity = dir;
  9377. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9378. this.basePoint = source;
  9379. source.multiplyToRef(this.radius, this.basePointWorld);
  9380. dir.multiplyToRef(this.radius, this.velocityWorld);
  9381. this.velocityWorldLength = this.velocityWorld.length();
  9382. this.epsilon = e;
  9383. this.collisionFound = false;
  9384. };
  9385. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9386. pa.subtractToRef(point, this._tempVector);
  9387. pb.subtractToRef(point, this._tempVector2);
  9388. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9389. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9390. if (d < 0)
  9391. return false;
  9392. pc.subtractToRef(point, this._tempVector3);
  9393. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9394. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9395. if (d < 0)
  9396. return false;
  9397. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9398. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9399. return d >= 0;
  9400. };
  9401. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9402. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9403. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9404. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9405. return false;
  9406. }
  9407. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9408. return false;
  9409. return true;
  9410. };
  9411. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9412. var t0;
  9413. var embeddedInPlane = false;
  9414. //defensive programming, actually not needed.
  9415. if (!trianglePlaneArray) {
  9416. trianglePlaneArray = [];
  9417. }
  9418. if (!trianglePlaneArray[faceIndex]) {
  9419. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9420. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9421. }
  9422. var trianglePlane = trianglePlaneArray[faceIndex];
  9423. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9424. return;
  9425. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9426. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9427. if (normalDotVelocity == 0) {
  9428. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9429. return;
  9430. embeddedInPlane = true;
  9431. t0 = 0;
  9432. }
  9433. else {
  9434. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9435. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9436. if (t0 > t1) {
  9437. var temp = t1;
  9438. t1 = t0;
  9439. t0 = temp;
  9440. }
  9441. if (t0 > 1.0 || t1 < 0.0)
  9442. return;
  9443. if (t0 < 0)
  9444. t0 = 0;
  9445. if (t0 > 1.0)
  9446. t0 = 1.0;
  9447. }
  9448. this._collisionPoint.copyFromFloats(0, 0, 0);
  9449. var found = false;
  9450. var t = 1.0;
  9451. if (!embeddedInPlane) {
  9452. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9453. this.velocity.scaleToRef(t0, this._tempVector);
  9454. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9455. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9456. found = true;
  9457. t = t0;
  9458. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9459. }
  9460. }
  9461. if (!found) {
  9462. var velocitySquaredLength = this.velocity.lengthSquared();
  9463. var a = velocitySquaredLength;
  9464. this.basePoint.subtractToRef(p1, this._tempVector);
  9465. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9466. var c = this._tempVector.lengthSquared() - 1.0;
  9467. var lowestRoot = getLowestRoot(a, b, c, t);
  9468. if (lowestRoot.found) {
  9469. t = lowestRoot.root;
  9470. found = true;
  9471. this._collisionPoint.copyFrom(p1);
  9472. }
  9473. this.basePoint.subtractToRef(p2, this._tempVector);
  9474. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9475. c = this._tempVector.lengthSquared() - 1.0;
  9476. lowestRoot = getLowestRoot(a, b, c, t);
  9477. if (lowestRoot.found) {
  9478. t = lowestRoot.root;
  9479. found = true;
  9480. this._collisionPoint.copyFrom(p2);
  9481. }
  9482. this.basePoint.subtractToRef(p3, this._tempVector);
  9483. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9484. c = this._tempVector.lengthSquared() - 1.0;
  9485. lowestRoot = getLowestRoot(a, b, c, t);
  9486. if (lowestRoot.found) {
  9487. t = lowestRoot.root;
  9488. found = true;
  9489. this._collisionPoint.copyFrom(p3);
  9490. }
  9491. p2.subtractToRef(p1, this._edge);
  9492. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9493. var edgeSquaredLength = this._edge.lengthSquared();
  9494. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9495. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9496. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9497. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9498. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9499. lowestRoot = getLowestRoot(a, b, c, t);
  9500. if (lowestRoot.found) {
  9501. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9502. if (f >= 0.0 && f <= 1.0) {
  9503. t = lowestRoot.root;
  9504. found = true;
  9505. this._edge.scaleInPlace(f);
  9506. p1.addToRef(this._edge, this._collisionPoint);
  9507. }
  9508. }
  9509. p3.subtractToRef(p2, this._edge);
  9510. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9511. edgeSquaredLength = this._edge.lengthSquared();
  9512. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9513. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9514. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9515. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9516. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9517. lowestRoot = getLowestRoot(a, b, c, t);
  9518. if (lowestRoot.found) {
  9519. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9520. if (f >= 0.0 && f <= 1.0) {
  9521. t = lowestRoot.root;
  9522. found = true;
  9523. this._edge.scaleInPlace(f);
  9524. p2.addToRef(this._edge, this._collisionPoint);
  9525. }
  9526. }
  9527. p1.subtractToRef(p3, this._edge);
  9528. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9529. edgeSquaredLength = this._edge.lengthSquared();
  9530. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9531. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9532. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9533. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9534. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9535. lowestRoot = getLowestRoot(a, b, c, t);
  9536. if (lowestRoot.found) {
  9537. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9538. if (f >= 0.0 && f <= 1.0) {
  9539. t = lowestRoot.root;
  9540. found = true;
  9541. this._edge.scaleInPlace(f);
  9542. p3.addToRef(this._edge, this._collisionPoint);
  9543. }
  9544. }
  9545. }
  9546. if (found) {
  9547. var distToCollision = t * this.velocity.length();
  9548. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9549. if (!this.intersectionPoint) {
  9550. this.intersectionPoint = this._collisionPoint.clone();
  9551. }
  9552. else {
  9553. this.intersectionPoint.copyFrom(this._collisionPoint);
  9554. }
  9555. this.nearestDistance = distToCollision;
  9556. this.collisionFound = true;
  9557. }
  9558. }
  9559. };
  9560. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9561. for (var i = indexStart; i < indexEnd; i += 3) {
  9562. var p1 = pts[indices[i] - decal];
  9563. var p2 = pts[indices[i + 1] - decal];
  9564. var p3 = pts[indices[i + 2] - decal];
  9565. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9566. }
  9567. };
  9568. Collider.prototype._getResponse = function (pos, vel) {
  9569. pos.addToRef(vel, this._destinationPoint);
  9570. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9571. this.basePoint.addToRef(vel, pos);
  9572. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9573. this._slidePlaneNormal.normalize();
  9574. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9575. pos.addInPlace(this._displacementVector);
  9576. this.intersectionPoint.addInPlace(this._displacementVector);
  9577. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9578. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9579. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9580. };
  9581. return Collider;
  9582. })();
  9583. BABYLON.Collider = Collider;
  9584. })(BABYLON || (BABYLON = {}));
  9585. var BABYLON;
  9586. (function (BABYLON) {
  9587. //WebWorker code will be inserted to this variable.
  9588. BABYLON.CollisionWorker = "";
  9589. (function (WorkerTaskType) {
  9590. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9591. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9592. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9593. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9594. var WorkerTaskType = BABYLON.WorkerTaskType;
  9595. (function (WorkerReplyType) {
  9596. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9597. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9598. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9599. var WorkerReplyType = BABYLON.WorkerReplyType;
  9600. var CollisionCoordinatorWorker = (function () {
  9601. function CollisionCoordinatorWorker() {
  9602. var _this = this;
  9603. this._scaledPosition = BABYLON.Vector3.Zero();
  9604. this._scaledVelocity = BABYLON.Vector3.Zero();
  9605. this.onMeshUpdated = function (mesh) {
  9606. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9607. };
  9608. this.onGeometryUpdated = function (geometry) {
  9609. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9610. };
  9611. this._afterRender = function () {
  9612. if (!_this._init)
  9613. return;
  9614. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9615. return;
  9616. }
  9617. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9618. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9619. if (_this._runningUpdated > 4) {
  9620. return;
  9621. }
  9622. ++_this._runningUpdated;
  9623. var payload = {
  9624. updatedMeshes: _this._addUpdateMeshesList,
  9625. updatedGeometries: _this._addUpdateGeometriesList,
  9626. removedGeometries: _this._toRemoveGeometryArray,
  9627. removedMeshes: _this._toRemoveMeshesArray
  9628. };
  9629. var message = {
  9630. payload: payload,
  9631. taskType: WorkerTaskType.UPDATE
  9632. };
  9633. var serializable = [];
  9634. for (var id in payload.updatedGeometries) {
  9635. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9636. //prepare transferables
  9637. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9638. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9639. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9640. }
  9641. }
  9642. _this._worker.postMessage(message, serializable);
  9643. _this._addUpdateMeshesList = {};
  9644. _this._addUpdateGeometriesList = {};
  9645. _this._toRemoveGeometryArray = [];
  9646. _this._toRemoveMeshesArray = [];
  9647. };
  9648. this._onMessageFromWorker = function (e) {
  9649. var returnData = e.data;
  9650. if (returnData.error != WorkerReplyType.SUCCESS) {
  9651. //TODO what errors can be returned from the worker?
  9652. BABYLON.Tools.Warn("error returned from worker!");
  9653. return;
  9654. }
  9655. switch (returnData.taskType) {
  9656. case WorkerTaskType.INIT:
  9657. _this._init = true;
  9658. //Update the worked with ALL of the scene's current state
  9659. _this._scene.meshes.forEach(function (mesh) {
  9660. _this.onMeshAdded(mesh);
  9661. });
  9662. _this._scene.getGeometries().forEach(function (geometry) {
  9663. _this.onGeometryAdded(geometry);
  9664. });
  9665. break;
  9666. case WorkerTaskType.UPDATE:
  9667. _this._runningUpdated--;
  9668. break;
  9669. case WorkerTaskType.COLLIDE:
  9670. _this._runningCollisionTask = false;
  9671. var returnPayload = returnData.payload;
  9672. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9673. return;
  9674. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9675. //cleanup
  9676. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9677. break;
  9678. }
  9679. };
  9680. this._collisionsCallbackArray = [];
  9681. this._init = false;
  9682. this._runningUpdated = 0;
  9683. this._runningCollisionTask = false;
  9684. this._addUpdateMeshesList = {};
  9685. this._addUpdateGeometriesList = {};
  9686. this._toRemoveGeometryArray = [];
  9687. this._toRemoveMeshesArray = [];
  9688. }
  9689. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9690. if (!this._init)
  9691. return;
  9692. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9693. return;
  9694. position.divideToRef(collider.radius, this._scaledPosition);
  9695. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9696. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9697. var payload = {
  9698. collider: {
  9699. position: this._scaledPosition.asArray(),
  9700. velocity: this._scaledVelocity.asArray(),
  9701. radius: collider.radius.asArray()
  9702. },
  9703. collisionId: collisionIndex,
  9704. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9705. maximumRetry: maximumRetry
  9706. };
  9707. var message = {
  9708. payload: payload,
  9709. taskType: WorkerTaskType.COLLIDE
  9710. };
  9711. this._worker.postMessage(message);
  9712. };
  9713. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9714. this._scene = scene;
  9715. this._scene.registerAfterRender(this._afterRender);
  9716. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9717. this._worker = new Worker(workerUrl);
  9718. this._worker.onmessage = this._onMessageFromWorker;
  9719. var message = {
  9720. payload: {},
  9721. taskType: WorkerTaskType.INIT
  9722. };
  9723. this._worker.postMessage(message);
  9724. };
  9725. CollisionCoordinatorWorker.prototype.destroy = function () {
  9726. this._scene.unregisterAfterRender(this._afterRender);
  9727. this._worker.terminate();
  9728. };
  9729. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9730. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9731. this.onMeshUpdated(mesh);
  9732. };
  9733. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9734. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9735. };
  9736. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9737. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9738. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9739. this.onGeometryUpdated(geometry);
  9740. };
  9741. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9742. this._toRemoveGeometryArray.push(geometry.id);
  9743. };
  9744. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9745. var submeshes = [];
  9746. if (mesh.subMeshes) {
  9747. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9748. return {
  9749. position: idx,
  9750. verticesStart: sm.verticesStart,
  9751. verticesCount: sm.verticesCount,
  9752. indexStart: sm.indexStart,
  9753. indexCount: sm.indexCount,
  9754. hasMaterial: !!sm.getMaterial(),
  9755. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9756. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9757. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9758. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9759. };
  9760. });
  9761. }
  9762. var geometryId = null;
  9763. if (mesh instanceof BABYLON.Mesh) {
  9764. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9765. }
  9766. else if (mesh instanceof BABYLON.InstancedMesh) {
  9767. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9768. }
  9769. return {
  9770. uniqueId: mesh.uniqueId,
  9771. id: mesh.id,
  9772. name: mesh.name,
  9773. geometryId: geometryId,
  9774. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9775. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9776. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9777. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9778. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9779. subMeshes: submeshes,
  9780. checkCollisions: mesh.checkCollisions
  9781. };
  9782. };
  9783. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9784. return {
  9785. id: geometry.id,
  9786. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9787. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9788. indices: new Int32Array(geometry.getIndices() || []),
  9789. };
  9790. };
  9791. return CollisionCoordinatorWorker;
  9792. })();
  9793. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9794. var CollisionCoordinatorLegacy = (function () {
  9795. function CollisionCoordinatorLegacy() {
  9796. this._scaledPosition = BABYLON.Vector3.Zero();
  9797. this._scaledVelocity = BABYLON.Vector3.Zero();
  9798. this._finalPosition = BABYLON.Vector3.Zero();
  9799. }
  9800. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9801. position.divideToRef(collider.radius, this._scaledPosition);
  9802. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9803. collider.collidedMesh = null;
  9804. collider.retry = 0;
  9805. collider.initialVelocity = this._scaledVelocity;
  9806. collider.initialPosition = this._scaledPosition;
  9807. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9808. this._finalPosition.multiplyInPlace(collider.radius);
  9809. //run the callback
  9810. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9811. };
  9812. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9813. this._scene = scene;
  9814. };
  9815. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9816. //Legacy need no destruction method.
  9817. };
  9818. //No update in legacy mode
  9819. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9820. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9821. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9822. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9823. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9824. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9825. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9826. if (excludedMesh === void 0) { excludedMesh = null; }
  9827. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9828. if (collider.retry >= maximumRetry) {
  9829. finalPosition.copyFrom(position);
  9830. return;
  9831. }
  9832. collider._initialize(position, velocity, closeDistance);
  9833. // Check all meshes
  9834. for (var index = 0; index < this._scene.meshes.length; index++) {
  9835. var mesh = this._scene.meshes[index];
  9836. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9837. mesh._checkCollision(collider);
  9838. }
  9839. }
  9840. if (!collider.collisionFound) {
  9841. position.addToRef(velocity, finalPosition);
  9842. return;
  9843. }
  9844. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9845. collider._getResponse(position, velocity);
  9846. }
  9847. if (velocity.length() <= closeDistance) {
  9848. finalPosition.copyFrom(position);
  9849. return;
  9850. }
  9851. collider.retry++;
  9852. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9853. };
  9854. return CollisionCoordinatorLegacy;
  9855. })();
  9856. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9857. })(BABYLON || (BABYLON = {}));
  9858. var BABYLON;
  9859. (function (BABYLON) {
  9860. var VRCameraMetrics = (function () {
  9861. function VRCameraMetrics() {
  9862. this.compensateDistortion = true;
  9863. }
  9864. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9865. get: function () {
  9866. return this.hResolution / (2 * this.vResolution);
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9872. get: function () {
  9873. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9874. },
  9875. enumerable: true,
  9876. configurable: true
  9877. });
  9878. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9879. get: function () {
  9880. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9881. var h = (4 * meters) / this.hScreenSize;
  9882. return BABYLON.Matrix.Translation(h, 0, 0);
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9888. get: function () {
  9889. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9890. var h = (4 * meters) / this.hScreenSize;
  9891. return BABYLON.Matrix.Translation(-h, 0, 0);
  9892. },
  9893. enumerable: true,
  9894. configurable: true
  9895. });
  9896. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9897. get: function () {
  9898. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9904. get: function () {
  9905. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9906. },
  9907. enumerable: true,
  9908. configurable: true
  9909. });
  9910. VRCameraMetrics.GetDefault = function () {
  9911. var result = new VRCameraMetrics();
  9912. result.hResolution = 1280;
  9913. result.vResolution = 800;
  9914. result.hScreenSize = 0.149759993;
  9915. result.vScreenSize = 0.0935999975;
  9916. result.vScreenCenter = 0.0467999987,
  9917. result.eyeToScreenDistance = 0.0410000011;
  9918. result.lensSeparationDistance = 0.0635000020;
  9919. result.interpupillaryDistance = 0.0640000030;
  9920. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9921. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9922. result.postProcessScaleFactor = 1.714605507808412;
  9923. result.lensCenterOffset = 0.151976421;
  9924. return result;
  9925. };
  9926. return VRCameraMetrics;
  9927. })();
  9928. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9929. var Camera = (function (_super) {
  9930. __extends(Camera, _super);
  9931. function Camera(name, position, scene) {
  9932. _super.call(this, name, scene);
  9933. this.position = position;
  9934. // Members
  9935. this.upVector = BABYLON.Vector3.Up();
  9936. this.orthoLeft = null;
  9937. this.orthoRight = null;
  9938. this.orthoBottom = null;
  9939. this.orthoTop = null;
  9940. this.fov = 0.8;
  9941. this.minZ = 1.0;
  9942. this.maxZ = 10000.0;
  9943. this.inertia = 0.9;
  9944. this.mode = Camera.PERSPECTIVE_CAMERA;
  9945. this.isIntermediate = false;
  9946. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9947. this.layerMask = 0x0FFFFFFF;
  9948. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9949. // Camera rig members
  9950. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9951. this._rigCameras = new Array();
  9952. // Cache
  9953. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9954. this._projectionMatrix = new BABYLON.Matrix();
  9955. this._postProcesses = new Array();
  9956. this._postProcessesTakenIndices = [];
  9957. this._activeMeshes = new BABYLON.SmartArray(256);
  9958. this._globalPosition = BABYLON.Vector3.Zero();
  9959. scene.addCamera(this);
  9960. if (!scene.activeCamera) {
  9961. scene.activeCamera = this;
  9962. }
  9963. }
  9964. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9965. get: function () {
  9966. return Camera._PERSPECTIVE_CAMERA;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9972. get: function () {
  9973. return Camera._ORTHOGRAPHIC_CAMERA;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9979. get: function () {
  9980. return Camera._FOVMODE_VERTICAL_FIXED;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9986. get: function () {
  9987. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9988. },
  9989. enumerable: true,
  9990. configurable: true
  9991. });
  9992. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9993. get: function () {
  9994. return Camera._RIG_MODE_NONE;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10000. get: function () {
  10001. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10007. get: function () {
  10008. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10014. get: function () {
  10015. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10016. },
  10017. enumerable: true,
  10018. configurable: true
  10019. });
  10020. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10021. get: function () {
  10022. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10028. get: function () {
  10029. return Camera._RIG_MODE_VR;
  10030. },
  10031. enumerable: true,
  10032. configurable: true
  10033. });
  10034. Object.defineProperty(Camera.prototype, "globalPosition", {
  10035. get: function () {
  10036. return this._globalPosition;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Camera.prototype.getActiveMeshes = function () {
  10042. return this._activeMeshes;
  10043. };
  10044. Camera.prototype.isActiveMesh = function (mesh) {
  10045. return (this._activeMeshes.indexOf(mesh) !== -1);
  10046. };
  10047. //Cache
  10048. Camera.prototype._initCache = function () {
  10049. _super.prototype._initCache.call(this);
  10050. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10051. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10052. this._cache.mode = undefined;
  10053. this._cache.minZ = undefined;
  10054. this._cache.maxZ = undefined;
  10055. this._cache.fov = undefined;
  10056. this._cache.aspectRatio = undefined;
  10057. this._cache.orthoLeft = undefined;
  10058. this._cache.orthoRight = undefined;
  10059. this._cache.orthoBottom = undefined;
  10060. this._cache.orthoTop = undefined;
  10061. this._cache.renderWidth = undefined;
  10062. this._cache.renderHeight = undefined;
  10063. };
  10064. Camera.prototype._updateCache = function (ignoreParentClass) {
  10065. if (!ignoreParentClass) {
  10066. _super.prototype._updateCache.call(this);
  10067. }
  10068. var engine = this.getEngine();
  10069. this._cache.position.copyFrom(this.position);
  10070. this._cache.upVector.copyFrom(this.upVector);
  10071. this._cache.mode = this.mode;
  10072. this._cache.minZ = this.minZ;
  10073. this._cache.maxZ = this.maxZ;
  10074. this._cache.fov = this.fov;
  10075. this._cache.aspectRatio = engine.getAspectRatio(this);
  10076. this._cache.orthoLeft = this.orthoLeft;
  10077. this._cache.orthoRight = this.orthoRight;
  10078. this._cache.orthoBottom = this.orthoBottom;
  10079. this._cache.orthoTop = this.orthoTop;
  10080. this._cache.renderWidth = engine.getRenderWidth();
  10081. this._cache.renderHeight = engine.getRenderHeight();
  10082. };
  10083. Camera.prototype._updateFromScene = function () {
  10084. this.updateCache();
  10085. this._update();
  10086. };
  10087. // Synchronized
  10088. Camera.prototype._isSynchronized = function () {
  10089. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10090. };
  10091. Camera.prototype._isSynchronizedViewMatrix = function () {
  10092. if (!_super.prototype._isSynchronized.call(this))
  10093. return false;
  10094. return this._cache.position.equals(this.position)
  10095. && this._cache.upVector.equals(this.upVector)
  10096. && this.isSynchronizedWithParent();
  10097. };
  10098. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10099. var check = this._cache.mode === this.mode
  10100. && this._cache.minZ === this.minZ
  10101. && this._cache.maxZ === this.maxZ;
  10102. if (!check) {
  10103. return false;
  10104. }
  10105. var engine = this.getEngine();
  10106. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10107. check = this._cache.fov === this.fov
  10108. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10109. }
  10110. else {
  10111. check = this._cache.orthoLeft === this.orthoLeft
  10112. && this._cache.orthoRight === this.orthoRight
  10113. && this._cache.orthoBottom === this.orthoBottom
  10114. && this._cache.orthoTop === this.orthoTop
  10115. && this._cache.renderWidth === engine.getRenderWidth()
  10116. && this._cache.renderHeight === engine.getRenderHeight();
  10117. }
  10118. return check;
  10119. };
  10120. // Controls
  10121. Camera.prototype.attachControl = function (element) {
  10122. };
  10123. Camera.prototype.detachControl = function (element) {
  10124. };
  10125. Camera.prototype._update = function () {
  10126. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10127. this._updateRigCameras();
  10128. }
  10129. this._checkInputs();
  10130. };
  10131. Camera.prototype._checkInputs = function () {
  10132. };
  10133. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10134. if (insertAt === void 0) { insertAt = null; }
  10135. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10136. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10137. return 0;
  10138. }
  10139. if (insertAt == null || insertAt < 0) {
  10140. this._postProcesses.push(postProcess);
  10141. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10142. return this._postProcesses.length - 1;
  10143. }
  10144. var add = 0;
  10145. var i;
  10146. var start;
  10147. if (this._postProcesses[insertAt]) {
  10148. start = this._postProcesses.length - 1;
  10149. for (i = start; i >= insertAt + 1; --i) {
  10150. this._postProcesses[i + 1] = this._postProcesses[i];
  10151. }
  10152. add = 1;
  10153. }
  10154. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10155. if (this._postProcessesTakenIndices[i] < insertAt) {
  10156. continue;
  10157. }
  10158. start = this._postProcessesTakenIndices.length - 1;
  10159. for (var j = start; j >= i; --j) {
  10160. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10161. }
  10162. this._postProcessesTakenIndices[i] = insertAt;
  10163. break;
  10164. }
  10165. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10166. this._postProcessesTakenIndices.push(insertAt);
  10167. }
  10168. var result = insertAt + add;
  10169. this._postProcesses[result] = postProcess;
  10170. return result;
  10171. };
  10172. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10173. if (atIndices === void 0) { atIndices = null; }
  10174. var result = [];
  10175. var i;
  10176. var index;
  10177. if (!atIndices) {
  10178. var length = this._postProcesses.length;
  10179. for (i = 0; i < length; i++) {
  10180. if (this._postProcesses[i] !== postProcess) {
  10181. continue;
  10182. }
  10183. delete this._postProcesses[i];
  10184. index = this._postProcessesTakenIndices.indexOf(i);
  10185. this._postProcessesTakenIndices.splice(index, 1);
  10186. }
  10187. }
  10188. else {
  10189. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10190. for (i = 0; i < atIndices.length; i++) {
  10191. var foundPostProcess = this._postProcesses[atIndices[i]];
  10192. if (foundPostProcess !== postProcess) {
  10193. result.push(i);
  10194. continue;
  10195. }
  10196. delete this._postProcesses[atIndices[i]];
  10197. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10198. this._postProcessesTakenIndices.splice(index, 1);
  10199. }
  10200. }
  10201. return result;
  10202. };
  10203. Camera.prototype.getWorldMatrix = function () {
  10204. if (!this._worldMatrix) {
  10205. this._worldMatrix = BABYLON.Matrix.Identity();
  10206. }
  10207. var viewMatrix = this.getViewMatrix();
  10208. viewMatrix.invertToRef(this._worldMatrix);
  10209. return this._worldMatrix;
  10210. };
  10211. Camera.prototype._getViewMatrix = function () {
  10212. return BABYLON.Matrix.Identity();
  10213. };
  10214. Camera.prototype.getViewMatrix = function (force) {
  10215. this._computedViewMatrix = this._computeViewMatrix(force);
  10216. if (!force && this._isSynchronizedViewMatrix()) {
  10217. return this._computedViewMatrix;
  10218. }
  10219. if (!this.parent || !this.parent.getWorldMatrix) {
  10220. this._globalPosition.copyFrom(this.position);
  10221. }
  10222. else {
  10223. if (!this._worldMatrix) {
  10224. this._worldMatrix = BABYLON.Matrix.Identity();
  10225. }
  10226. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10227. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10228. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10229. this._computedViewMatrix.invert();
  10230. this._markSyncedWithParent();
  10231. }
  10232. this._currentRenderId = this.getScene().getRenderId();
  10233. return this._computedViewMatrix;
  10234. };
  10235. Camera.prototype._computeViewMatrix = function (force) {
  10236. if (!force && this._isSynchronizedViewMatrix()) {
  10237. return this._computedViewMatrix;
  10238. }
  10239. this._computedViewMatrix = this._getViewMatrix();
  10240. this._currentRenderId = this.getScene().getRenderId();
  10241. return this._computedViewMatrix;
  10242. };
  10243. Camera.prototype.getProjectionMatrix = function (force) {
  10244. if (!force && this._isSynchronizedProjectionMatrix()) {
  10245. return this._projectionMatrix;
  10246. }
  10247. var engine = this.getEngine();
  10248. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10249. if (this.minZ <= 0) {
  10250. this.minZ = 0.1;
  10251. }
  10252. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10253. return this._projectionMatrix;
  10254. }
  10255. var halfWidth = engine.getRenderWidth() / 2.0;
  10256. var halfHeight = engine.getRenderHeight() / 2.0;
  10257. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10258. return this._projectionMatrix;
  10259. };
  10260. Camera.prototype.dispose = function () {
  10261. // Remove from scene
  10262. this.getScene().removeCamera(this);
  10263. while (this._rigCameras.length > 0) {
  10264. this._rigCameras.pop().dispose();
  10265. }
  10266. // Postprocesses
  10267. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10268. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10269. }
  10270. };
  10271. // ---- Camera rigs section ----
  10272. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10273. while (this._rigCameras.length > 0) {
  10274. this._rigCameras.pop().dispose();
  10275. }
  10276. this.cameraRigMode = mode;
  10277. this._cameraRigParams = {};
  10278. switch (this.cameraRigMode) {
  10279. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10280. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10281. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10282. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10283. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10284. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10285. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10286. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10287. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10288. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10289. break;
  10290. }
  10291. var postProcesses = new Array();
  10292. switch (this.cameraRigMode) {
  10293. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10294. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10295. this._rigCameras[0].isIntermediate = true;
  10296. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10297. postProcesses[1].onApply = function (effect) {
  10298. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10299. };
  10300. break;
  10301. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10302. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10303. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10304. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10305. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10306. var secondCamIndex = 1 - firstCamIndex;
  10307. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10308. this._rigCameras[firstCamIndex].isIntermediate = true;
  10309. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10310. break;
  10311. case Camera.RIG_MODE_VR:
  10312. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10313. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10314. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10315. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10316. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10317. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10318. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10319. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10320. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10321. if (metrics.compensateDistortion) {
  10322. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10323. }
  10324. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10325. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10326. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10327. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10328. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10329. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10330. if (metrics.compensateDistortion) {
  10331. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10332. }
  10333. break;
  10334. }
  10335. this._update();
  10336. };
  10337. Camera.prototype._getVRProjectionMatrix = function () {
  10338. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10339. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10340. return this._projectionMatrix;
  10341. };
  10342. Camera.prototype.setCameraRigParameter = function (name, value) {
  10343. this._cameraRigParams[name] = value;
  10344. //provisionnally:
  10345. if (name === "interaxialDistance") {
  10346. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10347. }
  10348. };
  10349. /**
  10350. * May needs to be overridden by children so sub has required properties to be copied
  10351. */
  10352. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10353. return null;
  10354. };
  10355. /**
  10356. * May needs to be overridden by children
  10357. */
  10358. Camera.prototype._updateRigCameras = function () {
  10359. for (var i = 0; i < this._rigCameras.length; i++) {
  10360. this._rigCameras[i].minZ = this.minZ;
  10361. this._rigCameras[i].maxZ = this.maxZ;
  10362. this._rigCameras[i].fov = this.fov;
  10363. }
  10364. // only update viewport when ANAGLYPH
  10365. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10366. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10367. }
  10368. };
  10369. // Statics
  10370. Camera._PERSPECTIVE_CAMERA = 0;
  10371. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10372. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10373. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10374. Camera._RIG_MODE_NONE = 0;
  10375. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10376. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10377. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10378. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10379. Camera._RIG_MODE_VR = 20;
  10380. return Camera;
  10381. })(BABYLON.Node);
  10382. BABYLON.Camera = Camera;
  10383. })(BABYLON || (BABYLON = {}));
  10384. var BABYLON;
  10385. (function (BABYLON) {
  10386. var TargetCamera = (function (_super) {
  10387. __extends(TargetCamera, _super);
  10388. function TargetCamera(name, position, scene) {
  10389. _super.call(this, name, position, scene);
  10390. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10391. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10392. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10393. this.speed = 2.0;
  10394. this.noRotationConstraint = false;
  10395. this.lockedTarget = null;
  10396. this._currentTarget = BABYLON.Vector3.Zero();
  10397. this._viewMatrix = BABYLON.Matrix.Zero();
  10398. this._camMatrix = BABYLON.Matrix.Zero();
  10399. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10400. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10401. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10402. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10403. this._lookAtTemp = BABYLON.Matrix.Zero();
  10404. this._tempMatrix = BABYLON.Matrix.Zero();
  10405. }
  10406. TargetCamera.prototype.getFrontPosition = function (distance) {
  10407. var direction = this.getTarget().subtract(this.position);
  10408. direction.normalize();
  10409. direction.scaleInPlace(distance);
  10410. return this.globalPosition.add(direction);
  10411. };
  10412. TargetCamera.prototype._getLockedTargetPosition = function () {
  10413. if (!this.lockedTarget) {
  10414. return null;
  10415. }
  10416. return this.lockedTarget.position || this.lockedTarget;
  10417. };
  10418. // Cache
  10419. TargetCamera.prototype._initCache = function () {
  10420. _super.prototype._initCache.call(this);
  10421. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10422. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10423. };
  10424. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10425. if (!ignoreParentClass) {
  10426. _super.prototype._updateCache.call(this);
  10427. }
  10428. var lockedTargetPosition = this._getLockedTargetPosition();
  10429. if (!lockedTargetPosition) {
  10430. this._cache.lockedTarget = null;
  10431. }
  10432. else {
  10433. if (!this._cache.lockedTarget) {
  10434. this._cache.lockedTarget = lockedTargetPosition.clone();
  10435. }
  10436. else {
  10437. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10438. }
  10439. }
  10440. this._cache.rotation.copyFrom(this.rotation);
  10441. };
  10442. // Synchronized
  10443. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10444. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10445. return false;
  10446. }
  10447. var lockedTargetPosition = this._getLockedTargetPosition();
  10448. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10449. && this._cache.rotation.equals(this.rotation);
  10450. };
  10451. // Methods
  10452. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10453. var engine = this.getEngine();
  10454. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10455. };
  10456. // Target
  10457. TargetCamera.prototype.setTarget = function (target) {
  10458. this.upVector.normalize();
  10459. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10460. this._camMatrix.invert();
  10461. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10462. var vDir = target.subtract(this.position);
  10463. if (vDir.x >= 0.0) {
  10464. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10465. }
  10466. else {
  10467. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10468. }
  10469. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10470. if (isNaN(this.rotation.x)) {
  10471. this.rotation.x = 0;
  10472. }
  10473. if (isNaN(this.rotation.y)) {
  10474. this.rotation.y = 0;
  10475. }
  10476. if (isNaN(this.rotation.z)) {
  10477. this.rotation.z = 0;
  10478. }
  10479. };
  10480. TargetCamera.prototype.getTarget = function () {
  10481. return this._currentTarget;
  10482. };
  10483. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10484. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10485. };
  10486. TargetCamera.prototype._updatePosition = function () {
  10487. this.position.addInPlace(this.cameraDirection);
  10488. };
  10489. TargetCamera.prototype._checkInputs = function () {
  10490. var needToMove = this._decideIfNeedsToMove();
  10491. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10492. // Move
  10493. if (needToMove) {
  10494. this._updatePosition();
  10495. }
  10496. // Rotate
  10497. if (needToRotate) {
  10498. this.rotation.x += this.cameraRotation.x;
  10499. this.rotation.y += this.cameraRotation.y;
  10500. if (!this.noRotationConstraint) {
  10501. var limit = (Math.PI / 2) * 0.95;
  10502. if (this.rotation.x > limit)
  10503. this.rotation.x = limit;
  10504. if (this.rotation.x < -limit)
  10505. this.rotation.x = -limit;
  10506. }
  10507. }
  10508. // Inertia
  10509. if (needToMove) {
  10510. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10511. this.cameraDirection.x = 0;
  10512. }
  10513. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10514. this.cameraDirection.y = 0;
  10515. }
  10516. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10517. this.cameraDirection.z = 0;
  10518. }
  10519. this.cameraDirection.scaleInPlace(this.inertia);
  10520. }
  10521. if (needToRotate) {
  10522. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10523. this.cameraRotation.x = 0;
  10524. }
  10525. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10526. this.cameraRotation.y = 0;
  10527. }
  10528. this.cameraRotation.scaleInPlace(this.inertia);
  10529. }
  10530. _super.prototype._checkInputs.call(this);
  10531. };
  10532. TargetCamera.prototype._getViewMatrix = function () {
  10533. if (!this.lockedTarget) {
  10534. // Compute
  10535. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10536. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10537. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10538. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10539. this._lookAtTemp.invert();
  10540. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10541. }
  10542. else {
  10543. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10544. }
  10545. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10546. // Computing target and final matrix
  10547. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10548. }
  10549. else {
  10550. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10551. }
  10552. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10553. return this._viewMatrix;
  10554. };
  10555. TargetCamera.prototype._getVRViewMatrix = function () {
  10556. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10557. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10558. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10559. // Computing target and final matrix
  10560. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10561. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10562. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10563. return this._viewMatrix;
  10564. };
  10565. /**
  10566. * @override
  10567. * Override Camera.createRigCamera
  10568. */
  10569. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10570. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10571. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10572. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10573. rigCamera._cameraRigParams = {};
  10574. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10575. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10576. }
  10577. return rigCamera;
  10578. }
  10579. return null;
  10580. };
  10581. /**
  10582. * @override
  10583. * Override Camera._updateRigCameras
  10584. */
  10585. TargetCamera.prototype._updateRigCameras = function () {
  10586. switch (this.cameraRigMode) {
  10587. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10588. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10589. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10590. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10591. case BABYLON.Camera.RIG_MODE_VR:
  10592. var camLeft = this._rigCameras[0];
  10593. var camRight = this._rigCameras[1];
  10594. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10595. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10596. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10597. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10598. camLeft.position.copyFrom(this.position);
  10599. camRight.position.copyFrom(this.position);
  10600. }
  10601. else {
  10602. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10603. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10604. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10605. camLeft.setTarget(this.getTarget());
  10606. camRight.setTarget(this.getTarget());
  10607. }
  10608. break;
  10609. }
  10610. _super.prototype._updateRigCameras.call(this);
  10611. };
  10612. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10613. if (!this._rigCamTransformMatrix) {
  10614. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10615. }
  10616. var target = this.getTarget();
  10617. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10618. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10619. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10620. };
  10621. return TargetCamera;
  10622. })(BABYLON.Camera);
  10623. BABYLON.TargetCamera = TargetCamera;
  10624. })(BABYLON || (BABYLON = {}));
  10625. var BABYLON;
  10626. (function (BABYLON) {
  10627. var FreeCamera = (function (_super) {
  10628. __extends(FreeCamera, _super);
  10629. function FreeCamera(name, position, scene) {
  10630. var _this = this;
  10631. _super.call(this, name, position, scene);
  10632. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10633. this.keysUp = [38];
  10634. this.keysDown = [40];
  10635. this.keysLeft = [37];
  10636. this.keysRight = [39];
  10637. this.checkCollisions = false;
  10638. this.applyGravity = false;
  10639. this.angularSensibility = 2000.0;
  10640. this._keys = [];
  10641. this._collider = new BABYLON.Collider();
  10642. this._needMoveForGravity = false;
  10643. this._oldPosition = BABYLON.Vector3.Zero();
  10644. this._diffPosition = BABYLON.Vector3.Zero();
  10645. this._newPosition = BABYLON.Vector3.Zero();
  10646. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10647. if (collidedMesh === void 0) { collidedMesh = null; }
  10648. //TODO move this to the collision coordinator!
  10649. if (_this.getScene().workerCollisions)
  10650. newPosition.multiplyInPlace(_this._collider.radius);
  10651. var updatePosition = function (newPos) {
  10652. _this._newPosition.copyFrom(newPos);
  10653. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10654. var oldPosition = _this.position.clone();
  10655. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10656. _this.position.addInPlace(_this._diffPosition);
  10657. if (_this.onCollide && collidedMesh) {
  10658. _this.onCollide(collidedMesh);
  10659. }
  10660. }
  10661. };
  10662. updatePosition(newPosition);
  10663. };
  10664. }
  10665. // Controls
  10666. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10667. var _this = this;
  10668. var previousPosition;
  10669. var engine = this.getEngine();
  10670. if (this._attachedElement) {
  10671. return;
  10672. }
  10673. this._attachedElement = element;
  10674. if (this._onMouseDown === undefined) {
  10675. this._onMouseDown = function (evt) {
  10676. previousPosition = {
  10677. x: evt.clientX,
  10678. y: evt.clientY
  10679. };
  10680. if (!noPreventDefault) {
  10681. evt.preventDefault();
  10682. }
  10683. };
  10684. this._onMouseUp = function (evt) {
  10685. previousPosition = null;
  10686. if (!noPreventDefault) {
  10687. evt.preventDefault();
  10688. }
  10689. };
  10690. this._onMouseOut = function (evt) {
  10691. previousPosition = null;
  10692. _this._keys = [];
  10693. if (!noPreventDefault) {
  10694. evt.preventDefault();
  10695. }
  10696. };
  10697. this._onMouseMove = function (evt) {
  10698. if (!previousPosition && !engine.isPointerLock) {
  10699. return;
  10700. }
  10701. var offsetX;
  10702. var offsetY;
  10703. if (!engine.isPointerLock) {
  10704. offsetX = evt.clientX - previousPosition.x;
  10705. offsetY = evt.clientY - previousPosition.y;
  10706. }
  10707. else {
  10708. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10709. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10710. }
  10711. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10712. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10713. previousPosition = {
  10714. x: evt.clientX,
  10715. y: evt.clientY
  10716. };
  10717. if (!noPreventDefault) {
  10718. evt.preventDefault();
  10719. }
  10720. };
  10721. this._onKeyDown = function (evt) {
  10722. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10723. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10724. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10725. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10726. var index = _this._keys.indexOf(evt.keyCode);
  10727. if (index === -1) {
  10728. _this._keys.push(evt.keyCode);
  10729. }
  10730. if (!noPreventDefault) {
  10731. evt.preventDefault();
  10732. }
  10733. }
  10734. };
  10735. this._onKeyUp = function (evt) {
  10736. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10737. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10738. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10739. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10740. var index = _this._keys.indexOf(evt.keyCode);
  10741. if (index >= 0) {
  10742. _this._keys.splice(index, 1);
  10743. }
  10744. if (!noPreventDefault) {
  10745. evt.preventDefault();
  10746. }
  10747. }
  10748. };
  10749. this._onLostFocus = function () {
  10750. _this._keys = [];
  10751. };
  10752. this._reset = function () {
  10753. _this._keys = [];
  10754. previousPosition = null;
  10755. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10756. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10757. };
  10758. }
  10759. element.addEventListener("mousedown", this._onMouseDown, false);
  10760. element.addEventListener("mouseup", this._onMouseUp, false);
  10761. element.addEventListener("mouseout", this._onMouseOut, false);
  10762. element.addEventListener("mousemove", this._onMouseMove, false);
  10763. BABYLON.Tools.RegisterTopRootEvents([
  10764. { name: "keydown", handler: this._onKeyDown },
  10765. { name: "keyup", handler: this._onKeyUp },
  10766. { name: "blur", handler: this._onLostFocus }
  10767. ]);
  10768. };
  10769. FreeCamera.prototype.detachControl = function (element) {
  10770. if (this._attachedElement != element) {
  10771. return;
  10772. }
  10773. element.removeEventListener("mousedown", this._onMouseDown);
  10774. element.removeEventListener("mouseup", this._onMouseUp);
  10775. element.removeEventListener("mouseout", this._onMouseOut);
  10776. element.removeEventListener("mousemove", this._onMouseMove);
  10777. BABYLON.Tools.UnregisterTopRootEvents([
  10778. { name: "keydown", handler: this._onKeyDown },
  10779. { name: "keyup", handler: this._onKeyUp },
  10780. { name: "blur", handler: this._onLostFocus }
  10781. ]);
  10782. this._attachedElement = null;
  10783. if (this._reset) {
  10784. this._reset();
  10785. }
  10786. };
  10787. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10788. var globalPosition;
  10789. if (this.parent) {
  10790. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10791. }
  10792. else {
  10793. globalPosition = this.position;
  10794. }
  10795. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10796. this._collider.radius = this.ellipsoid;
  10797. //no need for clone, as long as gravity is not on.
  10798. var actualVelocity = velocity;
  10799. //add gravity to the velocity to prevent the dual-collision checking
  10800. if (this.applyGravity) {
  10801. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10802. actualVelocity = velocity.add(this.getScene().gravity);
  10803. }
  10804. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10805. };
  10806. FreeCamera.prototype._checkInputs = function () {
  10807. if (!this._localDirection) {
  10808. this._localDirection = BABYLON.Vector3.Zero();
  10809. this._transformedDirection = BABYLON.Vector3.Zero();
  10810. }
  10811. // Keyboard
  10812. for (var index = 0; index < this._keys.length; index++) {
  10813. var keyCode = this._keys[index];
  10814. var speed = this._computeLocalCameraSpeed();
  10815. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10816. this._localDirection.copyFromFloats(-speed, 0, 0);
  10817. }
  10818. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10819. this._localDirection.copyFromFloats(0, 0, speed);
  10820. }
  10821. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10822. this._localDirection.copyFromFloats(speed, 0, 0);
  10823. }
  10824. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10825. this._localDirection.copyFromFloats(0, 0, -speed);
  10826. }
  10827. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10828. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10829. this.cameraDirection.addInPlace(this._transformedDirection);
  10830. }
  10831. _super.prototype._checkInputs.call(this);
  10832. };
  10833. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10834. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10835. };
  10836. FreeCamera.prototype._updatePosition = function () {
  10837. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10838. this._collideWithWorld(this.cameraDirection);
  10839. }
  10840. else {
  10841. this.position.addInPlace(this.cameraDirection);
  10842. }
  10843. };
  10844. return FreeCamera;
  10845. })(BABYLON.TargetCamera);
  10846. BABYLON.FreeCamera = FreeCamera;
  10847. })(BABYLON || (BABYLON = {}));
  10848. var BABYLON;
  10849. (function (BABYLON) {
  10850. var FollowCamera = (function (_super) {
  10851. __extends(FollowCamera, _super);
  10852. function FollowCamera(name, position, scene) {
  10853. _super.call(this, name, position, scene);
  10854. this.radius = 12;
  10855. this.rotationOffset = 0;
  10856. this.heightOffset = 4;
  10857. this.cameraAcceleration = 0.05;
  10858. this.maxCameraSpeed = 20;
  10859. }
  10860. FollowCamera.prototype.getRadians = function (degrees) {
  10861. return degrees * Math.PI / 180;
  10862. };
  10863. FollowCamera.prototype.follow = function (cameraTarget) {
  10864. if (!cameraTarget)
  10865. return;
  10866. var yRotation;
  10867. if (cameraTarget.rotationQuaternion) {
  10868. var rotMatrix = new BABYLON.Matrix();
  10869. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10870. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10871. }
  10872. else {
  10873. yRotation = cameraTarget.rotation.y;
  10874. }
  10875. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10876. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10877. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10878. var dx = targetX - this.position.x;
  10879. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10880. var dz = (targetZ) - this.position.z;
  10881. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10882. var vy = dy * this.cameraAcceleration;
  10883. var vz = dz * this.cameraAcceleration * 2;
  10884. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10885. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10886. }
  10887. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10888. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10889. }
  10890. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10891. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10892. }
  10893. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10894. this.setTarget(cameraTarget.position);
  10895. };
  10896. FollowCamera.prototype._checkInputs = function () {
  10897. _super.prototype._checkInputs.call(this);
  10898. this.follow(this.target);
  10899. };
  10900. return FollowCamera;
  10901. })(BABYLON.TargetCamera);
  10902. BABYLON.FollowCamera = FollowCamera;
  10903. var ArcFollowCamera = (function (_super) {
  10904. __extends(ArcFollowCamera, _super);
  10905. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10906. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10907. this.alpha = alpha;
  10908. this.beta = beta;
  10909. this.radius = radius;
  10910. this.target = target;
  10911. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10912. this.follow();
  10913. }
  10914. ArcFollowCamera.prototype.follow = function () {
  10915. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10916. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10917. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10918. this.position = this.target.position.add(this._cartesianCoordinates);
  10919. this.setTarget(this.target.position);
  10920. };
  10921. ArcFollowCamera.prototype._checkInputs = function () {
  10922. _super.prototype._checkInputs.call(this);
  10923. this.follow();
  10924. };
  10925. return ArcFollowCamera;
  10926. })(BABYLON.TargetCamera);
  10927. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10928. })(BABYLON || (BABYLON = {}));
  10929. var BABYLON;
  10930. (function (BABYLON) {
  10931. // We're mainly based on the logic defined into the FreeCamera code
  10932. var TouchCamera = (function (_super) {
  10933. __extends(TouchCamera, _super);
  10934. function TouchCamera(name, position, scene) {
  10935. _super.call(this, name, position, scene);
  10936. this._offsetX = null;
  10937. this._offsetY = null;
  10938. this._pointerCount = 0;
  10939. this._pointerPressed = [];
  10940. this.angularSensibility = 200000.0;
  10941. this.moveSensibility = 500.0;
  10942. }
  10943. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10944. var _this = this;
  10945. var previousPosition;
  10946. if (this._attachedCanvas) {
  10947. return;
  10948. }
  10949. this._attachedCanvas = canvas;
  10950. if (this._onPointerDown === undefined) {
  10951. this._onPointerDown = function (evt) {
  10952. if (!noPreventDefault) {
  10953. evt.preventDefault();
  10954. }
  10955. _this._pointerPressed.push(evt.pointerId);
  10956. if (_this._pointerPressed.length !== 1) {
  10957. return;
  10958. }
  10959. previousPosition = {
  10960. x: evt.clientX,
  10961. y: evt.clientY
  10962. };
  10963. };
  10964. this._onPointerUp = function (evt) {
  10965. if (!noPreventDefault) {
  10966. evt.preventDefault();
  10967. }
  10968. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10969. if (index === -1) {
  10970. return;
  10971. }
  10972. _this._pointerPressed.splice(index, 1);
  10973. if (index != 0) {
  10974. return;
  10975. }
  10976. previousPosition = null;
  10977. _this._offsetX = null;
  10978. _this._offsetY = null;
  10979. };
  10980. this._onPointerMove = function (evt) {
  10981. if (!noPreventDefault) {
  10982. evt.preventDefault();
  10983. }
  10984. if (!previousPosition) {
  10985. return;
  10986. }
  10987. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10988. if (index != 0) {
  10989. return;
  10990. }
  10991. _this._offsetX = evt.clientX - previousPosition.x;
  10992. _this._offsetY = -(evt.clientY - previousPosition.y);
  10993. };
  10994. this._onLostFocus = function () {
  10995. _this._offsetX = null;
  10996. _this._offsetY = null;
  10997. };
  10998. }
  10999. canvas.addEventListener("pointerdown", this._onPointerDown);
  11000. canvas.addEventListener("pointerup", this._onPointerUp);
  11001. canvas.addEventListener("pointerout", this._onPointerUp);
  11002. canvas.addEventListener("pointermove", this._onPointerMove);
  11003. BABYLON.Tools.RegisterTopRootEvents([
  11004. { name: "blur", handler: this._onLostFocus }
  11005. ]);
  11006. };
  11007. TouchCamera.prototype.detachControl = function (canvas) {
  11008. if (this._attachedCanvas != canvas) {
  11009. return;
  11010. }
  11011. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11012. canvas.removeEventListener("pointerup", this._onPointerUp);
  11013. canvas.removeEventListener("pointerout", this._onPointerUp);
  11014. canvas.removeEventListener("pointermove", this._onPointerMove);
  11015. BABYLON.Tools.UnregisterTopRootEvents([
  11016. { name: "blur", handler: this._onLostFocus }
  11017. ]);
  11018. this._attachedCanvas = null;
  11019. };
  11020. TouchCamera.prototype._checkInputs = function () {
  11021. if (this._offsetX) {
  11022. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  11023. if (this._pointerPressed.length > 1) {
  11024. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  11025. }
  11026. else {
  11027. var speed = this._computeLocalCameraSpeed();
  11028. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11029. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11030. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11031. }
  11032. }
  11033. _super.prototype._checkInputs.call(this);
  11034. };
  11035. return TouchCamera;
  11036. })(BABYLON.FreeCamera);
  11037. BABYLON.TouchCamera = TouchCamera;
  11038. })(BABYLON || (BABYLON = {}));
  11039. var BABYLON;
  11040. (function (BABYLON) {
  11041. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11042. var ArcRotateCamera = (function (_super) {
  11043. __extends(ArcRotateCamera, _super);
  11044. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11045. var _this = this;
  11046. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11047. this.alpha = alpha;
  11048. this.beta = beta;
  11049. this.radius = radius;
  11050. this.target = target;
  11051. this.inertialAlphaOffset = 0;
  11052. this.inertialBetaOffset = 0;
  11053. this.inertialRadiusOffset = 0;
  11054. this.lowerAlphaLimit = null;
  11055. this.upperAlphaLimit = null;
  11056. this.lowerBetaLimit = 0.01;
  11057. this.upperBetaLimit = Math.PI;
  11058. this.lowerRadiusLimit = null;
  11059. this.upperRadiusLimit = null;
  11060. this.angularSensibilityX = 1000.0;
  11061. this.angularSensibilityY = 1000.0;
  11062. this.wheelPrecision = 3.0;
  11063. this.pinchPrecision = 2.0;
  11064. this.panningSensibility = 50.0;
  11065. this.inertialPanningX = 0;
  11066. this.inertialPanningY = 0;
  11067. this.keysUp = [38];
  11068. this.keysDown = [40];
  11069. this.keysLeft = [37];
  11070. this.keysRight = [39];
  11071. this.zoomOnFactor = 1;
  11072. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11073. this.pinchInwards = true;
  11074. this.allowUpsideDown = true;
  11075. this._keys = [];
  11076. this._viewMatrix = new BABYLON.Matrix();
  11077. this._isRightClick = false;
  11078. this._isCtrlPushed = false;
  11079. this.checkCollisions = false;
  11080. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11081. this._collider = new BABYLON.Collider();
  11082. this._previousPosition = BABYLON.Vector3.Zero();
  11083. this._collisionVelocity = BABYLON.Vector3.Zero();
  11084. this._newPosition = BABYLON.Vector3.Zero();
  11085. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11086. if (collidedMesh === void 0) { collidedMesh = null; }
  11087. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11088. newPosition.multiplyInPlace(_this._collider.radius);
  11089. }
  11090. if (!collidedMesh) {
  11091. _this._previousPosition.copyFrom(_this.position);
  11092. }
  11093. else {
  11094. _this.setPosition(_this.position);
  11095. if (_this.onCollide) {
  11096. _this.onCollide(collidedMesh);
  11097. }
  11098. }
  11099. // Recompute because of constraints
  11100. var cosa = Math.cos(_this.alpha);
  11101. var sina = Math.sin(_this.alpha);
  11102. var cosb = Math.cos(_this.beta);
  11103. var sinb = Math.sin(_this.beta);
  11104. var target = _this._getTargetPosition();
  11105. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11106. _this.position.copyFrom(_this._newPosition);
  11107. var up = _this.upVector;
  11108. if (_this.allowUpsideDown && _this.beta < 0) {
  11109. var up = up.clone();
  11110. up = up.negate();
  11111. }
  11112. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11113. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11114. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11115. _this._collisionTriggered = false;
  11116. };
  11117. if (!this.target) {
  11118. this.target = BABYLON.Vector3.Zero();
  11119. }
  11120. this.getViewMatrix();
  11121. }
  11122. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11123. //deprecated angularSensibility support
  11124. get: function () {
  11125. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11126. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11127. },
  11128. //deprecated angularSensibility support
  11129. set: function (value) {
  11130. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11131. this.angularSensibilityX = value;
  11132. this.angularSensibilityY = value;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. ArcRotateCamera.prototype._getTargetPosition = function () {
  11138. return this.target.position || this.target;
  11139. };
  11140. // Cache
  11141. ArcRotateCamera.prototype._initCache = function () {
  11142. _super.prototype._initCache.call(this);
  11143. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11144. this._cache.alpha = undefined;
  11145. this._cache.beta = undefined;
  11146. this._cache.radius = undefined;
  11147. this._cache.targetScreenOffset = undefined;
  11148. };
  11149. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11150. if (!ignoreParentClass) {
  11151. _super.prototype._updateCache.call(this);
  11152. }
  11153. this._cache.target.copyFrom(this._getTargetPosition());
  11154. this._cache.alpha = this.alpha;
  11155. this._cache.beta = this.beta;
  11156. this._cache.radius = this.radius;
  11157. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11158. };
  11159. // Synchronized
  11160. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11161. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11162. return false;
  11163. return this._cache.target.equals(this._getTargetPosition())
  11164. && this._cache.alpha === this.alpha
  11165. && this._cache.beta === this.beta
  11166. && this._cache.radius === this.radius
  11167. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11168. };
  11169. // Methods
  11170. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11171. var _this = this;
  11172. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11173. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11174. var previousPinchDistance = 0;
  11175. var pointers = new BABYLON.SmartCollection();
  11176. if (this._attachedElement) {
  11177. return;
  11178. }
  11179. this._attachedElement = element;
  11180. var engine = this.getEngine();
  11181. if (this._onPointerDown === undefined) {
  11182. this._onPointerDown = function (evt) {
  11183. // Manage panning with right click
  11184. _this._isRightClick = evt.button === 2 ? true : false;
  11185. // manage pointers
  11186. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11187. cacheSoloPointer = pointers.item(evt.pointerId);
  11188. if (!noPreventDefault) {
  11189. evt.preventDefault();
  11190. }
  11191. };
  11192. this._onPointerUp = function (evt) {
  11193. cacheSoloPointer = null;
  11194. previousPinchDistance = 0;
  11195. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11196. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11197. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11198. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11199. pointers.empty();
  11200. if (!noPreventDefault) {
  11201. evt.preventDefault();
  11202. }
  11203. };
  11204. this._onContextMenu = function (evt) {
  11205. evt.preventDefault();
  11206. };
  11207. this._onPointerMove = function (evt) {
  11208. if (!noPreventDefault) {
  11209. evt.preventDefault();
  11210. }
  11211. switch (pointers.count) {
  11212. case 1:
  11213. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11214. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11215. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11216. }
  11217. else {
  11218. var offsetX = evt.clientX - cacheSoloPointer.x;
  11219. var offsetY = evt.clientY - cacheSoloPointer.y;
  11220. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11221. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11222. }
  11223. cacheSoloPointer.x = evt.clientX;
  11224. cacheSoloPointer.y = evt.clientY;
  11225. break;
  11226. case 2:
  11227. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11228. pointers.item(evt.pointerId).x = evt.clientX;
  11229. pointers.item(evt.pointerId).y = evt.clientY;
  11230. var direction = _this.pinchInwards ? 1 : -1;
  11231. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11232. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11233. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11234. if (previousPinchDistance === 0) {
  11235. previousPinchDistance = pinchSquaredDistance;
  11236. return;
  11237. }
  11238. if (pinchSquaredDistance !== previousPinchDistance) {
  11239. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11240. previousPinchDistance = pinchSquaredDistance;
  11241. }
  11242. break;
  11243. default:
  11244. if (pointers.item(evt.pointerId)) {
  11245. pointers.item(evt.pointerId).x = evt.clientX;
  11246. pointers.item(evt.pointerId).y = evt.clientY;
  11247. }
  11248. }
  11249. };
  11250. this._onMouseMove = function (evt) {
  11251. if (!engine.isPointerLock) {
  11252. return;
  11253. }
  11254. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11255. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11256. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11257. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11258. if (!noPreventDefault) {
  11259. evt.preventDefault();
  11260. }
  11261. };
  11262. this._wheel = function (event) {
  11263. var delta = 0;
  11264. if (event.wheelDelta) {
  11265. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11266. }
  11267. else if (event.detail) {
  11268. delta = -event.detail / _this.wheelPrecision;
  11269. }
  11270. if (delta)
  11271. _this.inertialRadiusOffset += delta;
  11272. if (event.preventDefault) {
  11273. if (!noPreventDefault) {
  11274. event.preventDefault();
  11275. }
  11276. }
  11277. };
  11278. this._onKeyDown = function (evt) {
  11279. _this._isCtrlPushed = evt.ctrlKey;
  11280. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11281. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11282. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11283. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11284. var index = _this._keys.indexOf(evt.keyCode);
  11285. if (index === -1) {
  11286. _this._keys.push(evt.keyCode);
  11287. }
  11288. if (evt.preventDefault) {
  11289. if (!noPreventDefault) {
  11290. evt.preventDefault();
  11291. }
  11292. }
  11293. }
  11294. };
  11295. this._onKeyUp = function (evt) {
  11296. _this._isCtrlPushed = evt.ctrlKey;
  11297. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11298. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11299. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11300. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11301. var index = _this._keys.indexOf(evt.keyCode);
  11302. if (index >= 0) {
  11303. _this._keys.splice(index, 1);
  11304. }
  11305. if (evt.preventDefault) {
  11306. if (!noPreventDefault) {
  11307. evt.preventDefault();
  11308. }
  11309. }
  11310. }
  11311. };
  11312. this._onLostFocus = function () {
  11313. _this._keys = [];
  11314. pointers.empty();
  11315. previousPinchDistance = 0;
  11316. cacheSoloPointer = null;
  11317. };
  11318. this._onGestureStart = function (e) {
  11319. if (window.MSGesture === undefined) {
  11320. return;
  11321. }
  11322. if (!_this._MSGestureHandler) {
  11323. _this._MSGestureHandler = new MSGesture();
  11324. _this._MSGestureHandler.target = element;
  11325. }
  11326. _this._MSGestureHandler.addPointer(e.pointerId);
  11327. };
  11328. this._onGesture = function (e) {
  11329. _this.radius *= e.scale;
  11330. if (e.preventDefault) {
  11331. if (!noPreventDefault) {
  11332. e.stopPropagation();
  11333. e.preventDefault();
  11334. }
  11335. }
  11336. };
  11337. this._reset = function () {
  11338. _this._keys = [];
  11339. _this.inertialAlphaOffset = 0;
  11340. _this.inertialBetaOffset = 0;
  11341. _this.inertialRadiusOffset = 0;
  11342. pointers.empty();
  11343. previousPinchDistance = 0;
  11344. cacheSoloPointer = null;
  11345. };
  11346. }
  11347. if (!useCtrlForPanning) {
  11348. element.addEventListener("contextmenu", this._onContextMenu, false);
  11349. }
  11350. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11351. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11352. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11353. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11354. element.addEventListener("mousemove", this._onMouseMove, false);
  11355. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11356. element.addEventListener("MSGestureChange", this._onGesture, false);
  11357. element.addEventListener('mousewheel', this._wheel, false);
  11358. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11359. BABYLON.Tools.RegisterTopRootEvents([
  11360. { name: "keydown", handler: this._onKeyDown },
  11361. { name: "keyup", handler: this._onKeyUp },
  11362. { name: "blur", handler: this._onLostFocus }
  11363. ]);
  11364. };
  11365. ArcRotateCamera.prototype.detachControl = function (element) {
  11366. if (this._attachedElement !== element) {
  11367. return;
  11368. }
  11369. element.removeEventListener("contextmenu", this._onContextMenu);
  11370. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11371. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11372. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11373. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11374. element.removeEventListener("mousemove", this._onMouseMove);
  11375. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11376. element.removeEventListener("MSGestureChange", this._onGesture);
  11377. element.removeEventListener('mousewheel', this._wheel);
  11378. element.removeEventListener('DOMMouseScroll', this._wheel);
  11379. BABYLON.Tools.UnregisterTopRootEvents([
  11380. { name: "keydown", handler: this._onKeyDown },
  11381. { name: "keyup", handler: this._onKeyUp },
  11382. { name: "blur", handler: this._onLostFocus }
  11383. ]);
  11384. this._MSGestureHandler = null;
  11385. this._attachedElement = null;
  11386. if (this._reset) {
  11387. this._reset();
  11388. }
  11389. };
  11390. ArcRotateCamera.prototype._checkInputs = function () {
  11391. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11392. if (this._collisionTriggered) {
  11393. return;
  11394. }
  11395. // Keyboard
  11396. for (var index = 0; index < this._keys.length; index++) {
  11397. var keyCode = this._keys[index];
  11398. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11399. this.inertialAlphaOffset -= 0.01;
  11400. }
  11401. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11402. this.inertialBetaOffset -= 0.01;
  11403. }
  11404. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11405. this.inertialAlphaOffset += 0.01;
  11406. }
  11407. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11408. this.inertialBetaOffset += 0.01;
  11409. }
  11410. }
  11411. // Inertia
  11412. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11413. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11414. this.beta += this.inertialBetaOffset;
  11415. this.radius -= this.inertialRadiusOffset;
  11416. this.inertialAlphaOffset *= this.inertia;
  11417. this.inertialBetaOffset *= this.inertia;
  11418. this.inertialRadiusOffset *= this.inertia;
  11419. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11420. this.inertialAlphaOffset = 0;
  11421. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11422. this.inertialBetaOffset = 0;
  11423. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11424. this.inertialRadiusOffset = 0;
  11425. }
  11426. // Panning inertia
  11427. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11428. if (!this._localDirection) {
  11429. this._localDirection = BABYLON.Vector3.Zero();
  11430. this._transformedDirection = BABYLON.Vector3.Zero();
  11431. }
  11432. this.inertialPanningX *= this.inertia;
  11433. this.inertialPanningY *= this.inertia;
  11434. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11435. this.inertialPanningX = 0;
  11436. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11437. this.inertialPanningY = 0;
  11438. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11439. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11440. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11441. this.target.addInPlace(this._transformedDirection);
  11442. }
  11443. // Limits
  11444. this._checkLimits();
  11445. _super.prototype._checkInputs.call(this);
  11446. };
  11447. ArcRotateCamera.prototype._checkLimits = function () {
  11448. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11449. if (this.allowUpsideDown && this.beta > Math.PI) {
  11450. this.beta = this.beta - (2 * Math.PI);
  11451. }
  11452. }
  11453. else {
  11454. if (this.beta < this.lowerBetaLimit) {
  11455. this.beta = this.lowerBetaLimit;
  11456. }
  11457. }
  11458. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11459. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11460. this.beta = this.beta + (2 * Math.PI);
  11461. }
  11462. }
  11463. else {
  11464. if (this.beta > this.upperBetaLimit) {
  11465. this.beta = this.upperBetaLimit;
  11466. }
  11467. }
  11468. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11469. this.alpha = this.lowerAlphaLimit;
  11470. }
  11471. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11472. this.alpha = this.upperAlphaLimit;
  11473. }
  11474. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11475. this.radius = this.lowerRadiusLimit;
  11476. }
  11477. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11478. this.radius = this.upperRadiusLimit;
  11479. }
  11480. };
  11481. ArcRotateCamera.prototype.setPosition = function (position) {
  11482. var radiusv3 = position.subtract(this._getTargetPosition());
  11483. this.radius = radiusv3.length();
  11484. // Alpha
  11485. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11486. if (radiusv3.z < 0) {
  11487. this.alpha = 2 * Math.PI - this.alpha;
  11488. }
  11489. // Beta
  11490. this.beta = Math.acos(radiusv3.y / this.radius);
  11491. this._checkLimits();
  11492. };
  11493. ArcRotateCamera.prototype.setTarget = function (target) {
  11494. this.target = target;
  11495. };
  11496. ArcRotateCamera.prototype._getViewMatrix = function () {
  11497. // Compute
  11498. var cosa = Math.cos(this.alpha);
  11499. var sina = Math.sin(this.alpha);
  11500. var cosb = Math.cos(this.beta);
  11501. var sinb = Math.sin(this.beta);
  11502. var target = this._getTargetPosition();
  11503. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11504. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11505. this._collider.radius = this.collisionRadius;
  11506. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11507. this._collisionTriggered = true;
  11508. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11509. }
  11510. else {
  11511. this.position.copyFrom(this._newPosition);
  11512. var up = this.upVector;
  11513. if (this.allowUpsideDown && this.beta < 0) {
  11514. var up = up.clone();
  11515. up = up.negate();
  11516. }
  11517. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11518. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11519. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11520. }
  11521. return this._viewMatrix;
  11522. };
  11523. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11524. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11525. meshes = meshes || this.getScene().meshes;
  11526. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11527. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11528. this.radius = distance * this.zoomOnFactor;
  11529. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11530. };
  11531. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11532. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11533. var meshesOrMinMaxVector;
  11534. var distance;
  11535. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11536. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11537. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11538. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11539. }
  11540. else {
  11541. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11542. distance = meshesOrMinMaxVectorAndDistance.distance;
  11543. }
  11544. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11545. if (!doNotUpdateMaxZ) {
  11546. this.maxZ = distance * 2;
  11547. }
  11548. };
  11549. /**
  11550. * @override
  11551. * Override Camera.createRigCamera
  11552. */
  11553. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11554. switch (this.cameraRigMode) {
  11555. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11559. case BABYLON.Camera.RIG_MODE_VR:
  11560. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11561. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11562. }
  11563. };
  11564. /**
  11565. * @override
  11566. * Override Camera._updateRigCameras
  11567. */
  11568. ArcRotateCamera.prototype._updateRigCameras = function () {
  11569. switch (this.cameraRigMode) {
  11570. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11571. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11572. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11573. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11574. case BABYLON.Camera.RIG_MODE_VR:
  11575. var camLeft = this._rigCameras[0];
  11576. var camRight = this._rigCameras[1];
  11577. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11578. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11579. camLeft.beta = camRight.beta = this.beta;
  11580. camLeft.radius = camRight.radius = this.radius;
  11581. break;
  11582. }
  11583. _super.prototype._updateRigCameras.call(this);
  11584. };
  11585. return ArcRotateCamera;
  11586. })(BABYLON.TargetCamera);
  11587. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11588. })(BABYLON || (BABYLON = {}));
  11589. var BABYLON;
  11590. (function (BABYLON) {
  11591. // We're mainly based on the logic defined into the FreeCamera code
  11592. var DeviceOrientationCamera = (function (_super) {
  11593. __extends(DeviceOrientationCamera, _super);
  11594. function DeviceOrientationCamera(name, position, scene) {
  11595. var _this = this;
  11596. _super.call(this, name, position, scene);
  11597. this._offsetX = null;
  11598. this._offsetY = null;
  11599. this._orientationGamma = 0;
  11600. this._orientationBeta = 0;
  11601. this._initialOrientationGamma = 0;
  11602. this._initialOrientationBeta = 0;
  11603. this.angularSensibility = 10000.0;
  11604. this.moveSensibility = 50.0;
  11605. window.addEventListener("resize", function () {
  11606. _this._initialOrientationGamma = null;
  11607. }, false);
  11608. }
  11609. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11610. var _this = this;
  11611. if (this._attachedCanvas) {
  11612. return;
  11613. }
  11614. this._attachedCanvas = canvas;
  11615. if (!this._orientationChanged) {
  11616. this._orientationChanged = function (evt) {
  11617. if (!_this._initialOrientationGamma) {
  11618. _this._initialOrientationGamma = evt.gamma;
  11619. _this._initialOrientationBeta = evt.beta;
  11620. }
  11621. _this._orientationGamma = evt.gamma;
  11622. _this._orientationBeta = evt.beta;
  11623. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11624. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11625. };
  11626. }
  11627. window.addEventListener("deviceorientation", this._orientationChanged);
  11628. };
  11629. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11630. if (this._attachedCanvas != canvas) {
  11631. return;
  11632. }
  11633. window.removeEventListener("deviceorientation", this._orientationChanged);
  11634. this._attachedCanvas = null;
  11635. this._orientationGamma = 0;
  11636. this._orientationBeta = 0;
  11637. this._initialOrientationGamma = 0;
  11638. this._initialOrientationBeta = 0;
  11639. };
  11640. DeviceOrientationCamera.prototype._checkInputs = function () {
  11641. if (!this._offsetX) {
  11642. return;
  11643. }
  11644. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11645. var speed = this._computeLocalCameraSpeed();
  11646. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11647. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11648. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11649. _super.prototype._checkInputs.call(this);
  11650. };
  11651. return DeviceOrientationCamera;
  11652. })(BABYLON.FreeCamera);
  11653. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11654. })(BABYLON || (BABYLON = {}));
  11655. var BABYLON;
  11656. (function (BABYLON) {
  11657. var Gamepads = (function () {
  11658. function Gamepads(ongamedpadconnected) {
  11659. var _this = this;
  11660. this.babylonGamepads = [];
  11661. this.oneGamepadConnected = false;
  11662. this.isMonitoring = false;
  11663. this.gamepadEventSupported = 'GamepadEvent' in window;
  11664. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11665. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11666. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  11667. this._callbackGamepadConnected = ongamedpadconnected;
  11668. if (this.gamepadSupportAvailable) {
  11669. // Checking if the gamepad connected event is supported (like in Firefox)
  11670. if (this.gamepadEventSupported) {
  11671. window.addEventListener('gamepadconnected', function (evt) {
  11672. _this._onGamepadConnected(evt);
  11673. }, false);
  11674. window.addEventListener('gamepaddisconnected', function (evt) {
  11675. _this._onGamepadDisconnected(evt);
  11676. }, false);
  11677. }
  11678. else {
  11679. this._startMonitoringGamepads();
  11680. }
  11681. if (!this.oneGamepadConnected) {
  11682. this._insertGamepadDOMInstructions();
  11683. }
  11684. }
  11685. else {
  11686. this._insertGamepadDOMNotSupported();
  11687. }
  11688. }
  11689. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11690. Gamepads.gamepadDOMInfo = document.createElement("div");
  11691. var buttonAImage = document.createElement("img");
  11692. buttonAImage.src = this.buttonADataURL;
  11693. var spanMessage = document.createElement("span");
  11694. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11695. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11696. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11697. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11698. Gamepads.gamepadDOMInfo.style.width = "100%";
  11699. Gamepads.gamepadDOMInfo.style.height = "48px";
  11700. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11701. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11702. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11703. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11704. buttonAImage.style.position = "relative";
  11705. buttonAImage.style.bottom = "8px";
  11706. spanMessage.style.position = "relative";
  11707. spanMessage.style.fontSize = "32px";
  11708. spanMessage.style.bottom = "32px";
  11709. spanMessage.style.color = "green";
  11710. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11711. };
  11712. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11713. Gamepads.gamepadDOMInfo = document.createElement("div");
  11714. var spanMessage = document.createElement("span");
  11715. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11716. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11717. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11718. Gamepads.gamepadDOMInfo.style.width = "100%";
  11719. Gamepads.gamepadDOMInfo.style.height = "40px";
  11720. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11721. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11722. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11723. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11724. spanMessage.style.position = "relative";
  11725. spanMessage.style.fontSize = "32px";
  11726. spanMessage.style.color = "red";
  11727. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11728. };
  11729. Gamepads.prototype.dispose = function () {
  11730. if (Gamepads.gamepadDOMInfo) {
  11731. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11732. }
  11733. };
  11734. Gamepads.prototype._onGamepadConnected = function (evt) {
  11735. var newGamepad = this._addNewGamepad(evt.gamepad);
  11736. if (this._callbackGamepadConnected)
  11737. this._callbackGamepadConnected(newGamepad);
  11738. this._startMonitoringGamepads();
  11739. };
  11740. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11741. if (!this.oneGamepadConnected) {
  11742. this.oneGamepadConnected = true;
  11743. if (Gamepads.gamepadDOMInfo) {
  11744. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11745. Gamepads.gamepadDOMInfo = null;
  11746. }
  11747. }
  11748. var newGamepad;
  11749. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11750. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11751. }
  11752. else {
  11753. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11754. }
  11755. this.babylonGamepads.push(newGamepad);
  11756. return newGamepad;
  11757. };
  11758. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11759. // Remove the gamepad from the list of gamepads to monitor.
  11760. for (var i in this.babylonGamepads) {
  11761. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11762. this.babylonGamepads.splice(i, 1);
  11763. break;
  11764. }
  11765. }
  11766. // If no gamepads are left, stop the polling loop.
  11767. if (this.babylonGamepads.length == 0) {
  11768. this._stopMonitoringGamepads();
  11769. }
  11770. };
  11771. Gamepads.prototype._startMonitoringGamepads = function () {
  11772. if (!this.isMonitoring) {
  11773. this.isMonitoring = true;
  11774. this._checkGamepadsStatus();
  11775. }
  11776. };
  11777. Gamepads.prototype._stopMonitoringGamepads = function () {
  11778. this.isMonitoring = false;
  11779. };
  11780. Gamepads.prototype._checkGamepadsStatus = function () {
  11781. var _this = this;
  11782. // updating gamepad objects
  11783. this._updateGamepadObjects();
  11784. for (var i in this.babylonGamepads) {
  11785. this.babylonGamepads[i].update();
  11786. }
  11787. if (this.isMonitoring) {
  11788. if (window.requestAnimationFrame) {
  11789. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11790. }
  11791. else if (window.mozRequestAnimationFrame) {
  11792. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11793. }
  11794. else if (window.webkitRequestAnimationFrame) {
  11795. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11796. }
  11797. }
  11798. };
  11799. // This function is called only on Chrome, which does not yet support
  11800. // connection/disconnection events, but requires you to monitor
  11801. // an array for changes.
  11802. Gamepads.prototype._updateGamepadObjects = function () {
  11803. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11804. for (var i = 0; i < gamepads.length; i++) {
  11805. if (gamepads[i]) {
  11806. if (!(gamepads[i].index in this.babylonGamepads)) {
  11807. var newGamepad = this._addNewGamepad(gamepads[i]);
  11808. if (this._callbackGamepadConnected) {
  11809. this._callbackGamepadConnected(newGamepad);
  11810. }
  11811. }
  11812. else {
  11813. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11814. }
  11815. }
  11816. }
  11817. };
  11818. return Gamepads;
  11819. })();
  11820. BABYLON.Gamepads = Gamepads;
  11821. var StickValues = (function () {
  11822. function StickValues(x, y) {
  11823. this.x = x;
  11824. this.y = y;
  11825. }
  11826. return StickValues;
  11827. })();
  11828. BABYLON.StickValues = StickValues;
  11829. var Gamepad = (function () {
  11830. function Gamepad(id, index, browserGamepad) {
  11831. this.id = id;
  11832. this.index = index;
  11833. this.browserGamepad = browserGamepad;
  11834. if (this.browserGamepad.axes.length >= 2) {
  11835. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11836. }
  11837. if (this.browserGamepad.axes.length >= 4) {
  11838. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11839. }
  11840. }
  11841. Gamepad.prototype.onleftstickchanged = function (callback) {
  11842. this._onleftstickchanged = callback;
  11843. };
  11844. Gamepad.prototype.onrightstickchanged = function (callback) {
  11845. this._onrightstickchanged = callback;
  11846. };
  11847. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11848. get: function () {
  11849. return this._leftStick;
  11850. },
  11851. set: function (newValues) {
  11852. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11853. this._onleftstickchanged(newValues);
  11854. }
  11855. this._leftStick = newValues;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11861. get: function () {
  11862. return this._rightStick;
  11863. },
  11864. set: function (newValues) {
  11865. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11866. this._onrightstickchanged(newValues);
  11867. }
  11868. this._rightStick = newValues;
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Gamepad.prototype.update = function () {
  11874. if (this._leftStick) {
  11875. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11876. }
  11877. if (this._rightStick) {
  11878. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11879. }
  11880. };
  11881. return Gamepad;
  11882. })();
  11883. BABYLON.Gamepad = Gamepad;
  11884. var GenericPad = (function (_super) {
  11885. __extends(GenericPad, _super);
  11886. function GenericPad(id, index, gamepad) {
  11887. _super.call(this, id, index, gamepad);
  11888. this.id = id;
  11889. this.index = index;
  11890. this.gamepad = gamepad;
  11891. this._buttons = new Array(gamepad.buttons.length);
  11892. }
  11893. GenericPad.prototype.onbuttondown = function (callback) {
  11894. this._onbuttondown = callback;
  11895. };
  11896. GenericPad.prototype.onbuttonup = function (callback) {
  11897. this._onbuttonup = callback;
  11898. };
  11899. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11900. if (newValue !== currentValue) {
  11901. if (this._onbuttondown && newValue === 1) {
  11902. this._onbuttondown(buttonIndex);
  11903. }
  11904. if (this._onbuttonup && newValue === 0) {
  11905. this._onbuttonup(buttonIndex);
  11906. }
  11907. }
  11908. return newValue;
  11909. };
  11910. GenericPad.prototype.update = function () {
  11911. _super.prototype.update.call(this);
  11912. for (var index = 0; index < this._buttons.length; index++) {
  11913. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11914. }
  11915. };
  11916. return GenericPad;
  11917. })(Gamepad);
  11918. BABYLON.GenericPad = GenericPad;
  11919. (function (Xbox360Button) {
  11920. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11921. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11922. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11923. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11924. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11925. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11926. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11927. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11928. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11929. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11930. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11931. var Xbox360Button = BABYLON.Xbox360Button;
  11932. (function (Xbox360Dpad) {
  11933. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11934. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11935. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11936. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11937. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11938. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11939. var Xbox360Pad = (function (_super) {
  11940. __extends(Xbox360Pad, _super);
  11941. function Xbox360Pad() {
  11942. _super.apply(this, arguments);
  11943. this._leftTrigger = 0;
  11944. this._rightTrigger = 0;
  11945. this._buttonA = 0;
  11946. this._buttonB = 0;
  11947. this._buttonX = 0;
  11948. this._buttonY = 0;
  11949. this._buttonBack = 0;
  11950. this._buttonStart = 0;
  11951. this._buttonLB = 0;
  11952. this._buttonRB = 0;
  11953. this._buttonLeftStick = 0;
  11954. this._buttonRightStick = 0;
  11955. this._dPadUp = 0;
  11956. this._dPadDown = 0;
  11957. this._dPadLeft = 0;
  11958. this._dPadRight = 0;
  11959. }
  11960. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11961. this._onlefttriggerchanged = callback;
  11962. };
  11963. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11964. this._onrighttriggerchanged = callback;
  11965. };
  11966. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11967. get: function () {
  11968. return this._leftTrigger;
  11969. },
  11970. set: function (newValue) {
  11971. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11972. this._onlefttriggerchanged(newValue);
  11973. }
  11974. this._leftTrigger = newValue;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11980. get: function () {
  11981. return this._rightTrigger;
  11982. },
  11983. set: function (newValue) {
  11984. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11985. this._onrighttriggerchanged(newValue);
  11986. }
  11987. this._rightTrigger = newValue;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11993. this._onbuttondown = callback;
  11994. };
  11995. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11996. this._onbuttonup = callback;
  11997. };
  11998. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11999. this._ondpaddown = callback;
  12000. };
  12001. Xbox360Pad.prototype.ondpadup = function (callback) {
  12002. this._ondpadup = callback;
  12003. };
  12004. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  12005. if (newValue !== currentValue) {
  12006. if (this._onbuttondown && newValue === 1) {
  12007. this._onbuttondown(buttonType);
  12008. }
  12009. if (this._onbuttonup && newValue === 0) {
  12010. this._onbuttonup(buttonType);
  12011. }
  12012. }
  12013. return newValue;
  12014. };
  12015. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  12016. if (newValue !== currentValue) {
  12017. if (this._ondpaddown && newValue === 1) {
  12018. this._ondpaddown(buttonType);
  12019. }
  12020. if (this._ondpadup && newValue === 0) {
  12021. this._ondpadup(buttonType);
  12022. }
  12023. }
  12024. return newValue;
  12025. };
  12026. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  12027. get: function () {
  12028. return this._buttonA;
  12029. },
  12030. set: function (value) {
  12031. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  12037. get: function () {
  12038. return this._buttonB;
  12039. },
  12040. set: function (value) {
  12041. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  12047. get: function () {
  12048. return this._buttonX;
  12049. },
  12050. set: function (value) {
  12051. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  12057. get: function () {
  12058. return this._buttonY;
  12059. },
  12060. set: function (value) {
  12061. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  12062. },
  12063. enumerable: true,
  12064. configurable: true
  12065. });
  12066. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  12067. get: function () {
  12068. return this._buttonStart;
  12069. },
  12070. set: function (value) {
  12071. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12077. get: function () {
  12078. return this._buttonBack;
  12079. },
  12080. set: function (value) {
  12081. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12087. get: function () {
  12088. return this._buttonLB;
  12089. },
  12090. set: function (value) {
  12091. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12097. get: function () {
  12098. return this._buttonRB;
  12099. },
  12100. set: function (value) {
  12101. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12107. get: function () {
  12108. return this._buttonLeftStick;
  12109. },
  12110. set: function (value) {
  12111. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12117. get: function () {
  12118. return this._buttonRightStick;
  12119. },
  12120. set: function (value) {
  12121. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12127. get: function () {
  12128. return this._dPadUp;
  12129. },
  12130. set: function (value) {
  12131. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12137. get: function () {
  12138. return this._dPadDown;
  12139. },
  12140. set: function (value) {
  12141. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12147. get: function () {
  12148. return this._dPadLeft;
  12149. },
  12150. set: function (value) {
  12151. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12157. get: function () {
  12158. return this._dPadRight;
  12159. },
  12160. set: function (value) {
  12161. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12162. },
  12163. enumerable: true,
  12164. configurable: true
  12165. });
  12166. Xbox360Pad.prototype.update = function () {
  12167. _super.prototype.update.call(this);
  12168. this.buttonA = this.browserGamepad.buttons[0].value;
  12169. this.buttonB = this.browserGamepad.buttons[1].value;
  12170. this.buttonX = this.browserGamepad.buttons[2].value;
  12171. this.buttonY = this.browserGamepad.buttons[3].value;
  12172. this.buttonLB = this.browserGamepad.buttons[4].value;
  12173. this.buttonRB = this.browserGamepad.buttons[5].value;
  12174. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12175. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12176. this.buttonBack = this.browserGamepad.buttons[8].value;
  12177. this.buttonStart = this.browserGamepad.buttons[9].value;
  12178. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12179. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12180. this.dPadUp = this.browserGamepad.buttons[12].value;
  12181. this.dPadDown = this.browserGamepad.buttons[13].value;
  12182. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12183. this.dPadRight = this.browserGamepad.buttons[15].value;
  12184. };
  12185. return Xbox360Pad;
  12186. })(Gamepad);
  12187. BABYLON.Xbox360Pad = Xbox360Pad;
  12188. })(BABYLON || (BABYLON = {}));
  12189. var BABYLON;
  12190. (function (BABYLON) {
  12191. // We're mainly based on the logic defined into the FreeCamera code
  12192. var GamepadCamera = (function (_super) {
  12193. __extends(GamepadCamera, _super);
  12194. function GamepadCamera(name, position, scene) {
  12195. var _this = this;
  12196. _super.call(this, name, position, scene);
  12197. this.angularSensibility = 200;
  12198. this.moveSensibility = 75;
  12199. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12200. }
  12201. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12202. // Only the first gamepad can control the camera
  12203. if (gamepad.index === 0) {
  12204. this._gamepad = gamepad;
  12205. }
  12206. };
  12207. GamepadCamera.prototype._checkInputs = function () {
  12208. if (this._gamepad) {
  12209. var LSValues = this._gamepad.leftStick;
  12210. var normalizedLX = LSValues.x / this.moveSensibility;
  12211. var normalizedLY = LSValues.y / this.moveSensibility;
  12212. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12213. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12214. var RSValues = this._gamepad.rightStick;
  12215. var normalizedRX = RSValues.x / this.angularSensibility;
  12216. var normalizedRY = RSValues.y / this.angularSensibility;
  12217. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12218. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12219. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12220. var speed = this._computeLocalCameraSpeed() * 50.0;
  12221. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12222. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12223. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12224. }
  12225. _super.prototype._checkInputs.call(this);
  12226. };
  12227. GamepadCamera.prototype.dispose = function () {
  12228. this._gamepads.dispose();
  12229. _super.prototype.dispose.call(this);
  12230. };
  12231. return GamepadCamera;
  12232. })(BABYLON.FreeCamera);
  12233. BABYLON.GamepadCamera = GamepadCamera;
  12234. })(BABYLON || (BABYLON = {}));
  12235. var BABYLON;
  12236. (function (BABYLON) {
  12237. var RenderingManager = (function () {
  12238. function RenderingManager(scene) {
  12239. this._renderingGroups = new Array();
  12240. this._scene = scene;
  12241. }
  12242. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12243. if (this._scene._activeParticleSystems.length === 0) {
  12244. return;
  12245. }
  12246. // Particles
  12247. var activeCamera = this._scene.activeCamera;
  12248. var beforeParticlesDate = BABYLON.Tools.Now;
  12249. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12250. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12251. if (particleSystem.renderingGroupId !== index) {
  12252. continue;
  12253. }
  12254. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12255. continue;
  12256. }
  12257. this._clearDepthBuffer();
  12258. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12259. this._scene._activeParticles += particleSystem.render();
  12260. }
  12261. }
  12262. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12263. };
  12264. RenderingManager.prototype._renderSprites = function (index) {
  12265. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12266. return;
  12267. }
  12268. // Sprites
  12269. var activeCamera = this._scene.activeCamera;
  12270. var beforeSpritessDate = BABYLON.Tools.Now;
  12271. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12272. var spriteManager = this._scene.spriteManagers[id];
  12273. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12274. this._clearDepthBuffer();
  12275. spriteManager.render();
  12276. }
  12277. }
  12278. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12279. };
  12280. RenderingManager.prototype._clearDepthBuffer = function () {
  12281. if (this._depthBufferAlreadyCleaned) {
  12282. return;
  12283. }
  12284. this._scene.getEngine().clear(0, false, true);
  12285. this._depthBufferAlreadyCleaned = true;
  12286. };
  12287. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12288. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12289. this._depthBufferAlreadyCleaned = false;
  12290. var renderingGroup = this._renderingGroups[index];
  12291. var needToStepBack = false;
  12292. if (renderingGroup) {
  12293. this._clearDepthBuffer();
  12294. if (!renderingGroup.render(customRenderFunction)) {
  12295. this._renderingGroups.splice(index, 1);
  12296. needToStepBack = true;
  12297. }
  12298. }
  12299. if (renderSprites) {
  12300. this._renderSprites(index);
  12301. }
  12302. if (renderParticles) {
  12303. this._renderParticles(index, activeMeshes);
  12304. }
  12305. if (needToStepBack) {
  12306. index--;
  12307. }
  12308. }
  12309. };
  12310. RenderingManager.prototype.reset = function () {
  12311. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12312. if (renderingGroup) {
  12313. renderingGroup.prepare();
  12314. }
  12315. });
  12316. };
  12317. RenderingManager.prototype.dispatch = function (subMesh) {
  12318. var mesh = subMesh.getMesh();
  12319. var renderingGroupId = mesh.renderingGroupId || 0;
  12320. if (!this._renderingGroups[renderingGroupId]) {
  12321. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12322. }
  12323. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12324. };
  12325. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12326. return RenderingManager;
  12327. })();
  12328. BABYLON.RenderingManager = RenderingManager;
  12329. })(BABYLON || (BABYLON = {}));
  12330. var BABYLON;
  12331. (function (BABYLON) {
  12332. var RenderingGroup = (function () {
  12333. function RenderingGroup(index, scene) {
  12334. this.index = index;
  12335. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12336. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12337. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12338. this._scene = scene;
  12339. }
  12340. RenderingGroup.prototype.render = function (customRenderFunction) {
  12341. if (customRenderFunction) {
  12342. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12343. return true;
  12344. }
  12345. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12346. return false;
  12347. }
  12348. var engine = this._scene.getEngine();
  12349. // Opaque
  12350. var subIndex;
  12351. var submesh;
  12352. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12353. submesh = this._opaqueSubMeshes.data[subIndex];
  12354. submesh.render(false);
  12355. }
  12356. // Alpha test
  12357. engine.setAlphaTesting(true);
  12358. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12359. submesh = this._alphaTestSubMeshes.data[subIndex];
  12360. submesh.render(false);
  12361. }
  12362. engine.setAlphaTesting(false);
  12363. // Transparent
  12364. if (this._transparentSubMeshes.length) {
  12365. // Sorting
  12366. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12367. submesh = this._transparentSubMeshes.data[subIndex];
  12368. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12369. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12370. }
  12371. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12372. sortedArray.sort(function (a, b) {
  12373. // Alpha index first
  12374. if (a._alphaIndex > b._alphaIndex) {
  12375. return 1;
  12376. }
  12377. if (a._alphaIndex < b._alphaIndex) {
  12378. return -1;
  12379. }
  12380. // Then distance to camera
  12381. if (a._distanceToCamera < b._distanceToCamera) {
  12382. return 1;
  12383. }
  12384. if (a._distanceToCamera > b._distanceToCamera) {
  12385. return -1;
  12386. }
  12387. return 0;
  12388. });
  12389. // Rendering
  12390. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12391. submesh = sortedArray[subIndex];
  12392. submesh.render(true);
  12393. }
  12394. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12395. }
  12396. return true;
  12397. };
  12398. RenderingGroup.prototype.prepare = function () {
  12399. this._opaqueSubMeshes.reset();
  12400. this._transparentSubMeshes.reset();
  12401. this._alphaTestSubMeshes.reset();
  12402. };
  12403. RenderingGroup.prototype.dispatch = function (subMesh) {
  12404. var material = subMesh.getMaterial();
  12405. var mesh = subMesh.getMesh();
  12406. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12407. this._transparentSubMeshes.push(subMesh);
  12408. }
  12409. else if (material.needAlphaTesting()) {
  12410. this._alphaTestSubMeshes.push(subMesh);
  12411. }
  12412. else {
  12413. this._opaqueSubMeshes.push(subMesh); // Opaque
  12414. }
  12415. };
  12416. return RenderingGroup;
  12417. })();
  12418. BABYLON.RenderingGroup = RenderingGroup;
  12419. })(BABYLON || (BABYLON = {}));
  12420. var BABYLON;
  12421. (function (BABYLON) {
  12422. /**
  12423. * Represents a scene to be rendered by the engine.
  12424. * @see http://doc.babylonjs.com/page.php?p=21911
  12425. */
  12426. var Scene = (function () {
  12427. /**
  12428. * @constructor
  12429. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12430. */
  12431. function Scene(engine) {
  12432. // Members
  12433. this.autoClear = true;
  12434. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12435. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12436. this.forceWireframe = false;
  12437. this.forcePointsCloud = false;
  12438. this.forceShowBoundingBoxes = false;
  12439. this.animationsEnabled = true;
  12440. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12441. // Fog
  12442. /**
  12443. * is fog enabled on this scene.
  12444. * @type {boolean}
  12445. */
  12446. this.fogEnabled = true;
  12447. this.fogMode = Scene.FOGMODE_NONE;
  12448. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12449. this.fogDensity = 0.1;
  12450. this.fogStart = 0;
  12451. this.fogEnd = 1000.0;
  12452. // Lights
  12453. /**
  12454. * is shadow enabled on this scene.
  12455. * @type {boolean}
  12456. */
  12457. this.shadowsEnabled = true;
  12458. /**
  12459. * is light enabled on this scene.
  12460. * @type {boolean}
  12461. */
  12462. this.lightsEnabled = true;
  12463. /**
  12464. * All of the lights added to this scene.
  12465. * @see BABYLON.Light
  12466. * @type {BABYLON.Light[]}
  12467. */
  12468. this.lights = new Array();
  12469. // Cameras
  12470. /**
  12471. * All of the cameras added to this scene.
  12472. * @see BABYLON.Camera
  12473. * @type {BABYLON.Camera[]}
  12474. */
  12475. this.cameras = new Array();
  12476. this.activeCameras = new Array();
  12477. // Meshes
  12478. /**
  12479. * All of the (abstract) meshes added to this scene.
  12480. * @see BABYLON.AbstractMesh
  12481. * @type {BABYLON.AbstractMesh[]}
  12482. */
  12483. this.meshes = new Array();
  12484. // Geometries
  12485. this._geometries = new Array();
  12486. this.materials = new Array();
  12487. this.multiMaterials = new Array();
  12488. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12489. // Textures
  12490. this.texturesEnabled = true;
  12491. this.textures = new Array();
  12492. // Particles
  12493. this.particlesEnabled = true;
  12494. this.particleSystems = new Array();
  12495. // Sprites
  12496. this.spritesEnabled = true;
  12497. this.spriteManagers = new Array();
  12498. // Layers
  12499. this.layers = new Array();
  12500. // Skeletons
  12501. this.skeletonsEnabled = true;
  12502. this.skeletons = new Array();
  12503. // Lens flares
  12504. this.lensFlaresEnabled = true;
  12505. this.lensFlareSystems = new Array();
  12506. // Collisions
  12507. this.collisionsEnabled = true;
  12508. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12509. // Postprocesses
  12510. this.postProcessesEnabled = true;
  12511. // Customs render targets
  12512. this.renderTargetsEnabled = true;
  12513. this.dumpNextRenderTargets = false;
  12514. this.customRenderTargets = new Array();
  12515. // Imported meshes
  12516. this.importedMeshesFiles = new Array();
  12517. // Probes
  12518. this.probesEnabled = true;
  12519. this.reflectionProbes = new Array();
  12520. this._actionManagers = new Array();
  12521. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12522. // Procedural textures
  12523. this.proceduralTexturesEnabled = true;
  12524. this._proceduralTextures = new Array();
  12525. this.soundTracks = new Array();
  12526. this._audioEnabled = true;
  12527. this._headphone = false;
  12528. this._totalVertices = 0;
  12529. this._activeIndices = 0;
  12530. this._activeParticles = 0;
  12531. this._lastFrameDuration = 0;
  12532. this._evaluateActiveMeshesDuration = 0;
  12533. this._renderTargetsDuration = 0;
  12534. this._particlesDuration = 0;
  12535. this._renderDuration = 0;
  12536. this._spritesDuration = 0;
  12537. this._animationRatio = 0;
  12538. this._renderId = 0;
  12539. this._executeWhenReadyTimeoutId = -1;
  12540. this._toBeDisposed = new BABYLON.SmartArray(256);
  12541. this._onReadyCallbacks = new Array();
  12542. this._pendingData = []; //ANY
  12543. this._onBeforeRenderCallbacks = new Array();
  12544. this._onAfterRenderCallbacks = new Array();
  12545. this._activeMeshes = new BABYLON.SmartArray(256);
  12546. this._processedMaterials = new BABYLON.SmartArray(256);
  12547. this._renderTargets = new BABYLON.SmartArray(256);
  12548. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12549. this._activeSkeletons = new BABYLON.SmartArray(32);
  12550. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12551. this._activeBones = 0;
  12552. this._activeAnimatables = new Array();
  12553. this._transformMatrix = BABYLON.Matrix.Zero();
  12554. this._edgesRenderers = new BABYLON.SmartArray(16);
  12555. this._uniqueIdCounter = 0;
  12556. this._engine = engine;
  12557. engine.scenes.push(this);
  12558. this._renderingManager = new BABYLON.RenderingManager(this);
  12559. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12560. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12561. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12562. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12563. this.attachControl();
  12564. this._debugLayer = new BABYLON.DebugLayer(this);
  12565. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12566. //simplification queue
  12567. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12568. //collision coordinator initialization. For now legacy per default.
  12569. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12570. }
  12571. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12572. get: function () {
  12573. return Scene._FOGMODE_NONE;
  12574. },
  12575. enumerable: true,
  12576. configurable: true
  12577. });
  12578. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12579. get: function () {
  12580. return Scene._FOGMODE_EXP;
  12581. },
  12582. enumerable: true,
  12583. configurable: true
  12584. });
  12585. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12586. get: function () {
  12587. return Scene._FOGMODE_EXP2;
  12588. },
  12589. enumerable: true,
  12590. configurable: true
  12591. });
  12592. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12593. get: function () {
  12594. return Scene._FOGMODE_LINEAR;
  12595. },
  12596. enumerable: true,
  12597. configurable: true
  12598. });
  12599. Object.defineProperty(Scene.prototype, "debugLayer", {
  12600. // Properties
  12601. get: function () {
  12602. return this._debugLayer;
  12603. },
  12604. enumerable: true,
  12605. configurable: true
  12606. });
  12607. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12608. get: function () {
  12609. return this._workerCollisions;
  12610. },
  12611. set: function (enabled) {
  12612. enabled = (enabled && !!Worker);
  12613. this._workerCollisions = enabled;
  12614. if (this.collisionCoordinator) {
  12615. this.collisionCoordinator.destroy();
  12616. }
  12617. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12618. this.collisionCoordinator.init(this);
  12619. },
  12620. enumerable: true,
  12621. configurable: true
  12622. });
  12623. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12624. get: function () {
  12625. return this._selectionOctree;
  12626. },
  12627. enumerable: true,
  12628. configurable: true
  12629. });
  12630. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12631. /**
  12632. * The mesh that is currently under the pointer.
  12633. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12634. */
  12635. get: function () {
  12636. return this._meshUnderPointer;
  12637. },
  12638. enumerable: true,
  12639. configurable: true
  12640. });
  12641. Object.defineProperty(Scene.prototype, "pointerX", {
  12642. /**
  12643. * Current on-screen X position of the pointer
  12644. * @return {number} X position of the pointer
  12645. */
  12646. get: function () {
  12647. return this._pointerX;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(Scene.prototype, "pointerY", {
  12653. /**
  12654. * Current on-screen Y position of the pointer
  12655. * @return {number} Y position of the pointer
  12656. */
  12657. get: function () {
  12658. return this._pointerY;
  12659. },
  12660. enumerable: true,
  12661. configurable: true
  12662. });
  12663. Scene.prototype.getCachedMaterial = function () {
  12664. return this._cachedMaterial;
  12665. };
  12666. Scene.prototype.getBoundingBoxRenderer = function () {
  12667. return this._boundingBoxRenderer;
  12668. };
  12669. Scene.prototype.getOutlineRenderer = function () {
  12670. return this._outlineRenderer;
  12671. };
  12672. Scene.prototype.getEngine = function () {
  12673. return this._engine;
  12674. };
  12675. Scene.prototype.getTotalVertices = function () {
  12676. return this._totalVertices;
  12677. };
  12678. Scene.prototype.getActiveIndices = function () {
  12679. return this._activeIndices;
  12680. };
  12681. Scene.prototype.getActiveParticles = function () {
  12682. return this._activeParticles;
  12683. };
  12684. Scene.prototype.getActiveBones = function () {
  12685. return this._activeBones;
  12686. };
  12687. // Stats
  12688. Scene.prototype.getLastFrameDuration = function () {
  12689. return this._lastFrameDuration;
  12690. };
  12691. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12692. return this._evaluateActiveMeshesDuration;
  12693. };
  12694. Scene.prototype.getActiveMeshes = function () {
  12695. return this._activeMeshes;
  12696. };
  12697. Scene.prototype.getRenderTargetsDuration = function () {
  12698. return this._renderTargetsDuration;
  12699. };
  12700. Scene.prototype.getRenderDuration = function () {
  12701. return this._renderDuration;
  12702. };
  12703. Scene.prototype.getParticlesDuration = function () {
  12704. return this._particlesDuration;
  12705. };
  12706. Scene.prototype.getSpritesDuration = function () {
  12707. return this._spritesDuration;
  12708. };
  12709. Scene.prototype.getAnimationRatio = function () {
  12710. return this._animationRatio;
  12711. };
  12712. Scene.prototype.getRenderId = function () {
  12713. return this._renderId;
  12714. };
  12715. Scene.prototype.incrementRenderId = function () {
  12716. this._renderId++;
  12717. };
  12718. Scene.prototype._updatePointerPosition = function (evt) {
  12719. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12720. this._pointerX = evt.clientX - canvasRect.left;
  12721. this._pointerY = evt.clientY - canvasRect.top;
  12722. if (this.cameraToUseForPointers) {
  12723. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12724. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12725. }
  12726. };
  12727. // Pointers handling
  12728. Scene.prototype.attachControl = function () {
  12729. var _this = this;
  12730. this._onPointerMove = function (evt) {
  12731. var canvas = _this._engine.getRenderingCanvas();
  12732. _this._updatePointerPosition(evt);
  12733. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12734. if (pickResult.hit) {
  12735. _this._meshUnderPointer = pickResult.pickedMesh;
  12736. _this.setPointerOverMesh(pickResult.pickedMesh);
  12737. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12738. canvas.style.cursor = "pointer";
  12739. }
  12740. else {
  12741. canvas.style.cursor = "";
  12742. }
  12743. }
  12744. else {
  12745. _this.setPointerOverMesh(null);
  12746. canvas.style.cursor = "";
  12747. _this._meshUnderPointer = null;
  12748. }
  12749. };
  12750. this._onPointerDown = function (evt) {
  12751. var predicate = null;
  12752. if (!_this.onPointerDown) {
  12753. predicate = function (mesh) {
  12754. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12755. };
  12756. }
  12757. _this._updatePointerPosition(evt);
  12758. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12759. if (pickResult.hit) {
  12760. if (pickResult.pickedMesh.actionManager) {
  12761. switch (evt.button) {
  12762. case 0:
  12763. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12764. break;
  12765. case 1:
  12766. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12767. break;
  12768. case 2:
  12769. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12770. break;
  12771. }
  12772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12773. }
  12774. }
  12775. if (_this.onPointerDown) {
  12776. _this.onPointerDown(evt, pickResult);
  12777. }
  12778. };
  12779. this._onPointerUp = function (evt) {
  12780. var predicate = null;
  12781. if (!_this.onPointerUp) {
  12782. predicate = function (mesh) {
  12783. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12784. };
  12785. }
  12786. _this._updatePointerPosition(evt);
  12787. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12788. if (pickResult.hit) {
  12789. if (pickResult.pickedMesh.actionManager) {
  12790. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12791. }
  12792. }
  12793. if (_this.onPointerUp) {
  12794. _this.onPointerUp(evt, pickResult);
  12795. }
  12796. };
  12797. this._onKeyDown = function (evt) {
  12798. if (_this.actionManager) {
  12799. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12800. }
  12801. };
  12802. this._onKeyUp = function (evt) {
  12803. if (_this.actionManager) {
  12804. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12805. }
  12806. };
  12807. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12808. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12809. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12810. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12811. // Wheel
  12812. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12813. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12814. BABYLON.Tools.RegisterTopRootEvents([
  12815. { name: "keydown", handler: this._onKeyDown },
  12816. { name: "keyup", handler: this._onKeyUp }
  12817. ]);
  12818. };
  12819. Scene.prototype.detachControl = function () {
  12820. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12821. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12822. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12823. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12824. // Wheel
  12825. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12826. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12827. BABYLON.Tools.UnregisterTopRootEvents([
  12828. { name: "keydown", handler: this._onKeyDown },
  12829. { name: "keyup", handler: this._onKeyUp }
  12830. ]);
  12831. };
  12832. // Ready
  12833. Scene.prototype.isReady = function () {
  12834. if (this._pendingData.length > 0) {
  12835. return false;
  12836. }
  12837. var index;
  12838. for (index = 0; index < this._geometries.length; index++) {
  12839. var geometry = this._geometries[index];
  12840. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12841. return false;
  12842. }
  12843. }
  12844. for (index = 0; index < this.meshes.length; index++) {
  12845. var mesh = this.meshes[index];
  12846. if (!mesh.isReady()) {
  12847. return false;
  12848. }
  12849. var mat = mesh.material;
  12850. if (mat) {
  12851. if (!mat.isReady(mesh)) {
  12852. return false;
  12853. }
  12854. }
  12855. }
  12856. return true;
  12857. };
  12858. Scene.prototype.resetCachedMaterial = function () {
  12859. this._cachedMaterial = null;
  12860. };
  12861. Scene.prototype.registerBeforeRender = function (func) {
  12862. this._onBeforeRenderCallbacks.push(func);
  12863. };
  12864. Scene.prototype.unregisterBeforeRender = function (func) {
  12865. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12866. if (index > -1) {
  12867. this._onBeforeRenderCallbacks.splice(index, 1);
  12868. }
  12869. };
  12870. Scene.prototype.registerAfterRender = function (func) {
  12871. this._onAfterRenderCallbacks.push(func);
  12872. };
  12873. Scene.prototype.unregisterAfterRender = function (func) {
  12874. var index = this._onAfterRenderCallbacks.indexOf(func);
  12875. if (index > -1) {
  12876. this._onAfterRenderCallbacks.splice(index, 1);
  12877. }
  12878. };
  12879. Scene.prototype._addPendingData = function (data) {
  12880. this._pendingData.push(data);
  12881. };
  12882. Scene.prototype._removePendingData = function (data) {
  12883. var index = this._pendingData.indexOf(data);
  12884. if (index !== -1) {
  12885. this._pendingData.splice(index, 1);
  12886. }
  12887. };
  12888. Scene.prototype.getWaitingItemsCount = function () {
  12889. return this._pendingData.length;
  12890. };
  12891. /**
  12892. * Registers a function to be executed when the scene is ready.
  12893. * @param {Function} func - the function to be executed.
  12894. */
  12895. Scene.prototype.executeWhenReady = function (func) {
  12896. var _this = this;
  12897. this._onReadyCallbacks.push(func);
  12898. if (this._executeWhenReadyTimeoutId !== -1) {
  12899. return;
  12900. }
  12901. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12902. _this._checkIsReady();
  12903. }, 150);
  12904. };
  12905. Scene.prototype._checkIsReady = function () {
  12906. var _this = this;
  12907. if (this.isReady()) {
  12908. this._onReadyCallbacks.forEach(function (func) {
  12909. func();
  12910. });
  12911. this._onReadyCallbacks = [];
  12912. this._executeWhenReadyTimeoutId = -1;
  12913. return;
  12914. }
  12915. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12916. _this._checkIsReady();
  12917. }, 150);
  12918. };
  12919. // Animations
  12920. /**
  12921. * Will start the animation sequence of a given target
  12922. * @param target - the target
  12923. * @param {number} from - from which frame should animation start
  12924. * @param {number} to - till which frame should animation run.
  12925. * @param {boolean} [loop] - should the animation loop
  12926. * @param {number} [speedRatio] - the speed in which to run the animation
  12927. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12928. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12929. * @return {BABYLON.Animatable} the animatable object created for this animation
  12930. * @see BABYLON.Animatable
  12931. * @see http://doc.babylonjs.com/page.php?p=22081
  12932. */
  12933. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12934. if (speedRatio === void 0) { speedRatio = 1.0; }
  12935. this.stopAnimation(target);
  12936. if (!animatable) {
  12937. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12938. }
  12939. // Local animations
  12940. if (target.animations) {
  12941. animatable.appendAnimations(target, target.animations);
  12942. }
  12943. // Children animations
  12944. if (target.getAnimatables) {
  12945. var animatables = target.getAnimatables();
  12946. for (var index = 0; index < animatables.length; index++) {
  12947. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12948. }
  12949. }
  12950. return animatable;
  12951. };
  12952. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12953. if (speedRatio === undefined) {
  12954. speedRatio = 1.0;
  12955. }
  12956. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12957. return animatable;
  12958. };
  12959. Scene.prototype.getAnimatableByTarget = function (target) {
  12960. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12961. if (this._activeAnimatables[index].target === target) {
  12962. return this._activeAnimatables[index];
  12963. }
  12964. }
  12965. return null;
  12966. };
  12967. /**
  12968. * Will stop the animation of the given target
  12969. * @param target - the target
  12970. * @see beginAnimation
  12971. */
  12972. Scene.prototype.stopAnimation = function (target) {
  12973. var animatable = this.getAnimatableByTarget(target);
  12974. if (animatable) {
  12975. animatable.stop();
  12976. }
  12977. };
  12978. Scene.prototype._animate = function () {
  12979. if (!this.animationsEnabled) {
  12980. return;
  12981. }
  12982. if (!this._animationStartDate) {
  12983. this._animationStartDate = BABYLON.Tools.Now;
  12984. }
  12985. // Getting time
  12986. var now = BABYLON.Tools.Now;
  12987. var delay = now - this._animationStartDate;
  12988. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12989. this._activeAnimatables[index]._animate(delay);
  12990. }
  12991. };
  12992. // Matrix
  12993. Scene.prototype.getViewMatrix = function () {
  12994. return this._viewMatrix;
  12995. };
  12996. Scene.prototype.getProjectionMatrix = function () {
  12997. return this._projectionMatrix;
  12998. };
  12999. Scene.prototype.getTransformMatrix = function () {
  13000. return this._transformMatrix;
  13001. };
  13002. Scene.prototype.setTransformMatrix = function (view, projection) {
  13003. this._viewMatrix = view;
  13004. this._projectionMatrix = projection;
  13005. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13006. };
  13007. // Methods
  13008. Scene.prototype.addMesh = function (newMesh) {
  13009. newMesh.uniqueId = this._uniqueIdCounter++;
  13010. var position = this.meshes.push(newMesh);
  13011. //notify the collision coordinator
  13012. this.collisionCoordinator.onMeshAdded(newMesh);
  13013. if (this.onNewMeshAdded) {
  13014. this.onNewMeshAdded(newMesh, position, this);
  13015. }
  13016. };
  13017. Scene.prototype.removeMesh = function (toRemove) {
  13018. var index = this.meshes.indexOf(toRemove);
  13019. if (index !== -1) {
  13020. // Remove from the scene if mesh found
  13021. this.meshes.splice(index, 1);
  13022. }
  13023. //notify the collision coordinator
  13024. this.collisionCoordinator.onMeshRemoved(toRemove);
  13025. if (this.onMeshRemoved) {
  13026. this.onMeshRemoved(toRemove);
  13027. }
  13028. return index;
  13029. };
  13030. Scene.prototype.removeLight = function (toRemove) {
  13031. var index = this.lights.indexOf(toRemove);
  13032. if (index !== -1) {
  13033. // Remove from the scene if mesh found
  13034. this.lights.splice(index, 1);
  13035. }
  13036. if (this.onLightRemoved) {
  13037. this.onLightRemoved(toRemove);
  13038. }
  13039. return index;
  13040. };
  13041. Scene.prototype.removeCamera = function (toRemove) {
  13042. var index = this.cameras.indexOf(toRemove);
  13043. if (index !== -1) {
  13044. // Remove from the scene if mesh found
  13045. this.cameras.splice(index, 1);
  13046. }
  13047. // Remove from activeCameras
  13048. var index2 = this.activeCameras.indexOf(toRemove);
  13049. if (index2 !== -1) {
  13050. // Remove from the scene if mesh found
  13051. this.activeCameras.splice(index2, 1);
  13052. }
  13053. // Reset the activeCamera
  13054. if (this.activeCamera === toRemove) {
  13055. if (this.cameras.length > 0) {
  13056. this.activeCamera = this.cameras[0];
  13057. }
  13058. else {
  13059. this.activeCamera = null;
  13060. }
  13061. }
  13062. if (this.onCameraRemoved) {
  13063. this.onCameraRemoved(toRemove);
  13064. }
  13065. return index;
  13066. };
  13067. Scene.prototype.addLight = function (newLight) {
  13068. newLight.uniqueId = this._uniqueIdCounter++;
  13069. var position = this.lights.push(newLight);
  13070. if (this.onNewLightAdded) {
  13071. this.onNewLightAdded(newLight, position, this);
  13072. }
  13073. };
  13074. Scene.prototype.addCamera = function (newCamera) {
  13075. newCamera.uniqueId = this._uniqueIdCounter++;
  13076. var position = this.cameras.push(newCamera);
  13077. if (this.onNewCameraAdded) {
  13078. this.onNewCameraAdded(newCamera, position, this);
  13079. }
  13080. };
  13081. /**
  13082. * sets the active camera of the scene using its ID
  13083. * @param {string} id - the camera's ID
  13084. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13085. * @see activeCamera
  13086. */
  13087. Scene.prototype.setActiveCameraByID = function (id) {
  13088. var camera = this.getCameraByID(id);
  13089. if (camera) {
  13090. this.activeCamera = camera;
  13091. return camera;
  13092. }
  13093. return null;
  13094. };
  13095. /**
  13096. * sets the active camera of the scene using its name
  13097. * @param {string} name - the camera's name
  13098. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13099. * @see activeCamera
  13100. */
  13101. Scene.prototype.setActiveCameraByName = function (name) {
  13102. var camera = this.getCameraByName(name);
  13103. if (camera) {
  13104. this.activeCamera = camera;
  13105. return camera;
  13106. }
  13107. return null;
  13108. };
  13109. /**
  13110. * get a material using its id
  13111. * @param {string} the material's ID
  13112. * @return {BABYLON.Material|null} the material or null if none found.
  13113. */
  13114. Scene.prototype.getMaterialByID = function (id) {
  13115. for (var index = 0; index < this.materials.length; index++) {
  13116. if (this.materials[index].id === id) {
  13117. return this.materials[index];
  13118. }
  13119. }
  13120. return null;
  13121. };
  13122. /**
  13123. * get a material using its name
  13124. * @param {string} the material's name
  13125. * @return {BABYLON.Material|null} the material or null if none found.
  13126. */
  13127. Scene.prototype.getMaterialByName = function (name) {
  13128. for (var index = 0; index < this.materials.length; index++) {
  13129. if (this.materials[index].name === name) {
  13130. return this.materials[index];
  13131. }
  13132. }
  13133. return null;
  13134. };
  13135. Scene.prototype.getLensFlareSystemByName = function (name) {
  13136. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13137. if (this.lensFlareSystems[index].name === name) {
  13138. return this.lensFlareSystems[index];
  13139. }
  13140. }
  13141. return null;
  13142. };
  13143. Scene.prototype.getCameraByID = function (id) {
  13144. for (var index = 0; index < this.cameras.length; index++) {
  13145. if (this.cameras[index].id === id) {
  13146. return this.cameras[index];
  13147. }
  13148. }
  13149. return null;
  13150. };
  13151. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13152. for (var index = 0; index < this.cameras.length; index++) {
  13153. if (this.cameras[index].uniqueId === uniqueId) {
  13154. return this.cameras[index];
  13155. }
  13156. }
  13157. return null;
  13158. };
  13159. /**
  13160. * get a camera using its name
  13161. * @param {string} the camera's name
  13162. * @return {BABYLON.Camera|null} the camera or null if none found.
  13163. */
  13164. Scene.prototype.getCameraByName = function (name) {
  13165. for (var index = 0; index < this.cameras.length; index++) {
  13166. if (this.cameras[index].name === name) {
  13167. return this.cameras[index];
  13168. }
  13169. }
  13170. return null;
  13171. };
  13172. /**
  13173. * get a light node using its name
  13174. * @param {string} the light's name
  13175. * @return {BABYLON.Light|null} the light or null if none found.
  13176. */
  13177. Scene.prototype.getLightByName = function (name) {
  13178. for (var index = 0; index < this.lights.length; index++) {
  13179. if (this.lights[index].name === name) {
  13180. return this.lights[index];
  13181. }
  13182. }
  13183. return null;
  13184. };
  13185. /**
  13186. * get a light node using its ID
  13187. * @param {string} the light's id
  13188. * @return {BABYLON.Light|null} the light or null if none found.
  13189. */
  13190. Scene.prototype.getLightByID = function (id) {
  13191. for (var index = 0; index < this.lights.length; index++) {
  13192. if (this.lights[index].id === id) {
  13193. return this.lights[index];
  13194. }
  13195. }
  13196. return null;
  13197. };
  13198. /**
  13199. * get a light node using its scene-generated unique ID
  13200. * @param {number} the light's unique id
  13201. * @return {BABYLON.Light|null} the light or null if none found.
  13202. */
  13203. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13204. for (var index = 0; index < this.lights.length; index++) {
  13205. if (this.lights[index].uniqueId === uniqueId) {
  13206. return this.lights[index];
  13207. }
  13208. }
  13209. return null;
  13210. };
  13211. /**
  13212. * get a geometry using its ID
  13213. * @param {string} the geometry's id
  13214. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13215. */
  13216. Scene.prototype.getGeometryByID = function (id) {
  13217. for (var index = 0; index < this._geometries.length; index++) {
  13218. if (this._geometries[index].id === id) {
  13219. return this._geometries[index];
  13220. }
  13221. }
  13222. return null;
  13223. };
  13224. /**
  13225. * add a new geometry to this scene.
  13226. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13227. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13228. * @return {boolean} was the geometry added or not
  13229. */
  13230. Scene.prototype.pushGeometry = function (geometry, force) {
  13231. if (!force && this.getGeometryByID(geometry.id)) {
  13232. return false;
  13233. }
  13234. this._geometries.push(geometry);
  13235. //notify the collision coordinator
  13236. this.collisionCoordinator.onGeometryAdded(geometry);
  13237. if (this.onGeometryAdded) {
  13238. this.onGeometryAdded(geometry);
  13239. }
  13240. return true;
  13241. };
  13242. /**
  13243. * Removes an existing geometry
  13244. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13245. * @return {boolean} was the geometry removed or not
  13246. */
  13247. Scene.prototype.removeGeometry = function (geometry) {
  13248. var index = this._geometries.indexOf(geometry);
  13249. if (index > -1) {
  13250. this._geometries.splice(index, 1);
  13251. //notify the collision coordinator
  13252. this.collisionCoordinator.onGeometryDeleted(geometry);
  13253. if (this.onGeometryRemoved) {
  13254. this.onGeometryRemoved(geometry);
  13255. }
  13256. return true;
  13257. }
  13258. return false;
  13259. };
  13260. Scene.prototype.getGeometries = function () {
  13261. return this._geometries;
  13262. };
  13263. /**
  13264. * Get the first added mesh found of a given ID
  13265. * @param {string} id - the id to search for
  13266. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13267. */
  13268. Scene.prototype.getMeshByID = function (id) {
  13269. for (var index = 0; index < this.meshes.length; index++) {
  13270. if (this.meshes[index].id === id) {
  13271. return this.meshes[index];
  13272. }
  13273. }
  13274. return null;
  13275. };
  13276. /**
  13277. * Get a mesh with its auto-generated unique id
  13278. * @param {number} uniqueId - the unique id to search for
  13279. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13280. */
  13281. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13282. for (var index = 0; index < this.meshes.length; index++) {
  13283. if (this.meshes[index].uniqueId === uniqueId) {
  13284. return this.meshes[index];
  13285. }
  13286. }
  13287. return null;
  13288. };
  13289. /**
  13290. * Get a the last added mesh found of a given ID
  13291. * @param {string} id - the id to search for
  13292. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13293. */
  13294. Scene.prototype.getLastMeshByID = function (id) {
  13295. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13296. if (this.meshes[index].id === id) {
  13297. return this.meshes[index];
  13298. }
  13299. }
  13300. return null;
  13301. };
  13302. /**
  13303. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13304. * @param {string} id - the id to search for
  13305. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13306. */
  13307. Scene.prototype.getLastEntryByID = function (id) {
  13308. var index;
  13309. for (index = this.meshes.length - 1; index >= 0; index--) {
  13310. if (this.meshes[index].id === id) {
  13311. return this.meshes[index];
  13312. }
  13313. }
  13314. for (index = this.cameras.length - 1; index >= 0; index--) {
  13315. if (this.cameras[index].id === id) {
  13316. return this.cameras[index];
  13317. }
  13318. }
  13319. for (index = this.lights.length - 1; index >= 0; index--) {
  13320. if (this.lights[index].id === id) {
  13321. return this.lights[index];
  13322. }
  13323. }
  13324. return null;
  13325. };
  13326. Scene.prototype.getNodeByID = function (id) {
  13327. var mesh = this.getMeshByID(id);
  13328. if (mesh) {
  13329. return mesh;
  13330. }
  13331. var light = this.getLightByID(id);
  13332. if (light) {
  13333. return light;
  13334. }
  13335. return this.getCameraByID(id);
  13336. };
  13337. Scene.prototype.getNodeByName = function (name) {
  13338. var mesh = this.getMeshByName(name);
  13339. if (mesh) {
  13340. return mesh;
  13341. }
  13342. var light = this.getLightByName(name);
  13343. if (light) {
  13344. return light;
  13345. }
  13346. return this.getCameraByName(name);
  13347. };
  13348. Scene.prototype.getMeshByName = function (name) {
  13349. for (var index = 0; index < this.meshes.length; index++) {
  13350. if (this.meshes[index].name === name) {
  13351. return this.meshes[index];
  13352. }
  13353. }
  13354. return null;
  13355. };
  13356. Scene.prototype.getSoundByName = function (name) {
  13357. var index;
  13358. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13359. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13360. return this.mainSoundTrack.soundCollection[index];
  13361. }
  13362. }
  13363. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13364. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13365. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13366. return this.soundTracks[sdIndex].soundCollection[index];
  13367. }
  13368. }
  13369. }
  13370. return null;
  13371. };
  13372. Scene.prototype.getLastSkeletonByID = function (id) {
  13373. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13374. if (this.skeletons[index].id === id) {
  13375. return this.skeletons[index];
  13376. }
  13377. }
  13378. return null;
  13379. };
  13380. Scene.prototype.getSkeletonById = function (id) {
  13381. for (var index = 0; index < this.skeletons.length; index++) {
  13382. if (this.skeletons[index].id === id) {
  13383. return this.skeletons[index];
  13384. }
  13385. }
  13386. return null;
  13387. };
  13388. Scene.prototype.getSkeletonByName = function (name) {
  13389. for (var index = 0; index < this.skeletons.length; index++) {
  13390. if (this.skeletons[index].name === name) {
  13391. return this.skeletons[index];
  13392. }
  13393. }
  13394. return null;
  13395. };
  13396. Scene.prototype.isActiveMesh = function (mesh) {
  13397. return (this._activeMeshes.indexOf(mesh) !== -1);
  13398. };
  13399. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13400. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13401. var material = subMesh.getMaterial();
  13402. if (mesh.showSubMeshesBoundingBox) {
  13403. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13404. }
  13405. if (material) {
  13406. // Render targets
  13407. if (material.getRenderTargetTextures) {
  13408. if (this._processedMaterials.indexOf(material) === -1) {
  13409. this._processedMaterials.push(material);
  13410. this._renderTargets.concat(material.getRenderTargetTextures());
  13411. }
  13412. }
  13413. // Dispatch
  13414. this._activeIndices += subMesh.indexCount;
  13415. this._renderingManager.dispatch(subMesh);
  13416. }
  13417. }
  13418. };
  13419. Scene.prototype._evaluateActiveMeshes = function () {
  13420. this.activeCamera._activeMeshes.reset();
  13421. this._activeMeshes.reset();
  13422. this._renderingManager.reset();
  13423. this._processedMaterials.reset();
  13424. this._activeParticleSystems.reset();
  13425. this._activeSkeletons.reset();
  13426. this._softwareSkinnedMeshes.reset();
  13427. this._boundingBoxRenderer.reset();
  13428. this._edgesRenderers.reset();
  13429. if (!this._frustumPlanes) {
  13430. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13431. }
  13432. else {
  13433. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13434. }
  13435. // Meshes
  13436. var meshes;
  13437. var len;
  13438. if (this._selectionOctree) {
  13439. var selection = this._selectionOctree.select(this._frustumPlanes);
  13440. meshes = selection.data;
  13441. len = selection.length;
  13442. }
  13443. else {
  13444. len = this.meshes.length;
  13445. meshes = this.meshes;
  13446. }
  13447. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13448. var mesh = meshes[meshIndex];
  13449. if (mesh.isBlocked) {
  13450. continue;
  13451. }
  13452. this._totalVertices += mesh.getTotalVertices();
  13453. if (!mesh.isReady() || !mesh.isEnabled()) {
  13454. continue;
  13455. }
  13456. mesh.computeWorldMatrix();
  13457. // Intersections
  13458. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13459. this._meshesForIntersections.pushNoDuplicate(mesh);
  13460. }
  13461. // Switch to current LOD
  13462. var meshLOD = mesh.getLOD(this.activeCamera);
  13463. if (!meshLOD) {
  13464. continue;
  13465. }
  13466. mesh._preActivate();
  13467. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13468. this._activeMeshes.push(mesh);
  13469. this.activeCamera._activeMeshes.push(mesh);
  13470. mesh._activate(this._renderId);
  13471. this._activeMesh(meshLOD);
  13472. }
  13473. }
  13474. // Particle systems
  13475. var beforeParticlesDate = BABYLON.Tools.Now;
  13476. if (this.particlesEnabled) {
  13477. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13478. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13479. var particleSystem = this.particleSystems[particleIndex];
  13480. if (!particleSystem.isStarted()) {
  13481. continue;
  13482. }
  13483. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13484. this._activeParticleSystems.push(particleSystem);
  13485. particleSystem.animate();
  13486. }
  13487. }
  13488. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13489. }
  13490. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13491. };
  13492. Scene.prototype._activeMesh = function (mesh) {
  13493. if (mesh.skeleton && this.skeletonsEnabled) {
  13494. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13495. if (!mesh.computeBonesUsingShaders) {
  13496. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13497. }
  13498. }
  13499. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13500. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13501. }
  13502. if (mesh._edgesRenderer) {
  13503. this._edgesRenderers.push(mesh._edgesRenderer);
  13504. }
  13505. if (mesh && mesh.subMeshes) {
  13506. // Submeshes Octrees
  13507. var len;
  13508. var subMeshes;
  13509. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13510. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13511. len = intersections.length;
  13512. subMeshes = intersections.data;
  13513. }
  13514. else {
  13515. subMeshes = mesh.subMeshes;
  13516. len = subMeshes.length;
  13517. }
  13518. for (var subIndex = 0; subIndex < len; subIndex++) {
  13519. var subMesh = subMeshes[subIndex];
  13520. this._evaluateSubMesh(subMesh, mesh);
  13521. }
  13522. }
  13523. };
  13524. Scene.prototype.updateTransformMatrix = function (force) {
  13525. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13526. };
  13527. Scene.prototype._renderForCamera = function (camera) {
  13528. var engine = this._engine;
  13529. this.activeCamera = camera;
  13530. if (!this.activeCamera)
  13531. throw new Error("Active camera not set");
  13532. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13533. // Viewport
  13534. engine.setViewport(this.activeCamera.viewport);
  13535. // Camera
  13536. this.resetCachedMaterial();
  13537. this._renderId++;
  13538. this.updateTransformMatrix();
  13539. if (this.beforeCameraRender) {
  13540. this.beforeCameraRender(this.activeCamera);
  13541. }
  13542. // Meshes
  13543. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13544. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13545. this._evaluateActiveMeshes();
  13546. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13547. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13548. // Skeletons
  13549. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13550. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13551. skeleton.prepare();
  13552. }
  13553. // Software skinning
  13554. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13555. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13556. mesh.applySkeleton(mesh.skeleton);
  13557. }
  13558. // Render targets
  13559. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13560. if (this.renderTargetsEnabled) {
  13561. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13562. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13563. var renderTarget = this._renderTargets.data[renderIndex];
  13564. if (renderTarget._shouldRender()) {
  13565. this._renderId++;
  13566. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13567. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13568. }
  13569. }
  13570. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13571. this._renderId++;
  13572. }
  13573. if (this._renderTargets.length > 0) {
  13574. engine.restoreDefaultFramebuffer();
  13575. }
  13576. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13577. // Prepare Frame
  13578. this.postProcessManager._prepareFrame();
  13579. var beforeRenderDate = BABYLON.Tools.Now;
  13580. // Backgrounds
  13581. var layerIndex;
  13582. var layer;
  13583. if (this.layers.length) {
  13584. engine.setDepthBuffer(false);
  13585. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13586. layer = this.layers[layerIndex];
  13587. if (layer.isBackground) {
  13588. layer.render();
  13589. }
  13590. }
  13591. engine.setDepthBuffer(true);
  13592. }
  13593. // Render
  13594. BABYLON.Tools.StartPerformanceCounter("Main render");
  13595. this._renderingManager.render(null, null, true, true);
  13596. BABYLON.Tools.EndPerformanceCounter("Main render");
  13597. // Bounding boxes
  13598. this._boundingBoxRenderer.render();
  13599. // Edges
  13600. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13601. this._edgesRenderers.data[edgesRendererIndex].render();
  13602. }
  13603. // Lens flares
  13604. if (this.lensFlaresEnabled) {
  13605. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13606. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13607. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13608. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13609. lensFlareSystem.render();
  13610. }
  13611. }
  13612. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13613. }
  13614. // Foregrounds
  13615. if (this.layers.length) {
  13616. engine.setDepthBuffer(false);
  13617. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13618. layer = this.layers[layerIndex];
  13619. if (!layer.isBackground) {
  13620. layer.render();
  13621. }
  13622. }
  13623. engine.setDepthBuffer(true);
  13624. }
  13625. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13626. // Finalize frame
  13627. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13628. // Update camera
  13629. this.activeCamera._updateFromScene();
  13630. // Reset some special arrays
  13631. this._renderTargets.reset();
  13632. if (this.afterCameraRender) {
  13633. this.afterCameraRender(this.activeCamera);
  13634. }
  13635. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13636. };
  13637. Scene.prototype._processSubCameras = function (camera) {
  13638. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13639. this._renderForCamera(camera);
  13640. return;
  13641. }
  13642. // rig cameras
  13643. for (var index = 0; index < camera._rigCameras.length; index++) {
  13644. this._renderForCamera(camera._rigCameras[index]);
  13645. }
  13646. this.activeCamera = camera;
  13647. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13648. // Update camera
  13649. this.activeCamera._updateFromScene();
  13650. };
  13651. Scene.prototype._checkIntersections = function () {
  13652. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13653. var sourceMesh = this._meshesForIntersections.data[index];
  13654. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13655. var action = sourceMesh.actionManager.actions[actionIndex];
  13656. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13657. var parameters = action.getTriggerParameter();
  13658. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13659. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13660. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13661. if (areIntersecting && currentIntersectionInProgress === -1) {
  13662. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13663. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13664. sourceMesh._intersectionsInProgress.push(otherMesh);
  13665. }
  13666. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13667. sourceMesh._intersectionsInProgress.push(otherMesh);
  13668. }
  13669. }
  13670. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13671. //They intersected, and now they don't.
  13672. //is this trigger an exit trigger? execute an event.
  13673. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13674. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13675. }
  13676. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13677. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13678. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13679. }
  13680. }
  13681. }
  13682. }
  13683. }
  13684. };
  13685. Scene.prototype.render = function () {
  13686. var startDate = BABYLON.Tools.Now;
  13687. this._particlesDuration = 0;
  13688. this._spritesDuration = 0;
  13689. this._activeParticles = 0;
  13690. this._renderDuration = 0;
  13691. this._renderTargetsDuration = 0;
  13692. this._evaluateActiveMeshesDuration = 0;
  13693. this._totalVertices = 0;
  13694. this._activeIndices = 0;
  13695. this._activeBones = 0;
  13696. this.getEngine().resetDrawCalls();
  13697. this._meshesForIntersections.reset();
  13698. this.resetCachedMaterial();
  13699. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13700. // Actions
  13701. if (this.actionManager) {
  13702. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13703. }
  13704. //Simplification Queue
  13705. if (!this.simplificationQueue.running) {
  13706. this.simplificationQueue.executeNext();
  13707. }
  13708. // Animations
  13709. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13710. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13711. this._animate();
  13712. // Physics
  13713. if (this._physicsEngine) {
  13714. BABYLON.Tools.StartPerformanceCounter("Physics");
  13715. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13716. BABYLON.Tools.EndPerformanceCounter("Physics");
  13717. }
  13718. // Before render
  13719. if (this.beforeRender) {
  13720. this.beforeRender();
  13721. }
  13722. var callbackIndex;
  13723. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13724. this._onBeforeRenderCallbacks[callbackIndex]();
  13725. }
  13726. // Customs render targets
  13727. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13728. var engine = this.getEngine();
  13729. var currentActiveCamera = this.activeCamera;
  13730. if (this.renderTargetsEnabled) {
  13731. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13732. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13733. var renderTarget = this.customRenderTargets[customIndex];
  13734. if (renderTarget._shouldRender()) {
  13735. this._renderId++;
  13736. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13737. if (!this.activeCamera)
  13738. throw new Error("Active camera not set");
  13739. // Viewport
  13740. engine.setViewport(this.activeCamera.viewport);
  13741. // Camera
  13742. this.updateTransformMatrix();
  13743. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13744. }
  13745. }
  13746. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13747. this._renderId++;
  13748. }
  13749. if (this.customRenderTargets.length > 0) {
  13750. engine.restoreDefaultFramebuffer();
  13751. }
  13752. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13753. this.activeCamera = currentActiveCamera;
  13754. // Procedural textures
  13755. if (this.proceduralTexturesEnabled) {
  13756. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13757. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13758. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13759. if (proceduralTexture._shouldRender()) {
  13760. proceduralTexture.render();
  13761. }
  13762. }
  13763. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13764. }
  13765. // Clear
  13766. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13767. // Shadows
  13768. if (this.shadowsEnabled) {
  13769. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13770. var light = this.lights[lightIndex];
  13771. var shadowGenerator = light.getShadowGenerator();
  13772. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13773. this._renderTargets.push(shadowGenerator.getShadowMap());
  13774. }
  13775. }
  13776. }
  13777. // Depth renderer
  13778. if (this._depthRenderer) {
  13779. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13780. }
  13781. // RenderPipeline
  13782. this.postProcessRenderPipelineManager.update();
  13783. // Multi-cameras?
  13784. if (this.activeCameras.length > 0) {
  13785. var currentRenderId = this._renderId;
  13786. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13787. this._renderId = currentRenderId;
  13788. this._processSubCameras(this.activeCameras[cameraIndex]);
  13789. }
  13790. }
  13791. else {
  13792. if (!this.activeCamera) {
  13793. throw new Error("No camera defined");
  13794. }
  13795. this._processSubCameras(this.activeCamera);
  13796. }
  13797. // Intersection checks
  13798. this._checkIntersections();
  13799. // Update the audio listener attached to the camera
  13800. this._updateAudioParameters();
  13801. // After render
  13802. if (this.afterRender) {
  13803. this.afterRender();
  13804. }
  13805. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13806. this._onAfterRenderCallbacks[callbackIndex]();
  13807. }
  13808. // Cleaning
  13809. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13810. this._toBeDisposed.data[index].dispose();
  13811. this._toBeDisposed[index] = null;
  13812. }
  13813. this._toBeDisposed.reset();
  13814. if (this.dumpNextRenderTargets) {
  13815. this.dumpNextRenderTargets = false;
  13816. }
  13817. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13818. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13819. };
  13820. Scene.prototype._updateAudioParameters = function () {
  13821. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13822. return;
  13823. }
  13824. var listeningCamera;
  13825. var audioEngine = BABYLON.Engine.audioEngine;
  13826. if (this.activeCameras.length > 0) {
  13827. listeningCamera = this.activeCameras[0];
  13828. }
  13829. else {
  13830. listeningCamera = this.activeCamera;
  13831. }
  13832. if (listeningCamera && audioEngine.canUseWebAudio) {
  13833. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13834. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13835. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13836. cameraDirection.normalize();
  13837. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13838. var i;
  13839. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13840. var sound = this.mainSoundTrack.soundCollection[i];
  13841. if (sound.useCustomAttenuation) {
  13842. sound.updateDistanceFromListener();
  13843. }
  13844. }
  13845. for (i = 0; i < this.soundTracks.length; i++) {
  13846. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13847. sound = this.soundTracks[i].soundCollection[j];
  13848. if (sound.useCustomAttenuation) {
  13849. sound.updateDistanceFromListener();
  13850. }
  13851. }
  13852. }
  13853. }
  13854. };
  13855. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13856. // Audio
  13857. get: function () {
  13858. return this._audioEnabled;
  13859. },
  13860. set: function (value) {
  13861. this._audioEnabled = value;
  13862. if (this._audioEnabled) {
  13863. this._enableAudio();
  13864. }
  13865. else {
  13866. this._disableAudio();
  13867. }
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Scene.prototype._disableAudio = function () {
  13873. var i;
  13874. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13875. this.mainSoundTrack.soundCollection[i].pause();
  13876. }
  13877. for (i = 0; i < this.soundTracks.length; i++) {
  13878. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13879. this.soundTracks[i].soundCollection[j].pause();
  13880. }
  13881. }
  13882. };
  13883. Scene.prototype._enableAudio = function () {
  13884. var i;
  13885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13886. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13887. this.mainSoundTrack.soundCollection[i].play();
  13888. }
  13889. }
  13890. for (i = 0; i < this.soundTracks.length; i++) {
  13891. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13892. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13893. this.soundTracks[i].soundCollection[j].play();
  13894. }
  13895. }
  13896. }
  13897. };
  13898. Object.defineProperty(Scene.prototype, "headphone", {
  13899. get: function () {
  13900. return this._headphone;
  13901. },
  13902. set: function (value) {
  13903. this._headphone = value;
  13904. if (this._headphone) {
  13905. this._switchAudioModeForHeadphones();
  13906. }
  13907. else {
  13908. this._switchAudioModeForNormalSpeakers();
  13909. }
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Scene.prototype._switchAudioModeForHeadphones = function () {
  13915. this.mainSoundTrack.switchPanningModelToHRTF();
  13916. for (var i = 0; i < this.soundTracks.length; i++) {
  13917. this.soundTracks[i].switchPanningModelToHRTF();
  13918. }
  13919. };
  13920. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13921. this.mainSoundTrack.switchPanningModelToEqualPower();
  13922. for (var i = 0; i < this.soundTracks.length; i++) {
  13923. this.soundTracks[i].switchPanningModelToEqualPower();
  13924. }
  13925. };
  13926. Scene.prototype.enableDepthRenderer = function () {
  13927. if (this._depthRenderer) {
  13928. return this._depthRenderer;
  13929. }
  13930. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13931. return this._depthRenderer;
  13932. };
  13933. Scene.prototype.disableDepthRenderer = function () {
  13934. if (!this._depthRenderer) {
  13935. return;
  13936. }
  13937. this._depthRenderer.dispose();
  13938. this._depthRenderer = null;
  13939. };
  13940. Scene.prototype.dispose = function () {
  13941. this.beforeRender = null;
  13942. this.afterRender = null;
  13943. this.skeletons = [];
  13944. this._boundingBoxRenderer.dispose();
  13945. if (this._depthRenderer) {
  13946. this._depthRenderer.dispose();
  13947. }
  13948. // Debug layer
  13949. this.debugLayer.hide();
  13950. // Events
  13951. if (this.onDispose) {
  13952. this.onDispose();
  13953. }
  13954. this._onBeforeRenderCallbacks = [];
  13955. this._onAfterRenderCallbacks = [];
  13956. this.detachControl();
  13957. // Release sounds & sounds tracks
  13958. this.disposeSounds();
  13959. // Detach cameras
  13960. var canvas = this._engine.getRenderingCanvas();
  13961. var index;
  13962. for (index = 0; index < this.cameras.length; index++) {
  13963. this.cameras[index].detachControl(canvas);
  13964. }
  13965. // Release lights
  13966. while (this.lights.length) {
  13967. this.lights[0].dispose();
  13968. }
  13969. // Release meshes
  13970. while (this.meshes.length) {
  13971. this.meshes[0].dispose(true);
  13972. }
  13973. // Release cameras
  13974. while (this.cameras.length) {
  13975. this.cameras[0].dispose();
  13976. }
  13977. // Release materials
  13978. while (this.materials.length) {
  13979. this.materials[0].dispose();
  13980. }
  13981. // Release particles
  13982. while (this.particleSystems.length) {
  13983. this.particleSystems[0].dispose();
  13984. }
  13985. // Release sprites
  13986. while (this.spriteManagers.length) {
  13987. this.spriteManagers[0].dispose();
  13988. }
  13989. // Release layers
  13990. while (this.layers.length) {
  13991. this.layers[0].dispose();
  13992. }
  13993. // Release textures
  13994. while (this.textures.length) {
  13995. this.textures[0].dispose();
  13996. }
  13997. // Post-processes
  13998. this.postProcessManager.dispose();
  13999. // Physics
  14000. if (this._physicsEngine) {
  14001. this.disablePhysicsEngine();
  14002. }
  14003. // Remove from engine
  14004. index = this._engine.scenes.indexOf(this);
  14005. if (index > -1) {
  14006. this._engine.scenes.splice(index, 1);
  14007. }
  14008. this._engine.wipeCaches();
  14009. };
  14010. // Release sounds & sounds tracks
  14011. Scene.prototype.disposeSounds = function () {
  14012. this.mainSoundTrack.dispose();
  14013. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14014. this.soundTracks[scIndex].dispose();
  14015. }
  14016. };
  14017. // Octrees
  14018. Scene.prototype.getWorldExtends = function () {
  14019. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14020. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14021. for (var index = 0; index < this.meshes.length; index++) {
  14022. var mesh = this.meshes[index];
  14023. mesh.computeWorldMatrix(true);
  14024. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14025. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14026. BABYLON.Tools.CheckExtends(minBox, min, max);
  14027. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14028. }
  14029. return {
  14030. min: min,
  14031. max: max
  14032. };
  14033. };
  14034. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14035. if (maxCapacity === void 0) { maxCapacity = 64; }
  14036. if (maxDepth === void 0) { maxDepth = 2; }
  14037. if (!this._selectionOctree) {
  14038. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14039. }
  14040. var worldExtends = this.getWorldExtends();
  14041. // Update octree
  14042. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14043. return this._selectionOctree;
  14044. };
  14045. // Picking
  14046. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  14047. var engine = this._engine;
  14048. if (!camera) {
  14049. if (!this.activeCamera)
  14050. throw new Error("Active camera not set");
  14051. camera = this.activeCamera;
  14052. }
  14053. var cameraViewport = camera.viewport;
  14054. var viewport = cameraViewport.toGlobal(engine);
  14055. // Moving coordinates to local viewport world
  14056. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14057. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14058. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14059. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14060. };
  14061. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14062. var pickingInfo = null;
  14063. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14064. var mesh = this.meshes[meshIndex];
  14065. if (predicate) {
  14066. if (!predicate(mesh)) {
  14067. continue;
  14068. }
  14069. }
  14070. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14071. continue;
  14072. }
  14073. var world = mesh.getWorldMatrix();
  14074. var ray = rayFunction(world);
  14075. var result = mesh.intersects(ray, fastCheck);
  14076. if (!result || !result.hit)
  14077. continue;
  14078. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14079. continue;
  14080. pickingInfo = result;
  14081. if (fastCheck) {
  14082. break;
  14083. }
  14084. }
  14085. return pickingInfo || new BABYLON.PickingInfo();
  14086. };
  14087. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14088. var _this = this;
  14089. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14090. /// <param name="x">X position on screen</param>
  14091. /// <param name="y">Y position on screen</param>
  14092. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14093. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14094. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14095. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14096. };
  14097. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14098. var _this = this;
  14099. return this._internalPick(function (world) {
  14100. if (!_this._pickWithRayInverseMatrix) {
  14101. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14102. }
  14103. world.invertToRef(_this._pickWithRayInverseMatrix);
  14104. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14105. }, predicate, fastCheck);
  14106. };
  14107. Scene.prototype.setPointerOverMesh = function (mesh) {
  14108. if (this._pointerOverMesh === mesh) {
  14109. return;
  14110. }
  14111. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14112. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14113. }
  14114. this._pointerOverMesh = mesh;
  14115. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14116. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14117. }
  14118. };
  14119. Scene.prototype.getPointerOverMesh = function () {
  14120. return this._pointerOverMesh;
  14121. };
  14122. // Physics
  14123. Scene.prototype.getPhysicsEngine = function () {
  14124. return this._physicsEngine;
  14125. };
  14126. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14127. if (this._physicsEngine) {
  14128. return true;
  14129. }
  14130. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14131. if (!this._physicsEngine.isSupported()) {
  14132. this._physicsEngine = null;
  14133. return false;
  14134. }
  14135. this._physicsEngine._initialize(gravity);
  14136. return true;
  14137. };
  14138. Scene.prototype.disablePhysicsEngine = function () {
  14139. if (!this._physicsEngine) {
  14140. return;
  14141. }
  14142. this._physicsEngine.dispose();
  14143. this._physicsEngine = undefined;
  14144. };
  14145. Scene.prototype.isPhysicsEnabled = function () {
  14146. return this._physicsEngine !== undefined;
  14147. };
  14148. Scene.prototype.setGravity = function (gravity) {
  14149. if (!this._physicsEngine) {
  14150. return;
  14151. }
  14152. this._physicsEngine._setGravity(gravity);
  14153. };
  14154. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14155. if (parts.parts) {
  14156. options = parts;
  14157. parts = parts.parts;
  14158. }
  14159. if (!this._physicsEngine) {
  14160. return null;
  14161. }
  14162. for (var index = 0; index < parts.length; index++) {
  14163. var mesh = parts[index].mesh;
  14164. mesh._physicImpostor = parts[index].impostor;
  14165. mesh._physicsMass = options.mass / parts.length;
  14166. mesh._physicsFriction = options.friction;
  14167. mesh._physicRestitution = options.restitution;
  14168. }
  14169. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14170. };
  14171. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14172. for (var index = 0; index < compound.parts.length; index++) {
  14173. var mesh = compound.parts[index].mesh;
  14174. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14175. this._physicsEngine._unregisterMesh(mesh);
  14176. }
  14177. };
  14178. // Misc.
  14179. Scene.prototype.createDefaultCameraOrLight = function () {
  14180. // Light
  14181. if (this.lights.length === 0) {
  14182. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14183. }
  14184. // Camera
  14185. if (!this.activeCamera) {
  14186. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14187. // Compute position
  14188. var worldExtends = this.getWorldExtends();
  14189. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14190. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14191. camera.setTarget(worldCenter);
  14192. this.activeCamera = camera;
  14193. }
  14194. };
  14195. // Tags
  14196. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14197. if (tagsQuery === undefined) {
  14198. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14199. return list;
  14200. }
  14201. var listByTags = [];
  14202. forEach = forEach || (function (item) { return; });
  14203. for (var i in list) {
  14204. var item = list[i];
  14205. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14206. listByTags.push(item);
  14207. forEach(item);
  14208. }
  14209. }
  14210. return listByTags;
  14211. };
  14212. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14213. return this._getByTags(this.meshes, tagsQuery, forEach);
  14214. };
  14215. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14216. return this._getByTags(this.cameras, tagsQuery, forEach);
  14217. };
  14218. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14219. return this._getByTags(this.lights, tagsQuery, forEach);
  14220. };
  14221. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14222. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14223. };
  14224. // Statics
  14225. Scene._FOGMODE_NONE = 0;
  14226. Scene._FOGMODE_EXP = 1;
  14227. Scene._FOGMODE_EXP2 = 2;
  14228. Scene._FOGMODE_LINEAR = 3;
  14229. Scene.MinDeltaTime = 1.0;
  14230. Scene.MaxDeltaTime = 1000.0;
  14231. return Scene;
  14232. })();
  14233. BABYLON.Scene = Scene;
  14234. })(BABYLON || (BABYLON = {}));
  14235. var BABYLON;
  14236. (function (BABYLON) {
  14237. var VertexBuffer = (function () {
  14238. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14239. if (engine instanceof BABYLON.Mesh) {
  14240. this._engine = engine.getScene().getEngine();
  14241. }
  14242. else {
  14243. this._engine = engine;
  14244. }
  14245. this._updatable = updatable;
  14246. this._data = data;
  14247. if (!postponeInternalCreation) {
  14248. this.create();
  14249. }
  14250. this._kind = kind;
  14251. if (stride) {
  14252. this._strideSize = stride;
  14253. return;
  14254. }
  14255. // Deduce stride from kind
  14256. switch (kind) {
  14257. case VertexBuffer.PositionKind:
  14258. this._strideSize = 3;
  14259. break;
  14260. case VertexBuffer.NormalKind:
  14261. this._strideSize = 3;
  14262. break;
  14263. case VertexBuffer.UVKind:
  14264. case VertexBuffer.UV2Kind:
  14265. case VertexBuffer.UV3Kind:
  14266. case VertexBuffer.UV4Kind:
  14267. case VertexBuffer.UV5Kind:
  14268. case VertexBuffer.UV6Kind:
  14269. this._strideSize = 2;
  14270. break;
  14271. case VertexBuffer.ColorKind:
  14272. this._strideSize = 4;
  14273. break;
  14274. case VertexBuffer.MatricesIndicesKind:
  14275. this._strideSize = 4;
  14276. break;
  14277. case VertexBuffer.MatricesWeightsKind:
  14278. this._strideSize = 4;
  14279. break;
  14280. }
  14281. }
  14282. // Properties
  14283. VertexBuffer.prototype.isUpdatable = function () {
  14284. return this._updatable;
  14285. };
  14286. VertexBuffer.prototype.getData = function () {
  14287. return this._data;
  14288. };
  14289. VertexBuffer.prototype.getBuffer = function () {
  14290. return this._buffer;
  14291. };
  14292. VertexBuffer.prototype.getStrideSize = function () {
  14293. return this._strideSize;
  14294. };
  14295. // Methods
  14296. VertexBuffer.prototype.create = function (data) {
  14297. if (!data && this._buffer) {
  14298. return; // nothing to do
  14299. }
  14300. data = data || this._data;
  14301. if (!this._buffer) {
  14302. if (this._updatable) {
  14303. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14304. }
  14305. else {
  14306. this._buffer = this._engine.createVertexBuffer(data);
  14307. }
  14308. }
  14309. if (this._updatable) {
  14310. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14311. this._data = data;
  14312. }
  14313. };
  14314. VertexBuffer.prototype.update = function (data) {
  14315. this.create(data);
  14316. };
  14317. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14318. if (!this._buffer) {
  14319. return;
  14320. }
  14321. if (this._updatable) {
  14322. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14323. this._data = null;
  14324. }
  14325. };
  14326. VertexBuffer.prototype.dispose = function () {
  14327. if (!this._buffer) {
  14328. return;
  14329. }
  14330. if (this._engine._releaseBuffer(this._buffer)) {
  14331. this._buffer = null;
  14332. }
  14333. };
  14334. Object.defineProperty(VertexBuffer, "PositionKind", {
  14335. get: function () {
  14336. return VertexBuffer._PositionKind;
  14337. },
  14338. enumerable: true,
  14339. configurable: true
  14340. });
  14341. Object.defineProperty(VertexBuffer, "NormalKind", {
  14342. get: function () {
  14343. return VertexBuffer._NormalKind;
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(VertexBuffer, "UVKind", {
  14349. get: function () {
  14350. return VertexBuffer._UVKind;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14356. get: function () {
  14357. return VertexBuffer._UV2Kind;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14363. get: function () {
  14364. return VertexBuffer._UV3Kind;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14370. get: function () {
  14371. return VertexBuffer._UV4Kind;
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14377. get: function () {
  14378. return VertexBuffer._UV5Kind;
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14384. get: function () {
  14385. return VertexBuffer._UV6Kind;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Object.defineProperty(VertexBuffer, "ColorKind", {
  14391. get: function () {
  14392. return VertexBuffer._ColorKind;
  14393. },
  14394. enumerable: true,
  14395. configurable: true
  14396. });
  14397. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14398. get: function () {
  14399. return VertexBuffer._MatricesIndicesKind;
  14400. },
  14401. enumerable: true,
  14402. configurable: true
  14403. });
  14404. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14405. get: function () {
  14406. return VertexBuffer._MatricesWeightsKind;
  14407. },
  14408. enumerable: true,
  14409. configurable: true
  14410. });
  14411. // Enums
  14412. VertexBuffer._PositionKind = "position";
  14413. VertexBuffer._NormalKind = "normal";
  14414. VertexBuffer._UVKind = "uv";
  14415. VertexBuffer._UV2Kind = "uv2";
  14416. VertexBuffer._UV3Kind = "uv3";
  14417. VertexBuffer._UV4Kind = "uv4";
  14418. VertexBuffer._UV5Kind = "uv5";
  14419. VertexBuffer._UV6Kind = "uv6";
  14420. VertexBuffer._ColorKind = "color";
  14421. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14422. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14423. return VertexBuffer;
  14424. })();
  14425. BABYLON.VertexBuffer = VertexBuffer;
  14426. })(BABYLON || (BABYLON = {}));
  14427. var BABYLON;
  14428. (function (BABYLON) {
  14429. /**
  14430. * Creates an instance based on a source mesh.
  14431. */
  14432. var InstancedMesh = (function (_super) {
  14433. __extends(InstancedMesh, _super);
  14434. function InstancedMesh(name, source) {
  14435. _super.call(this, name, source.getScene());
  14436. source.instances.push(this);
  14437. this._sourceMesh = source;
  14438. this.position.copyFrom(source.position);
  14439. this.rotation.copyFrom(source.rotation);
  14440. this.scaling.copyFrom(source.scaling);
  14441. if (source.rotationQuaternion) {
  14442. this.rotationQuaternion = source.rotationQuaternion.clone();
  14443. }
  14444. this.infiniteDistance = source.infiniteDistance;
  14445. this.setPivotMatrix(source.getPivotMatrix());
  14446. this.refreshBoundingInfo();
  14447. this._syncSubMeshes();
  14448. }
  14449. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14450. // Methods
  14451. get: function () {
  14452. return this._sourceMesh.receiveShadows;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Object.defineProperty(InstancedMesh.prototype, "material", {
  14458. get: function () {
  14459. return this._sourceMesh.material;
  14460. },
  14461. enumerable: true,
  14462. configurable: true
  14463. });
  14464. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14465. get: function () {
  14466. return this._sourceMesh.visibility;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14472. get: function () {
  14473. return this._sourceMesh.skeleton;
  14474. },
  14475. enumerable: true,
  14476. configurable: true
  14477. });
  14478. InstancedMesh.prototype.getTotalVertices = function () {
  14479. return this._sourceMesh.getTotalVertices();
  14480. };
  14481. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14482. get: function () {
  14483. return this._sourceMesh;
  14484. },
  14485. enumerable: true,
  14486. configurable: true
  14487. });
  14488. InstancedMesh.prototype.getVerticesData = function (kind) {
  14489. return this._sourceMesh.getVerticesData(kind);
  14490. };
  14491. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14492. return this._sourceMesh.isVerticesDataPresent(kind);
  14493. };
  14494. InstancedMesh.prototype.getIndices = function () {
  14495. return this._sourceMesh.getIndices();
  14496. };
  14497. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14498. get: function () {
  14499. return this._sourceMesh._positions;
  14500. },
  14501. enumerable: true,
  14502. configurable: true
  14503. });
  14504. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14505. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14506. if (data) {
  14507. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14508. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14509. }
  14510. this._updateBoundingInfo();
  14511. };
  14512. InstancedMesh.prototype._preActivate = function () {
  14513. if (this._currentLOD) {
  14514. this._currentLOD._preActivate();
  14515. }
  14516. };
  14517. InstancedMesh.prototype._activate = function (renderId) {
  14518. if (this._currentLOD) {
  14519. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14520. }
  14521. };
  14522. InstancedMesh.prototype.getLOD = function (camera) {
  14523. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14524. if (this._currentLOD === this.sourceMesh) {
  14525. return this;
  14526. }
  14527. return this._currentLOD;
  14528. };
  14529. InstancedMesh.prototype._syncSubMeshes = function () {
  14530. this.releaseSubMeshes();
  14531. if (this._sourceMesh.subMeshes) {
  14532. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14533. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14534. }
  14535. }
  14536. };
  14537. InstancedMesh.prototype._generatePointsArray = function () {
  14538. return this._sourceMesh._generatePointsArray();
  14539. };
  14540. // Clone
  14541. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14542. var result = this._sourceMesh.createInstance(name);
  14543. // Deep copy
  14544. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14545. // Bounding info
  14546. this.refreshBoundingInfo();
  14547. // Parent
  14548. if (newParent) {
  14549. result.parent = newParent;
  14550. }
  14551. if (!doNotCloneChildren) {
  14552. // Children
  14553. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14554. var mesh = this.getScene().meshes[index];
  14555. if (mesh.parent === this) {
  14556. mesh.clone(mesh.name, result);
  14557. }
  14558. }
  14559. }
  14560. result.computeWorldMatrix(true);
  14561. return result;
  14562. };
  14563. // Dispoe
  14564. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14565. // Remove from mesh
  14566. var index = this._sourceMesh.instances.indexOf(this);
  14567. this._sourceMesh.instances.splice(index, 1);
  14568. _super.prototype.dispose.call(this, doNotRecurse);
  14569. };
  14570. return InstancedMesh;
  14571. })(BABYLON.AbstractMesh);
  14572. BABYLON.InstancedMesh = InstancedMesh;
  14573. })(BABYLON || (BABYLON = {}));
  14574. var BABYLON;
  14575. (function (BABYLON) {
  14576. var _InstancesBatch = (function () {
  14577. function _InstancesBatch() {
  14578. this.mustReturn = false;
  14579. this.visibleInstances = new Array();
  14580. this.renderSelf = new Array();
  14581. }
  14582. return _InstancesBatch;
  14583. })();
  14584. BABYLON._InstancesBatch = _InstancesBatch;
  14585. var Mesh = (function (_super) {
  14586. __extends(Mesh, _super);
  14587. /**
  14588. * @constructor
  14589. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14590. * @param {Scene} scene - The scene to add this mesh to.
  14591. * @param {Node} parent - The parent of this mesh, if it has one
  14592. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14593. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14594. * When false, achieved by calling a clone(), also passing False.
  14595. * This will make creation of children, recursive.
  14596. */
  14597. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14598. if (parent === void 0) { parent = null; }
  14599. _super.call(this, name, scene);
  14600. // Members
  14601. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14602. this.instances = new Array();
  14603. this._LODLevels = new Array();
  14604. this._onBeforeRenderCallbacks = new Array();
  14605. this._onAfterRenderCallbacks = new Array();
  14606. this._visibleInstances = {};
  14607. this._renderIdForInstances = new Array();
  14608. this._batchCache = new _InstancesBatch();
  14609. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14610. this._sideOrientation = Mesh._DEFAULTSIDE;
  14611. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14612. if (source) {
  14613. // Geometry
  14614. if (source._geometry) {
  14615. source._geometry.applyToMesh(this);
  14616. }
  14617. // Deep copy
  14618. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14619. this.id = name + "." + source.id;
  14620. // Material
  14621. this.material = source.material;
  14622. var index;
  14623. if (!doNotCloneChildren) {
  14624. // Children
  14625. for (index = 0; index < scene.meshes.length; index++) {
  14626. var mesh = scene.meshes[index];
  14627. if (mesh.parent === source) {
  14628. // doNotCloneChildren is always going to be False
  14629. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14630. }
  14631. }
  14632. }
  14633. // Particles
  14634. for (index = 0; index < scene.particleSystems.length; index++) {
  14635. var system = scene.particleSystems[index];
  14636. if (system.emitter === source) {
  14637. system.clone(system.name, this);
  14638. }
  14639. }
  14640. this.computeWorldMatrix(true);
  14641. }
  14642. // Parent
  14643. if (parent !== null) {
  14644. this.parent = parent;
  14645. }
  14646. }
  14647. Object.defineProperty(Mesh, "FRONTSIDE", {
  14648. get: function () {
  14649. return Mesh._FRONTSIDE;
  14650. },
  14651. enumerable: true,
  14652. configurable: true
  14653. });
  14654. Object.defineProperty(Mesh, "BACKSIDE", {
  14655. get: function () {
  14656. return Mesh._BACKSIDE;
  14657. },
  14658. enumerable: true,
  14659. configurable: true
  14660. });
  14661. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14662. get: function () {
  14663. return Mesh._DOUBLESIDE;
  14664. },
  14665. enumerable: true,
  14666. configurable: true
  14667. });
  14668. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14669. get: function () {
  14670. return Mesh._DEFAULTSIDE;
  14671. },
  14672. enumerable: true,
  14673. configurable: true
  14674. });
  14675. Object.defineProperty(Mesh, "NO_CAP", {
  14676. get: function () {
  14677. return Mesh._NO_CAP;
  14678. },
  14679. enumerable: true,
  14680. configurable: true
  14681. });
  14682. Object.defineProperty(Mesh, "CAP_START", {
  14683. get: function () {
  14684. return Mesh._CAP_START;
  14685. },
  14686. enumerable: true,
  14687. configurable: true
  14688. });
  14689. Object.defineProperty(Mesh, "CAP_END", {
  14690. get: function () {
  14691. return Mesh._CAP_END;
  14692. },
  14693. enumerable: true,
  14694. configurable: true
  14695. });
  14696. Object.defineProperty(Mesh, "CAP_ALL", {
  14697. get: function () {
  14698. return Mesh._CAP_ALL;
  14699. },
  14700. enumerable: true,
  14701. configurable: true
  14702. });
  14703. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14704. // Methods
  14705. get: function () {
  14706. return this._LODLevels.length > 0;
  14707. },
  14708. enumerable: true,
  14709. configurable: true
  14710. });
  14711. Mesh.prototype._sortLODLevels = function () {
  14712. this._LODLevels.sort(function (a, b) {
  14713. if (a.distance < b.distance) {
  14714. return 1;
  14715. }
  14716. if (a.distance > b.distance) {
  14717. return -1;
  14718. }
  14719. return 0;
  14720. });
  14721. };
  14722. /**
  14723. * Add a mesh as LOD level triggered at the given distance.
  14724. * @param {number} distance - the distance from the center of the object to show this level
  14725. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14726. * @return {BABYLON.Mesh} this mesh (for chaining)
  14727. */
  14728. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14729. if (mesh && mesh._masterMesh) {
  14730. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14731. return this;
  14732. }
  14733. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14734. this._LODLevels.push(level);
  14735. if (mesh) {
  14736. mesh._masterMesh = this;
  14737. }
  14738. this._sortLODLevels();
  14739. return this;
  14740. };
  14741. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14742. for (var index = 0; index < this._LODLevels.length; index++) {
  14743. var level = this._LODLevels[index];
  14744. if (level.distance === distance) {
  14745. return level.mesh;
  14746. }
  14747. }
  14748. return null;
  14749. };
  14750. /**
  14751. * Remove a mesh from the LOD array
  14752. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14753. * @return {BABYLON.Mesh} this mesh (for chaining)
  14754. */
  14755. Mesh.prototype.removeLODLevel = function (mesh) {
  14756. for (var index = 0; index < this._LODLevels.length; index++) {
  14757. if (this._LODLevels[index].mesh === mesh) {
  14758. this._LODLevels.splice(index, 1);
  14759. if (mesh) {
  14760. mesh._masterMesh = null;
  14761. }
  14762. }
  14763. }
  14764. this._sortLODLevels();
  14765. return this;
  14766. };
  14767. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14768. if (!this._LODLevels || this._LODLevels.length === 0) {
  14769. return this;
  14770. }
  14771. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14772. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14773. if (this.onLODLevelSelection) {
  14774. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14775. }
  14776. return this;
  14777. }
  14778. for (var index = 0; index < this._LODLevels.length; index++) {
  14779. var level = this._LODLevels[index];
  14780. if (level.distance < distanceToCamera) {
  14781. if (level.mesh) {
  14782. level.mesh._preActivate();
  14783. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14784. }
  14785. if (this.onLODLevelSelection) {
  14786. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14787. }
  14788. return level.mesh;
  14789. }
  14790. }
  14791. if (this.onLODLevelSelection) {
  14792. this.onLODLevelSelection(distanceToCamera, this, this);
  14793. }
  14794. return this;
  14795. };
  14796. Object.defineProperty(Mesh.prototype, "geometry", {
  14797. get: function () {
  14798. return this._geometry;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Mesh.prototype.getTotalVertices = function () {
  14804. if (!this._geometry) {
  14805. return 0;
  14806. }
  14807. return this._geometry.getTotalVertices();
  14808. };
  14809. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14810. if (!this._geometry) {
  14811. return null;
  14812. }
  14813. return this._geometry.getVerticesData(kind, copyWhenShared);
  14814. };
  14815. Mesh.prototype.getVertexBuffer = function (kind) {
  14816. if (!this._geometry) {
  14817. return undefined;
  14818. }
  14819. return this._geometry.getVertexBuffer(kind);
  14820. };
  14821. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14822. if (!this._geometry) {
  14823. if (this._delayInfo) {
  14824. return this._delayInfo.indexOf(kind) !== -1;
  14825. }
  14826. return false;
  14827. }
  14828. return this._geometry.isVerticesDataPresent(kind);
  14829. };
  14830. Mesh.prototype.getVerticesDataKinds = function () {
  14831. if (!this._geometry) {
  14832. var result = [];
  14833. if (this._delayInfo) {
  14834. for (var kind in this._delayInfo) {
  14835. result.push(kind);
  14836. }
  14837. }
  14838. return result;
  14839. }
  14840. return this._geometry.getVerticesDataKinds();
  14841. };
  14842. Mesh.prototype.getTotalIndices = function () {
  14843. if (!this._geometry) {
  14844. return 0;
  14845. }
  14846. return this._geometry.getTotalIndices();
  14847. };
  14848. Mesh.prototype.getIndices = function (copyWhenShared) {
  14849. if (!this._geometry) {
  14850. return [];
  14851. }
  14852. return this._geometry.getIndices(copyWhenShared);
  14853. };
  14854. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14855. get: function () {
  14856. return this._masterMesh !== null && this._masterMesh !== undefined;
  14857. },
  14858. enumerable: true,
  14859. configurable: true
  14860. });
  14861. Mesh.prototype.isReady = function () {
  14862. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14863. return false;
  14864. }
  14865. return _super.prototype.isReady.call(this);
  14866. };
  14867. Mesh.prototype.isDisposed = function () {
  14868. return this._isDisposed;
  14869. };
  14870. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14871. get: function () {
  14872. return this._sideOrientation;
  14873. },
  14874. set: function (sideO) {
  14875. this._sideOrientation = sideO;
  14876. },
  14877. enumerable: true,
  14878. configurable: true
  14879. });
  14880. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14881. get: function () {
  14882. return this._areNormalsFrozen;
  14883. },
  14884. enumerable: true,
  14885. configurable: true
  14886. });
  14887. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14888. Mesh.prototype.freezeNormals = function () {
  14889. this._areNormalsFrozen = true;
  14890. };
  14891. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14892. Mesh.prototype.unfreezeNormals = function () {
  14893. this._areNormalsFrozen = false;
  14894. };
  14895. // Methods
  14896. Mesh.prototype._preActivate = function () {
  14897. var sceneRenderId = this.getScene().getRenderId();
  14898. if (this._preActivateId === sceneRenderId) {
  14899. return;
  14900. }
  14901. this._preActivateId = sceneRenderId;
  14902. this._visibleInstances = null;
  14903. };
  14904. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14905. if (!this._visibleInstances) {
  14906. this._visibleInstances = {};
  14907. this._visibleInstances.defaultRenderId = renderId;
  14908. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14909. }
  14910. if (!this._visibleInstances[renderId]) {
  14911. this._visibleInstances[renderId] = new Array();
  14912. }
  14913. this._visibleInstances[renderId].push(instance);
  14914. };
  14915. Mesh.prototype.refreshBoundingInfo = function () {
  14916. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14917. if (data) {
  14918. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14919. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14920. }
  14921. if (this.subMeshes) {
  14922. for (var index = 0; index < this.subMeshes.length; index++) {
  14923. this.subMeshes[index].refreshBoundingInfo();
  14924. }
  14925. }
  14926. this._updateBoundingInfo();
  14927. };
  14928. Mesh.prototype._createGlobalSubMesh = function () {
  14929. var totalVertices = this.getTotalVertices();
  14930. if (!totalVertices || !this.getIndices()) {
  14931. return null;
  14932. }
  14933. this.releaseSubMeshes();
  14934. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14935. };
  14936. Mesh.prototype.subdivide = function (count) {
  14937. if (count < 1) {
  14938. return;
  14939. }
  14940. var totalIndices = this.getTotalIndices();
  14941. var subdivisionSize = (totalIndices / count) | 0;
  14942. var offset = 0;
  14943. // Ensure that subdivisionSize is a multiple of 3
  14944. while (subdivisionSize % 3 !== 0) {
  14945. subdivisionSize++;
  14946. }
  14947. this.releaseSubMeshes();
  14948. for (var index = 0; index < count; index++) {
  14949. if (offset >= totalIndices) {
  14950. break;
  14951. }
  14952. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14953. offset += subdivisionSize;
  14954. }
  14955. this.synchronizeInstances();
  14956. };
  14957. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14958. if (kind instanceof Array) {
  14959. var temp = data;
  14960. data = kind;
  14961. kind = temp;
  14962. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14963. }
  14964. if (!this._geometry) {
  14965. var vertexData = new BABYLON.VertexData();
  14966. vertexData.set(data, kind);
  14967. var scene = this.getScene();
  14968. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14969. }
  14970. else {
  14971. this._geometry.setVerticesData(kind, data, updatable, stride);
  14972. }
  14973. };
  14974. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14975. if (!this._geometry) {
  14976. return;
  14977. }
  14978. if (!makeItUnique) {
  14979. this._geometry.updateVerticesData(kind, data, updateExtends);
  14980. }
  14981. else {
  14982. this.makeGeometryUnique();
  14983. this.updateVerticesData(kind, data, updateExtends, false);
  14984. }
  14985. };
  14986. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14987. if (!this._geometry) {
  14988. return;
  14989. }
  14990. if (!makeItUnique) {
  14991. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14992. }
  14993. else {
  14994. this.makeGeometryUnique();
  14995. this.updateVerticesDataDirectly(kind, data, offset, false);
  14996. }
  14997. };
  14998. // Mesh positions update function :
  14999. // updates the mesh positions according to the positionFunction returned values.
  15000. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15001. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15002. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15003. if (computeNormals === void 0) { computeNormals = true; }
  15004. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15005. positionFunction(positions);
  15006. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15007. if (computeNormals) {
  15008. var indices = this.getIndices();
  15009. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15010. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15011. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15012. }
  15013. };
  15014. Mesh.prototype.makeGeometryUnique = function () {
  15015. if (!this._geometry) {
  15016. return;
  15017. }
  15018. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15019. geometry.applyToMesh(this);
  15020. };
  15021. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15022. if (!this._geometry) {
  15023. var vertexData = new BABYLON.VertexData();
  15024. vertexData.indices = indices;
  15025. var scene = this.getScene();
  15026. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15027. }
  15028. else {
  15029. this._geometry.setIndices(indices, totalVertices);
  15030. }
  15031. };
  15032. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15033. var engine = this.getScene().getEngine();
  15034. // Wireframe
  15035. var indexToBind;
  15036. switch (fillMode) {
  15037. case BABYLON.Material.PointFillMode:
  15038. indexToBind = null;
  15039. break;
  15040. case BABYLON.Material.WireFrameFillMode:
  15041. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15042. break;
  15043. default:
  15044. case BABYLON.Material.TriangleFillMode:
  15045. indexToBind = this._geometry.getIndexBuffer();
  15046. break;
  15047. }
  15048. // VBOs
  15049. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15050. };
  15051. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15052. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15053. return;
  15054. }
  15055. var engine = this.getScene().getEngine();
  15056. // Draw order
  15057. switch (fillMode) {
  15058. case BABYLON.Material.PointFillMode:
  15059. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15060. break;
  15061. case BABYLON.Material.WireFrameFillMode:
  15062. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15063. break;
  15064. default:
  15065. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15066. }
  15067. };
  15068. Mesh.prototype.registerBeforeRender = function (func) {
  15069. this._onBeforeRenderCallbacks.push(func);
  15070. };
  15071. Mesh.prototype.unregisterBeforeRender = function (func) {
  15072. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15073. if (index > -1) {
  15074. this._onBeforeRenderCallbacks.splice(index, 1);
  15075. }
  15076. };
  15077. Mesh.prototype.registerAfterRender = function (func) {
  15078. this._onAfterRenderCallbacks.push(func);
  15079. };
  15080. Mesh.prototype.unregisterAfterRender = function (func) {
  15081. var index = this._onAfterRenderCallbacks.indexOf(func);
  15082. if (index > -1) {
  15083. this._onAfterRenderCallbacks.splice(index, 1);
  15084. }
  15085. };
  15086. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15087. var scene = this.getScene();
  15088. this._batchCache.mustReturn = false;
  15089. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15090. this._batchCache.visibleInstances[subMeshId] = null;
  15091. if (this._visibleInstances) {
  15092. var currentRenderId = scene.getRenderId();
  15093. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15094. var selfRenderId = this._renderId;
  15095. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15096. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15097. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15098. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15099. }
  15100. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15101. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15102. this._batchCache.mustReturn = true;
  15103. return this._batchCache;
  15104. }
  15105. if (currentRenderId !== selfRenderId) {
  15106. this._batchCache.renderSelf[subMeshId] = false;
  15107. }
  15108. }
  15109. this._renderIdForInstances[subMeshId] = currentRenderId;
  15110. }
  15111. return this._batchCache;
  15112. };
  15113. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15114. var visibleInstances = batch.visibleInstances[subMesh._id];
  15115. var matricesCount = visibleInstances.length + 1;
  15116. var bufferSize = matricesCount * 16 * 4;
  15117. while (this._instancesBufferSize < bufferSize) {
  15118. this._instancesBufferSize *= 2;
  15119. }
  15120. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15121. if (this._worldMatricesInstancesBuffer) {
  15122. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15123. }
  15124. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15125. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15126. }
  15127. var offset = 0;
  15128. var instancesCount = 0;
  15129. var world = this.getWorldMatrix();
  15130. if (batch.renderSelf[subMesh._id]) {
  15131. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15132. offset += 16;
  15133. instancesCount++;
  15134. }
  15135. if (visibleInstances) {
  15136. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15137. var instance = visibleInstances[instanceIndex];
  15138. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15139. offset += 16;
  15140. instancesCount++;
  15141. }
  15142. }
  15143. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15144. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15145. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15146. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15147. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15148. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15149. this._draw(subMesh, fillMode, instancesCount);
  15150. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15151. };
  15152. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15153. var scene = this.getScene();
  15154. var engine = scene.getEngine();
  15155. if (hardwareInstancedRendering) {
  15156. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15157. }
  15158. else {
  15159. if (batch.renderSelf[subMesh._id]) {
  15160. // Draw
  15161. if (onBeforeDraw) {
  15162. onBeforeDraw(false, this.getWorldMatrix());
  15163. }
  15164. this._draw(subMesh, fillMode);
  15165. }
  15166. if (batch.visibleInstances[subMesh._id]) {
  15167. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15168. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15169. // World
  15170. var world = instance.getWorldMatrix();
  15171. if (onBeforeDraw) {
  15172. onBeforeDraw(true, world);
  15173. }
  15174. // Draw
  15175. this._draw(subMesh, fillMode);
  15176. }
  15177. }
  15178. }
  15179. };
  15180. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15181. var scene = this.getScene();
  15182. // Managing instances
  15183. var batch = this._getInstancesRenderList(subMesh._id);
  15184. if (batch.mustReturn) {
  15185. return;
  15186. }
  15187. // Checking geometry state
  15188. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15189. return;
  15190. }
  15191. var callbackIndex;
  15192. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15193. this._onBeforeRenderCallbacks[callbackIndex](this);
  15194. }
  15195. var engine = scene.getEngine();
  15196. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15197. // Material
  15198. var effectiveMaterial = subMesh.getMaterial();
  15199. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15200. return;
  15201. }
  15202. // Outline - step 1
  15203. var savedDepthWrite = engine.getDepthWrite();
  15204. if (this.renderOutline) {
  15205. engine.setDepthWrite(false);
  15206. scene.getOutlineRenderer().render(subMesh, batch);
  15207. engine.setDepthWrite(savedDepthWrite);
  15208. }
  15209. effectiveMaterial._preBind();
  15210. var effect = effectiveMaterial.getEffect();
  15211. // Bind
  15212. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15213. this._bind(subMesh, effect, fillMode);
  15214. var world = this.getWorldMatrix();
  15215. effectiveMaterial.bind(world, this);
  15216. // Alpha mode
  15217. if (enableAlphaMode) {
  15218. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15219. }
  15220. // Draw
  15221. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15222. if (isInstance) {
  15223. effectiveMaterial.bindOnlyWorldMatrix(world);
  15224. }
  15225. });
  15226. // Unbind
  15227. effectiveMaterial.unbind();
  15228. // Outline - step 2
  15229. if (this.renderOutline && savedDepthWrite) {
  15230. engine.setDepthWrite(true);
  15231. engine.setColorWrite(false);
  15232. scene.getOutlineRenderer().render(subMesh, batch);
  15233. engine.setColorWrite(true);
  15234. }
  15235. // Overlay
  15236. if (this.renderOverlay) {
  15237. var currentMode = engine.getAlphaMode();
  15238. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15239. scene.getOutlineRenderer().render(subMesh, batch, true);
  15240. engine.setAlphaMode(currentMode);
  15241. }
  15242. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15243. this._onAfterRenderCallbacks[callbackIndex](this);
  15244. }
  15245. };
  15246. Mesh.prototype.getEmittedParticleSystems = function () {
  15247. var results = new Array();
  15248. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15249. var particleSystem = this.getScene().particleSystems[index];
  15250. if (particleSystem.emitter === this) {
  15251. results.push(particleSystem);
  15252. }
  15253. }
  15254. return results;
  15255. };
  15256. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15257. var results = new Array();
  15258. var descendants = this.getDescendants();
  15259. descendants.push(this);
  15260. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15261. var particleSystem = this.getScene().particleSystems[index];
  15262. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15263. results.push(particleSystem);
  15264. }
  15265. }
  15266. return results;
  15267. };
  15268. Mesh.prototype.getChildren = function () {
  15269. var results = [];
  15270. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15271. var mesh = this.getScene().meshes[index];
  15272. if (mesh.parent === this) {
  15273. results.push(mesh);
  15274. }
  15275. }
  15276. return results;
  15277. };
  15278. Mesh.prototype._checkDelayState = function () {
  15279. var _this = this;
  15280. var that = this;
  15281. var scene = this.getScene();
  15282. if (this._geometry) {
  15283. this._geometry.load(scene);
  15284. }
  15285. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15286. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15287. scene._addPendingData(that);
  15288. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15289. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15290. if (data instanceof ArrayBuffer) {
  15291. _this._delayLoadingFunction(data, _this);
  15292. }
  15293. else {
  15294. _this._delayLoadingFunction(JSON.parse(data), _this);
  15295. }
  15296. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15297. scene._removePendingData(_this);
  15298. }, function () { }, scene.database, getBinaryData);
  15299. }
  15300. };
  15301. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15302. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15303. return false;
  15304. }
  15305. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15306. return false;
  15307. }
  15308. this._checkDelayState();
  15309. return true;
  15310. };
  15311. Mesh.prototype.setMaterialByID = function (id) {
  15312. var materials = this.getScene().materials;
  15313. var index;
  15314. for (index = 0; index < materials.length; index++) {
  15315. if (materials[index].id === id) {
  15316. this.material = materials[index];
  15317. return;
  15318. }
  15319. }
  15320. // Multi
  15321. var multiMaterials = this.getScene().multiMaterials;
  15322. for (index = 0; index < multiMaterials.length; index++) {
  15323. if (multiMaterials[index].id === id) {
  15324. this.material = multiMaterials[index];
  15325. return;
  15326. }
  15327. }
  15328. };
  15329. Mesh.prototype.getAnimatables = function () {
  15330. var results = [];
  15331. if (this.material) {
  15332. results.push(this.material);
  15333. }
  15334. if (this.skeleton) {
  15335. results.push(this.skeleton);
  15336. }
  15337. return results;
  15338. };
  15339. // Geometry
  15340. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15341. // Position
  15342. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15343. return;
  15344. }
  15345. this._resetPointsArrayCache();
  15346. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15347. var temp = [];
  15348. var index;
  15349. for (index = 0; index < data.length; index += 3) {
  15350. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15351. }
  15352. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15353. // Normals
  15354. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15355. return;
  15356. }
  15357. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15358. temp = [];
  15359. for (index = 0; index < data.length; index += 3) {
  15360. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15361. }
  15362. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15363. // flip faces?
  15364. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15365. this.flipFaces();
  15366. }
  15367. };
  15368. // Will apply current transform to mesh and reset world matrix
  15369. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15370. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15371. this.scaling.copyFromFloats(1, 1, 1);
  15372. this.position.copyFromFloats(0, 0, 0);
  15373. this.rotation.copyFromFloats(0, 0, 0);
  15374. //only if quaternion is already set
  15375. if (this.rotationQuaternion) {
  15376. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15377. }
  15378. this._worldMatrix = BABYLON.Matrix.Identity();
  15379. };
  15380. // Cache
  15381. Mesh.prototype._resetPointsArrayCache = function () {
  15382. this._positions = null;
  15383. };
  15384. Mesh.prototype._generatePointsArray = function () {
  15385. if (this._positions)
  15386. return true;
  15387. this._positions = [];
  15388. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15389. if (!data) {
  15390. return false;
  15391. }
  15392. for (var index = 0; index < data.length; index += 3) {
  15393. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15394. }
  15395. return true;
  15396. };
  15397. // Clone
  15398. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15399. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15400. };
  15401. // Dispose
  15402. Mesh.prototype.dispose = function (doNotRecurse) {
  15403. if (this._geometry) {
  15404. this._geometry.releaseForMesh(this, true);
  15405. }
  15406. // Instances
  15407. if (this._worldMatricesInstancesBuffer) {
  15408. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15409. this._worldMatricesInstancesBuffer = null;
  15410. }
  15411. while (this.instances.length) {
  15412. this.instances[0].dispose();
  15413. }
  15414. _super.prototype.dispose.call(this, doNotRecurse);
  15415. };
  15416. // Geometric tools
  15417. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15418. var _this = this;
  15419. var scene = this.getScene();
  15420. var onload = function (img) {
  15421. // Getting height map data
  15422. var canvas = document.createElement("canvas");
  15423. var context = canvas.getContext("2d");
  15424. var heightMapWidth = img.width;
  15425. var heightMapHeight = img.height;
  15426. canvas.width = heightMapWidth;
  15427. canvas.height = heightMapHeight;
  15428. context.drawImage(img, 0, 0);
  15429. // Create VertexData from map data
  15430. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15431. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15432. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15433. //execute success callback, if set
  15434. if (onSuccess) {
  15435. onSuccess(_this);
  15436. }
  15437. };
  15438. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15439. };
  15440. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15441. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15442. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15443. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15444. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15445. return;
  15446. }
  15447. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15448. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15449. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15450. var position = BABYLON.Vector3.Zero();
  15451. var normal = BABYLON.Vector3.Zero();
  15452. var uv = BABYLON.Vector2.Zero();
  15453. for (var index = 0; index < positions.length; index += 3) {
  15454. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15455. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15456. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15457. // Compute height
  15458. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15459. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15460. var pos = (u + v * heightMapWidth) * 4;
  15461. var r = buffer[pos] / 255.0;
  15462. var g = buffer[pos + 1] / 255.0;
  15463. var b = buffer[pos + 2] / 255.0;
  15464. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15465. normal.normalize();
  15466. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15467. position = position.add(normal);
  15468. position.toArray(positions, index);
  15469. }
  15470. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15471. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15472. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15473. };
  15474. Mesh.prototype.convertToFlatShadedMesh = function () {
  15475. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15476. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15477. var kinds = this.getVerticesDataKinds();
  15478. var vbs = [];
  15479. var data = [];
  15480. var newdata = [];
  15481. var updatableNormals = false;
  15482. var kindIndex;
  15483. var kind;
  15484. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15485. kind = kinds[kindIndex];
  15486. var vertexBuffer = this.getVertexBuffer(kind);
  15487. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15488. updatableNormals = vertexBuffer.isUpdatable();
  15489. kinds.splice(kindIndex, 1);
  15490. kindIndex--;
  15491. continue;
  15492. }
  15493. vbs[kind] = vertexBuffer;
  15494. data[kind] = vbs[kind].getData();
  15495. newdata[kind] = [];
  15496. }
  15497. // Save previous submeshes
  15498. var previousSubmeshes = this.subMeshes.slice(0);
  15499. var indices = this.getIndices();
  15500. var totalIndices = this.getTotalIndices();
  15501. // Generating unique vertices per face
  15502. var index;
  15503. for (index = 0; index < totalIndices; index++) {
  15504. var vertexIndex = indices[index];
  15505. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15506. kind = kinds[kindIndex];
  15507. var stride = vbs[kind].getStrideSize();
  15508. for (var offset = 0; offset < stride; offset++) {
  15509. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15510. }
  15511. }
  15512. }
  15513. // Updating faces & normal
  15514. var normals = [];
  15515. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15516. for (index = 0; index < totalIndices; index += 3) {
  15517. indices[index] = index;
  15518. indices[index + 1] = index + 1;
  15519. indices[index + 2] = index + 2;
  15520. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15521. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15522. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15523. var p1p2 = p1.subtract(p2);
  15524. var p3p2 = p3.subtract(p2);
  15525. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15526. // Store same normals for every vertex
  15527. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15528. normals.push(normal.x);
  15529. normals.push(normal.y);
  15530. normals.push(normal.z);
  15531. }
  15532. }
  15533. this.setIndices(indices);
  15534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15535. // Updating vertex buffers
  15536. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15537. kind = kinds[kindIndex];
  15538. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15539. }
  15540. // Updating submeshes
  15541. this.releaseSubMeshes();
  15542. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15543. var previousOne = previousSubmeshes[submeshIndex];
  15544. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15545. }
  15546. this.synchronizeInstances();
  15547. };
  15548. // will inverse faces orientations, and invert normals too if specified
  15549. Mesh.prototype.flipFaces = function (flipNormals) {
  15550. if (flipNormals === void 0) { flipNormals = false; }
  15551. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15552. var i;
  15553. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15554. for (i = 0; i < vertex_data.normals.length; i++) {
  15555. vertex_data.normals[i] *= -1;
  15556. }
  15557. }
  15558. var temp;
  15559. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15560. // reassign indices
  15561. temp = vertex_data.indices[i + 1];
  15562. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15563. vertex_data.indices[i + 2] = temp;
  15564. }
  15565. vertex_data.applyToMesh(this);
  15566. };
  15567. // Instances
  15568. Mesh.prototype.createInstance = function (name) {
  15569. return new BABYLON.InstancedMesh(name, this);
  15570. };
  15571. Mesh.prototype.synchronizeInstances = function () {
  15572. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15573. var instance = this.instances[instanceIndex];
  15574. instance._syncSubMeshes();
  15575. }
  15576. };
  15577. /**
  15578. * Simplify the mesh according to the given array of settings.
  15579. * Function will return immediately and will simplify async.
  15580. * @param settings a collection of simplification settings.
  15581. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15582. * @param type the type of simplification to run.
  15583. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15584. */
  15585. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15586. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15587. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15588. this.getScene().simplificationQueue.addTask({
  15589. settings: settings,
  15590. parallelProcessing: parallelProcessing,
  15591. mesh: this,
  15592. simplificationType: simplificationType,
  15593. successCallback: successCallback
  15594. });
  15595. };
  15596. /**
  15597. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15598. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15599. * This should be used together with the simplification to avoid disappearing triangles.
  15600. * @param successCallback an optional success callback to be called after the optimization finished.
  15601. */
  15602. Mesh.prototype.optimizeIndices = function (successCallback) {
  15603. var _this = this;
  15604. var indices = this.getIndices();
  15605. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15606. var vectorPositions = [];
  15607. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15608. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15609. }
  15610. var dupes = [];
  15611. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15612. var realPos = vectorPositions.length - 1 - iteration;
  15613. var testedPosition = vectorPositions[realPos];
  15614. for (var j = 0; j < realPos; ++j) {
  15615. var againstPosition = vectorPositions[j];
  15616. if (testedPosition.equals(againstPosition)) {
  15617. dupes[realPos] = j;
  15618. break;
  15619. }
  15620. }
  15621. }, function () {
  15622. for (var i = 0; i < indices.length; ++i) {
  15623. indices[i] = dupes[indices[i]] || indices[i];
  15624. }
  15625. //indices are now reordered
  15626. var originalSubMeshes = _this.subMeshes.slice(0);
  15627. _this.setIndices(indices);
  15628. _this.subMeshes = originalSubMeshes;
  15629. if (successCallback) {
  15630. successCallback(_this);
  15631. }
  15632. });
  15633. };
  15634. Mesh.CreateRibbon = function (name, options, closeArrayOrScene, closePath, offset, scene, updatable, sideOrientation, instance) {
  15635. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15636. if (instance === void 0) { instance = null; }
  15637. var pathArray;
  15638. var closeArray;
  15639. if (Array.isArray(options)) {
  15640. pathArray = options;
  15641. closeArray = closeArrayOrScene;
  15642. if (!instance) {
  15643. options = {
  15644. pathArray: pathArray,
  15645. closeArray: closeArray,
  15646. closePath: closePath,
  15647. offset: offset,
  15648. updatable: updatable,
  15649. sideOrientation: sideOrientation
  15650. };
  15651. }
  15652. }
  15653. else {
  15654. scene = closeArrayOrScene;
  15655. pathArray = options.pathArray;
  15656. closeArray = options.closeArray;
  15657. closePath = options.closePath;
  15658. offset = options.offset;
  15659. sideOrientation = options.sideOrientation;
  15660. instance = options.instance;
  15661. updatable = options.updatable;
  15662. }
  15663. if (instance) {
  15664. // positionFunction : ribbon case
  15665. // only pathArray and sideOrientation parameters are taken into account for positions update
  15666. var positionFunction = function (positions) {
  15667. var minlg = pathArray[0].length;
  15668. var i = 0;
  15669. var ns = (instance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15670. for (var si = 1; si <= ns; si++) {
  15671. for (var p = 0; p < pathArray.length; p++) {
  15672. var path = pathArray[p];
  15673. var l = path.length;
  15674. minlg = (minlg < l) ? minlg : l;
  15675. var j = 0;
  15676. while (j < minlg) {
  15677. positions[i] = path[j].x;
  15678. positions[i + 1] = path[j].y;
  15679. positions[i + 2] = path[j].z;
  15680. j++;
  15681. i += 3;
  15682. }
  15683. if (instance._closePath) {
  15684. positions[i] = path[0].x;
  15685. positions[i + 1] = path[0].y;
  15686. positions[i + 2] = path[0].z;
  15687. i += 3;
  15688. }
  15689. }
  15690. }
  15691. };
  15692. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15693. positionFunction(positions);
  15694. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15695. if (!(instance.areNormalsFrozen)) {
  15696. var indices = instance.getIndices();
  15697. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15698. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15699. if (instance._closePath) {
  15700. var indexFirst = 0;
  15701. var indexLast = 0;
  15702. for (var p = 0; p < pathArray.length; p++) {
  15703. indexFirst = instance._idx[p] * 3;
  15704. if (p + 1 < pathArray.length) {
  15705. indexLast = (instance._idx[p + 1] - 1) * 3;
  15706. }
  15707. else {
  15708. indexLast = normals.length - 3;
  15709. }
  15710. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15711. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15712. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15713. normals[indexLast] = normals[indexFirst];
  15714. normals[indexLast + 1] = normals[indexFirst + 1];
  15715. normals[indexLast + 2] = normals[indexFirst + 2];
  15716. }
  15717. }
  15718. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15719. }
  15720. return instance;
  15721. }
  15722. else {
  15723. var ribbon = new Mesh(name, scene);
  15724. ribbon.sideOrientation = sideOrientation;
  15725. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15726. if (closePath) {
  15727. ribbon._idx = vertexData._idx;
  15728. }
  15729. ribbon._closePath = closePath;
  15730. ribbon._closeArray = closeArray;
  15731. vertexData.applyToMesh(ribbon, updatable);
  15732. return ribbon;
  15733. }
  15734. };
  15735. Mesh.CreateDisc = function (name, options, tessellationOrScene, scene, updatable, sideOrientation) {
  15736. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15737. if (tessellationOrScene instanceof BABYLON.Scene) {
  15738. scene = tessellationOrScene;
  15739. }
  15740. else {
  15741. var radius = options;
  15742. options = {
  15743. radius: radius,
  15744. tessellation: tessellationOrScene,
  15745. sideOrientation: sideOrientation
  15746. };
  15747. }
  15748. var disc = new Mesh(name, scene);
  15749. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15750. vertexData.applyToMesh(disc, updatable || options.updatable);
  15751. return disc;
  15752. };
  15753. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15754. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15755. // Check parameters
  15756. updatable = updatable || options.updatable;
  15757. if (typeof options === 'number') {
  15758. var size = options;
  15759. options = {
  15760. size: size,
  15761. sideOrientation: sideOrientation
  15762. };
  15763. }
  15764. var box = new Mesh(name, scene);
  15765. var vertexData = BABYLON.VertexData.CreateBox(options);
  15766. vertexData.applyToMesh(box, updatable);
  15767. return box;
  15768. };
  15769. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15770. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15771. if (diameterOrScene instanceof BABYLON.Scene) {
  15772. scene = diameterOrScene;
  15773. updatable = options.updatable;
  15774. }
  15775. else {
  15776. var segments = options;
  15777. options = {
  15778. segments: segments,
  15779. diameterX: diameterOrScene,
  15780. diameterY: diameterOrScene,
  15781. diameterZ: diameterOrScene,
  15782. sideOrientation: sideOrientation
  15783. };
  15784. }
  15785. var sphere = new Mesh(name, scene);
  15786. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15787. vertexData.applyToMesh(sphere, updatable);
  15788. return sphere;
  15789. };
  15790. Mesh.CreateCylinder = function (name, options, diameterTopOrScene, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15791. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15792. if (diameterTopOrScene instanceof BABYLON.Scene) {
  15793. scene = diameterTopOrScene;
  15794. updatable = options.updatable;
  15795. }
  15796. else {
  15797. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15798. if (scene !== undefined) {
  15799. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  15800. updatable = scene;
  15801. }
  15802. scene = subdivisions;
  15803. subdivisions = 1;
  15804. }
  15805. var height = options;
  15806. options = {
  15807. height: height,
  15808. diameterTop: diameterTopOrScene,
  15809. diameterBottom: diameterBottom,
  15810. tessellation: tessellation,
  15811. subdivisions: subdivisions,
  15812. sideOrientation: sideOrientation
  15813. };
  15814. }
  15815. var cylinder = new Mesh(name, scene);
  15816. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15817. vertexData.applyToMesh(cylinder, updatable);
  15818. return cylinder;
  15819. };
  15820. Mesh.CreateTorus = function (name, options, thicknessOrScene, tessellation, scene, updatable, sideOrientation) {
  15821. if (thicknessOrScene instanceof BABYLON.Scene) {
  15822. scene = thicknessOrScene;
  15823. updatable = options.updatable;
  15824. }
  15825. else {
  15826. var diameter = options;
  15827. options = {
  15828. diameter: diameter,
  15829. thickness: thicknessOrScene,
  15830. tessellation: tessellation,
  15831. sideOrientation: sideOrientation
  15832. };
  15833. }
  15834. var torus = new Mesh(name, scene);
  15835. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15836. vertexData.applyToMesh(torus, updatable);
  15837. return torus;
  15838. };
  15839. Mesh.CreateTorusKnot = function (name, options, tubeOrScene, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15840. if (tubeOrScene instanceof BABYLON.Scene) {
  15841. scene = tubeOrScene;
  15842. updatable = options.updatable;
  15843. }
  15844. else {
  15845. var radius = options;
  15846. options = {
  15847. radius: radius,
  15848. tube: tubeOrScene,
  15849. radialSegments: radialSegments,
  15850. tubularSegments: tubularSegments,
  15851. p: p,
  15852. q: q,
  15853. sideOrientation: sideOrientation
  15854. };
  15855. }
  15856. var torusKnot = new Mesh(name, scene);
  15857. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15858. vertexData.applyToMesh(torusKnot, updatable);
  15859. return torusKnot;
  15860. };
  15861. Mesh.CreateLines = function (name, options, scene, updatable, instance) {
  15862. var points;
  15863. if (Array.isArray(options)) {
  15864. points = options;
  15865. if (!instance) {
  15866. options = {
  15867. points: points
  15868. };
  15869. }
  15870. }
  15871. else {
  15872. instance = options.instance;
  15873. points = options.points;
  15874. }
  15875. if (instance) {
  15876. var positionFunction = function (positions) {
  15877. var i = 0;
  15878. for (var p = 0; p < points.length; p++) {
  15879. positions[i] = points[p].x;
  15880. positions[i + 1] = points[p].y;
  15881. positions[i + 2] = points[p].z;
  15882. i += 3;
  15883. }
  15884. };
  15885. instance.updateMeshPositions(positionFunction, false);
  15886. return instance;
  15887. }
  15888. // lines creation
  15889. var lines = new BABYLON.LinesMesh(name, scene);
  15890. var vertexData = BABYLON.VertexData.CreateLines(options);
  15891. vertexData.applyToMesh(lines, updatable || options.updatable);
  15892. return lines;
  15893. };
  15894. Mesh.CreateDashedLines = function (name, options, dashSizeOrScene, gapSize, dashNb, scene, updatable, instance) {
  15895. var points;
  15896. var dashSize;
  15897. if (Array.isArray(options)) {
  15898. points = options;
  15899. dashSize = dashSizeOrScene;
  15900. if (!instance) {
  15901. options = {
  15902. points: points,
  15903. dashSize: dashSize,
  15904. gapSize: gapSize,
  15905. dashNb: dashNb
  15906. };
  15907. }
  15908. }
  15909. else {
  15910. scene = dashSizeOrScene,
  15911. points = options.points;
  15912. instance = options.instance;
  15913. gapSize = options.gapSize;
  15914. dashNb = options.dashNb;
  15915. dashSize = options.dashSize;
  15916. }
  15917. if (instance) {
  15918. var positionFunction = function (positions) {
  15919. var curvect = BABYLON.Vector3.Zero();
  15920. var nbSeg = positions.length / 6;
  15921. var lg = 0;
  15922. var nb = 0;
  15923. var shft = 0;
  15924. var dashshft = 0;
  15925. var curshft = 0;
  15926. var p = 0;
  15927. var i = 0;
  15928. var j = 0;
  15929. for (i = 0; i < points.length - 1; i++) {
  15930. points[i + 1].subtractToRef(points[i], curvect);
  15931. lg += curvect.length();
  15932. }
  15933. shft = lg / nbSeg;
  15934. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15935. for (i = 0; i < points.length - 1; i++) {
  15936. points[i + 1].subtractToRef(points[i], curvect);
  15937. nb = Math.floor(curvect.length() / shft);
  15938. curvect.normalize();
  15939. j = 0;
  15940. while (j < nb && p < positions.length) {
  15941. curshft = shft * j;
  15942. positions[p] = points[i].x + curshft * curvect.x;
  15943. positions[p + 1] = points[i].y + curshft * curvect.y;
  15944. positions[p + 2] = points[i].z + curshft * curvect.z;
  15945. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15946. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15947. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15948. p += 6;
  15949. j++;
  15950. }
  15951. }
  15952. while (p < positions.length) {
  15953. positions[p] = points[i].x;
  15954. positions[p + 1] = points[i].y;
  15955. positions[p + 2] = points[i].z;
  15956. p += 3;
  15957. }
  15958. };
  15959. instance.updateMeshPositions(positionFunction, false);
  15960. return instance;
  15961. }
  15962. // dashed lines creation
  15963. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15964. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15965. vertexData.applyToMesh(dashedLines, updatable || options.updatable);
  15966. dashedLines.dashSize = dashSize;
  15967. dashedLines.gapSize = gapSize;
  15968. return dashedLines;
  15969. };
  15970. Mesh.ExtrudeShape = function (name, options, pathOrScene, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15971. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15972. if (instance === void 0) { instance = null; }
  15973. var path;
  15974. var shape;
  15975. if (Array.isArray(options)) {
  15976. shape = options;
  15977. path = pathOrScene;
  15978. scale = scale || 1;
  15979. rotation = rotation || 0;
  15980. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  15981. }
  15982. else {
  15983. scene = pathOrScene;
  15984. path = options.path;
  15985. shape = options.shape;
  15986. scale = options.scale || 1;
  15987. rotation = options.rotation || 0;
  15988. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  15989. updatable = options.updatable;
  15990. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  15991. instance = options.instance;
  15992. }
  15993. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15994. return extruded;
  15995. };
  15996. Mesh.ExtrudeShapeCustom = function (name, options, pathOrScene, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15997. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15998. if (instance === void 0) { instance = null; }
  15999. var path;
  16000. var shape;
  16001. if (Array.isArray(options)) {
  16002. shape = options;
  16003. path = pathOrScene;
  16004. ribbonCloseArray = ribbonCloseArray || false;
  16005. ribbonClosePath = ribbonClosePath || false;
  16006. cap = (cap === 0) ? 0 : cap || Mesh.NO_CAP;
  16007. }
  16008. else {
  16009. scene = pathOrScene;
  16010. path = options.path;
  16011. shape = options.shape;
  16012. scaleFunction = options.scaleFunction || (function (i, distance) { return 1; });
  16013. rotationFunction = options.rotationFunction || (function (i, distance) { return 0; });
  16014. ribbonCloseArray = options.ribbonCloseArray || false;
  16015. ribbonClosePath = options.ribbonClosePath || false;
  16016. cap = (options.cap === 0) ? 0 : options.cap || Mesh.NO_CAP;
  16017. updatable = options.updatable;
  16018. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16019. instance = options.instance;
  16020. }
  16021. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16022. return extrudedCustom;
  16023. };
  16024. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16025. // extrusion geometry
  16026. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16027. var tangents = path3D.getTangents();
  16028. var normals = path3D.getNormals();
  16029. var binormals = path3D.getBinormals();
  16030. var distances = path3D.getDistances();
  16031. var angle = 0;
  16032. var returnScale = function (i, distance) { return scale; };
  16033. var returnRotation = function (i, distance) { return rotation; };
  16034. var rotate = custom ? rotateFunction : returnRotation;
  16035. var scl = custom ? scaleFunction : returnScale;
  16036. var index = (cap === Mesh.NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16037. var rotationMatrix = BABYLON.Matrix.Zero();
  16038. for (var i = 0; i < curve.length; i++) {
  16039. var shapePath = new Array();
  16040. var angleStep = rotate(i, distances[i]);
  16041. var scaleRatio = scl(i, distances[i]);
  16042. for (var p = 0; p < shape.length; p++) {
  16043. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16044. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16045. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16046. shapePath.push(rotated);
  16047. }
  16048. shapePaths[index] = shapePath;
  16049. angle += angleStep;
  16050. index++;
  16051. }
  16052. // cap
  16053. var capPath = function (shapePath) {
  16054. var pointCap = Array();
  16055. var barycenter = BABYLON.Vector3.Zero();
  16056. var i;
  16057. for (i = 0; i < shapePath.length; i++) {
  16058. barycenter.addInPlace(shapePath[i]);
  16059. }
  16060. barycenter.scaleInPlace(1 / shapePath.length);
  16061. for (i = 0; i < shapePath.length; i++) {
  16062. pointCap.push(barycenter);
  16063. }
  16064. return pointCap;
  16065. };
  16066. switch (cap) {
  16067. case Mesh.NO_CAP:
  16068. break;
  16069. case Mesh.CAP_START:
  16070. shapePaths[0] = capPath(shapePaths[2]);
  16071. shapePaths[1] = shapePaths[2].slice(0);
  16072. break;
  16073. case Mesh.CAP_END:
  16074. shapePaths[index] = shapePaths[index - 1];
  16075. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16076. break;
  16077. case Mesh.CAP_ALL:
  16078. shapePaths[0] = capPath(shapePaths[2]);
  16079. shapePaths[1] = shapePaths[2].slice(0);
  16080. shapePaths[index] = shapePaths[index - 1];
  16081. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16082. break;
  16083. default:
  16084. break;
  16085. }
  16086. return shapePaths;
  16087. };
  16088. var path3D;
  16089. var pathArray;
  16090. if (instance) {
  16091. path3D = (instance.path3D).update(curve);
  16092. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16093. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16094. return instance;
  16095. }
  16096. // extruded shape creation
  16097. path3D = new BABYLON.Path3D(curve);
  16098. var newShapePaths = new Array();
  16099. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16100. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16101. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16102. extrudedGeneric.pathArray = pathArray;
  16103. extrudedGeneric.path3D = path3D;
  16104. extrudedGeneric.cap = cap;
  16105. return extrudedGeneric;
  16106. };
  16107. Mesh.CreateLathe = function (name, options, radiusOrScene, tessellation, scene, updatable, sideOrientation) {
  16108. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16109. var shape;
  16110. var radius;
  16111. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  16112. var closed = (options.closed === undefined) ? true : options.closed;
  16113. if (Array.isArray(options)) {
  16114. shape = options;
  16115. radius = radiusOrScene || 1;
  16116. tessellation = tessellation || 64;
  16117. }
  16118. else {
  16119. scene = radiusOrScene;
  16120. shape = options.shape;
  16121. radius = options.radius || 1;
  16122. tessellation = options.tessellation || 64;
  16123. updatable = options.updatable;
  16124. sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || Mesh.DEFAULTSIDE;
  16125. }
  16126. var pi2 = Math.PI * 2;
  16127. var shapeLathe = new Array();
  16128. // first rotatable point
  16129. var i = 0;
  16130. while (shape[i].x === 0) {
  16131. i++;
  16132. }
  16133. var pt = shape[i];
  16134. for (i = 0; i < shape.length; i++) {
  16135. shapeLathe.push(shape[i].subtract(pt));
  16136. }
  16137. // circle path
  16138. var step = pi2 / tessellation * arc;
  16139. var rotated;
  16140. var path = new Array();
  16141. ;
  16142. for (i = 0; i <= tessellation; i++) {
  16143. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  16144. path.push(rotated);
  16145. }
  16146. if (closed) {
  16147. path.push(path[0]);
  16148. }
  16149. // extrusion
  16150. var scaleFunction = function () { return 1; };
  16151. var rotateFunction = function () { return 0; };
  16152. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  16153. return lathe;
  16154. };
  16155. Mesh.CreatePlane = function (name, options, scene, updatable, sideOrientation) {
  16156. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16157. if (typeof options === 'number') {
  16158. var size = options;
  16159. options = {
  16160. size: size,
  16161. width: size,
  16162. height: size,
  16163. sideOrientation: sideOrientation
  16164. };
  16165. }
  16166. var plane = new Mesh(name, scene);
  16167. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16168. vertexData.applyToMesh(plane, updatable || options.updatable);
  16169. return plane;
  16170. };
  16171. Mesh.CreateGround = function (name, options, heightOrScene, subdivisions, scene, updatable) {
  16172. if (heightOrScene instanceof BABYLON.Scene) {
  16173. scene = heightOrScene;
  16174. updatable = options.updatable;
  16175. }
  16176. else {
  16177. var width = options;
  16178. options = {
  16179. width: width,
  16180. height: heightOrScene,
  16181. subdivisions: subdivisions
  16182. };
  16183. }
  16184. var ground = new BABYLON.GroundMesh(name, scene);
  16185. ground._setReady(false);
  16186. ground._subdivisions = options.subdivisions || 1;
  16187. var vertexData = BABYLON.VertexData.CreateGround(options);
  16188. vertexData.applyToMesh(ground, updatable || options.updatable);
  16189. ground._setReady(true);
  16190. return ground;
  16191. };
  16192. Mesh.CreateTiledGround = function (name, options, zminOrScene, xmax, zmax, subdivisions, precision, scene, updatable) {
  16193. var xmin;
  16194. var zmin;
  16195. if (typeof options === 'number') {
  16196. xmin = options || -1;
  16197. zmin = zminOrScene || -1;
  16198. xmax = xmax || 1;
  16199. zmax = zmax || 1;
  16200. subdivisions = subdivisions || { w: 6, h: 6 };
  16201. precision = precision || { w: 2, h: 2 };
  16202. }
  16203. else {
  16204. scene = zminOrScene;
  16205. xmin = options.xmin || -1;
  16206. zmin = options.zmin || -1;
  16207. xmax = options.xmax || 1;
  16208. zmax = options.zmax || 1;
  16209. subdivisions = options.subdivisions || { w: 6, h: 6 };
  16210. precision = options.precision || { w: 2, h: 2 };
  16211. }
  16212. var tiledGround = new Mesh(name, scene);
  16213. var vertexData = BABYLON.VertexData.CreateTiledGround({ xmin: xmin, zmin: zmin, xmax: xmax, zmax: zmax, subdivisions: subdivisions, precision: precision });
  16214. vertexData.applyToMesh(tiledGround, updatable);
  16215. return tiledGround;
  16216. };
  16217. Mesh.CreateGroundFromHeightMap = function (name, url, widthOrOptions, heightorScene, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16218. var width;
  16219. var height;
  16220. if (typeof widthOrOptions === "number") {
  16221. width = widthOrOptions;
  16222. height = heightorScene;
  16223. }
  16224. else {
  16225. width = widthOrOptions.width || 10;
  16226. height = widthOrOptions.height || 10;
  16227. subdivisions = widthOrOptions.subdivisions || 1;
  16228. minHeight = widthOrOptions.minHeight;
  16229. maxHeight = widthOrOptions.maxHeight || 10;
  16230. updatable = widthOrOptions.updatable;
  16231. onReady = widthOrOptions.onReady;
  16232. scene = heightorScene;
  16233. }
  16234. var ground = new BABYLON.GroundMesh(name, scene);
  16235. ground._subdivisions = subdivisions;
  16236. ground._setReady(false);
  16237. var onload = function (img) {
  16238. // Getting height map data
  16239. var canvas = document.createElement("canvas");
  16240. var context = canvas.getContext("2d");
  16241. var bufferWidth = img.width;
  16242. var bufferHeight = img.height;
  16243. canvas.width = bufferWidth;
  16244. canvas.height = bufferHeight;
  16245. context.drawImage(img, 0, 0);
  16246. // Create VertexData from map data
  16247. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16248. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16249. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16250. width: width, height: height,
  16251. subdivisions: subdivisions,
  16252. minHeight: minHeight, maxHeight: maxHeight,
  16253. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16254. });
  16255. vertexData.applyToMesh(ground, updatable);
  16256. ground._setReady(true);
  16257. //execute ready callback, if set
  16258. if (onReady) {
  16259. onReady(ground);
  16260. }
  16261. };
  16262. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16263. return ground;
  16264. };
  16265. Mesh.CreateTube = function (name, options, radiusOrScene, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16266. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  16267. if (instance === void 0) { instance = null; }
  16268. var path;
  16269. var radius;
  16270. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  16271. ;
  16272. if (Array.isArray(options)) {
  16273. path = options;
  16274. radius = radiusOrScene;
  16275. }
  16276. else {
  16277. scene = radiusOrScene;
  16278. path = options.path;
  16279. radius = options.radius || 1;
  16280. tessellation = options.tessellation || 64;
  16281. radiusFunction = options.radiusFunction;
  16282. cap = options.cap || Mesh.NO_CAP,
  16283. updatable = options.updatable;
  16284. sideOrientation = options.sideOrientation || Mesh.DEFAULTSIDE,
  16285. instance = options.instance;
  16286. }
  16287. // tube geometry
  16288. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16289. var tangents = path3D.getTangents();
  16290. var normals = path3D.getNormals();
  16291. var distances = path3D.getDistances();
  16292. var pi2 = Math.PI * 2;
  16293. var step = pi2 / tessellation * arc;
  16294. var returnRadius = function (i, distance) { return radius; };
  16295. var radiusFunctionFinal = radiusFunction || returnRadius;
  16296. var circlePath;
  16297. var rad;
  16298. var normal;
  16299. var rotated;
  16300. var rotationMatrix = BABYLON.Matrix.Zero();
  16301. var index = (cap === Mesh._NO_CAP || cap === Mesh.CAP_END) ? 0 : 2;
  16302. for (var i = 0; i < path.length; i++) {
  16303. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16304. circlePath = Array(); // current circle array
  16305. normal = normals[i]; // current normal
  16306. for (var t = 0; t < tessellation; t++) {
  16307. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16308. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  16309. circlePath.push(rotated);
  16310. }
  16311. circlePaths[index] = circlePath;
  16312. index++;
  16313. }
  16314. // cap
  16315. var capPath = function (nbPoints, pathIndex) {
  16316. var pointCap = Array();
  16317. for (var i = 0; i < nbPoints; i++) {
  16318. pointCap.push(path[pathIndex]);
  16319. }
  16320. return pointCap;
  16321. };
  16322. switch (cap) {
  16323. case Mesh.NO_CAP:
  16324. break;
  16325. case Mesh.CAP_START:
  16326. circlePaths[0] = capPath(tessellation, 0);
  16327. circlePaths[1] = circlePaths[2].slice(0);
  16328. break;
  16329. case Mesh.CAP_END:
  16330. circlePaths[index] = circlePaths[index - 1].slice(0);
  16331. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16332. break;
  16333. case Mesh.CAP_ALL:
  16334. circlePaths[0] = capPath(tessellation, 0);
  16335. circlePaths[1] = circlePaths[2].slice(0);
  16336. circlePaths[index] = circlePaths[index - 1].slice(0);
  16337. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  16338. break;
  16339. default:
  16340. break;
  16341. }
  16342. return circlePaths;
  16343. };
  16344. var path3D;
  16345. var pathArray;
  16346. if (instance) {
  16347. arc = arc || instance.arc;
  16348. path3D = (instance.path3D).update(path);
  16349. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  16350. instance = Mesh.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  16351. instance.path3D = path3D;
  16352. instance.pathArray = pathArray;
  16353. instance.arc = arc;
  16354. return instance;
  16355. }
  16356. // tube creation
  16357. path3D = new BABYLON.Path3D(path);
  16358. var newPathArray = new Array();
  16359. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16360. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, arc);
  16361. var tube = Mesh.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  16362. tube.pathArray = pathArray;
  16363. tube.path3D = path3D;
  16364. tube.tessellation = tessellation;
  16365. tube.cap = cap;
  16366. tube.arc = arc;
  16367. return tube;
  16368. };
  16369. Mesh.CreateDecal = function (name, sourceMesh, positionOrOptions, normal, size, angle) {
  16370. if (angle === void 0) { angle = 0; }
  16371. var indices = sourceMesh.getIndices();
  16372. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16373. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16374. var position;
  16375. if (positionOrOptions instanceof BABYLON.Vector3) {
  16376. position = positionOrOptions;
  16377. }
  16378. else {
  16379. position = positionOrOptions.position || BABYLON.Vector3.Zero();
  16380. normal = positionOrOptions.normal || BABYLON.Vector3.Up();
  16381. size = positionOrOptions.size || new BABYLON.Vector3(1, 1, 1);
  16382. angle = positionOrOptions.angle;
  16383. }
  16384. // Getting correct rotation
  16385. if (!normal) {
  16386. var target = new BABYLON.Vector3(0, 0, 1);
  16387. var camera = sourceMesh.getScene().activeCamera;
  16388. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16389. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16390. }
  16391. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16392. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16393. var pitch = Math.atan2(normal.y, len);
  16394. // Matrix
  16395. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16396. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16397. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16398. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16399. var vertexData = new BABYLON.VertexData();
  16400. vertexData.indices = [];
  16401. vertexData.positions = [];
  16402. vertexData.normals = [];
  16403. vertexData.uvs = [];
  16404. var currentVertexDataIndex = 0;
  16405. var extractDecalVector3 = function (indexId) {
  16406. var vertexId = indices[indexId];
  16407. var result = new BABYLON.PositionNormalVertex();
  16408. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16409. // Send vector to decal local world
  16410. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16411. // Get normal
  16412. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16413. return result;
  16414. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16415. var clip = function (vertices, axis) {
  16416. if (vertices.length === 0) {
  16417. return vertices;
  16418. }
  16419. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16420. var clipVertices = function (v0, v1) {
  16421. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16422. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16423. };
  16424. var result = new Array();
  16425. for (var index = 0; index < vertices.length; index += 3) {
  16426. var v1Out;
  16427. var v2Out;
  16428. var v3Out;
  16429. var total = 0;
  16430. var nV1, nV2, nV3, nV4;
  16431. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16432. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16433. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16434. v1Out = d1 > 0;
  16435. v2Out = d2 > 0;
  16436. v3Out = d3 > 0;
  16437. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16438. switch (total) {
  16439. case 0:
  16440. result.push(vertices[index]);
  16441. result.push(vertices[index + 1]);
  16442. result.push(vertices[index + 2]);
  16443. break;
  16444. case 1:
  16445. if (v1Out) {
  16446. nV1 = vertices[index + 1];
  16447. nV2 = vertices[index + 2];
  16448. nV3 = clipVertices(vertices[index], nV1);
  16449. nV4 = clipVertices(vertices[index], nV2);
  16450. }
  16451. if (v2Out) {
  16452. nV1 = vertices[index];
  16453. nV2 = vertices[index + 2];
  16454. nV3 = clipVertices(vertices[index + 1], nV1);
  16455. nV4 = clipVertices(vertices[index + 1], nV2);
  16456. result.push(nV3);
  16457. result.push(nV2.clone());
  16458. result.push(nV1.clone());
  16459. result.push(nV2.clone());
  16460. result.push(nV3.clone());
  16461. result.push(nV4);
  16462. break;
  16463. }
  16464. if (v3Out) {
  16465. nV1 = vertices[index];
  16466. nV2 = vertices[index + 1];
  16467. nV3 = clipVertices(vertices[index + 2], nV1);
  16468. nV4 = clipVertices(vertices[index + 2], nV2);
  16469. }
  16470. result.push(nV1.clone());
  16471. result.push(nV2.clone());
  16472. result.push(nV3);
  16473. result.push(nV4);
  16474. result.push(nV3.clone());
  16475. result.push(nV2.clone());
  16476. break;
  16477. case 2:
  16478. if (!v1Out) {
  16479. nV1 = vertices[index].clone();
  16480. nV2 = clipVertices(nV1, vertices[index + 1]);
  16481. nV3 = clipVertices(nV1, vertices[index + 2]);
  16482. result.push(nV1);
  16483. result.push(nV2);
  16484. result.push(nV3);
  16485. }
  16486. if (!v2Out) {
  16487. nV1 = vertices[index + 1].clone();
  16488. nV2 = clipVertices(nV1, vertices[index + 2]);
  16489. nV3 = clipVertices(nV1, vertices[index]);
  16490. result.push(nV1);
  16491. result.push(nV2);
  16492. result.push(nV3);
  16493. }
  16494. if (!v3Out) {
  16495. nV1 = vertices[index + 2].clone();
  16496. nV2 = clipVertices(nV1, vertices[index]);
  16497. nV3 = clipVertices(nV1, vertices[index + 1]);
  16498. result.push(nV1);
  16499. result.push(nV2);
  16500. result.push(nV3);
  16501. }
  16502. break;
  16503. case 3:
  16504. break;
  16505. }
  16506. }
  16507. return result;
  16508. };
  16509. for (var index = 0; index < indices.length; index += 3) {
  16510. var faceVertices = new Array();
  16511. faceVertices.push(extractDecalVector3(index));
  16512. faceVertices.push(extractDecalVector3(index + 1));
  16513. faceVertices.push(extractDecalVector3(index + 2));
  16514. // Clip
  16515. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16516. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16517. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16518. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16519. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16520. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16521. if (faceVertices.length === 0) {
  16522. continue;
  16523. }
  16524. // Add UVs and get back to world
  16525. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16526. var vertex = faceVertices[vIndex];
  16527. vertexData.indices.push(currentVertexDataIndex);
  16528. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16529. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16530. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16531. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16532. currentVertexDataIndex++;
  16533. }
  16534. }
  16535. // Return mesh
  16536. var decal = new Mesh(name, sourceMesh.getScene());
  16537. vertexData.applyToMesh(decal);
  16538. decal.position = position.clone();
  16539. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16540. return decal;
  16541. };
  16542. // Skeletons
  16543. /**
  16544. * Update the vertex buffers by applying transformation from the bones
  16545. * @param {skeleton} skeleton to apply
  16546. */
  16547. Mesh.prototype.applySkeleton = function (skeleton) {
  16548. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16549. return this;
  16550. }
  16551. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16552. return this;
  16553. }
  16554. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16555. return this;
  16556. }
  16557. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16558. return this;
  16559. }
  16560. var source;
  16561. if (!this._sourcePositions) {
  16562. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16563. this._sourcePositions = new Float32Array(source);
  16564. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16565. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16566. }
  16567. }
  16568. if (!this._sourceNormals) {
  16569. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16570. this._sourceNormals = new Float32Array(source);
  16571. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16572. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16573. }
  16574. }
  16575. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16576. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16577. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16578. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16579. var skeletonMatrices = skeleton.getTransformMatrices();
  16580. var tempVector3 = BABYLON.Vector3.Zero();
  16581. var finalMatrix = new BABYLON.Matrix();
  16582. var tempMatrix = new BABYLON.Matrix();
  16583. for (var index = 0; index < positionsData.length; index += 3) {
  16584. var index4 = (index / 3) * 4;
  16585. var matricesWeight0 = matricesWeightsData[index4];
  16586. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16587. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16588. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16589. if (matricesWeight0 > 0) {
  16590. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16591. finalMatrix.addToSelf(tempMatrix);
  16592. }
  16593. if (matricesWeight1 > 0) {
  16594. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16595. finalMatrix.addToSelf(tempMatrix);
  16596. }
  16597. if (matricesWeight2 > 0) {
  16598. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16599. finalMatrix.addToSelf(tempMatrix);
  16600. }
  16601. if (matricesWeight3 > 0) {
  16602. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16603. finalMatrix.addToSelf(tempMatrix);
  16604. }
  16605. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16606. tempVector3.toArray(positionsData, index);
  16607. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16608. tempVector3.toArray(normalsData, index);
  16609. finalMatrix.reset();
  16610. }
  16611. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16612. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16613. return this;
  16614. };
  16615. // Tools
  16616. Mesh.MinMax = function (meshes) {
  16617. var minVector = null;
  16618. var maxVector = null;
  16619. for (var i in meshes) {
  16620. var mesh = meshes[i];
  16621. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16622. if (!minVector) {
  16623. minVector = boundingBox.minimumWorld;
  16624. maxVector = boundingBox.maximumWorld;
  16625. continue;
  16626. }
  16627. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16628. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16629. }
  16630. return {
  16631. min: minVector,
  16632. max: maxVector
  16633. };
  16634. };
  16635. Mesh.Center = function (meshesOrMinMaxVector) {
  16636. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16637. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16638. };
  16639. /**
  16640. * Merge the array of meshes into a single mesh for performance reasons.
  16641. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16642. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16643. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16644. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16645. */
  16646. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16647. if (disposeSource === void 0) { disposeSource = true; }
  16648. var index;
  16649. if (!allow32BitsIndices) {
  16650. var totalVertices = 0;
  16651. // Counting vertices
  16652. for (index = 0; index < meshes.length; index++) {
  16653. if (meshes[index]) {
  16654. totalVertices += meshes[index].getTotalVertices();
  16655. if (totalVertices > 65536) {
  16656. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16657. return null;
  16658. }
  16659. }
  16660. }
  16661. }
  16662. // Merge
  16663. var vertexData;
  16664. var otherVertexData;
  16665. var source;
  16666. for (index = 0; index < meshes.length; index++) {
  16667. if (meshes[index]) {
  16668. meshes[index].computeWorldMatrix(true);
  16669. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16670. otherVertexData.transform(meshes[index].getWorldMatrix());
  16671. if (vertexData) {
  16672. vertexData.merge(otherVertexData);
  16673. }
  16674. else {
  16675. vertexData = otherVertexData;
  16676. source = meshes[index];
  16677. }
  16678. }
  16679. }
  16680. if (!meshSubclass) {
  16681. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16682. }
  16683. vertexData.applyToMesh(meshSubclass);
  16684. // Setting properties
  16685. meshSubclass.material = source.material;
  16686. meshSubclass.checkCollisions = source.checkCollisions;
  16687. // Cleaning
  16688. if (disposeSource) {
  16689. for (index = 0; index < meshes.length; index++) {
  16690. if (meshes[index]) {
  16691. meshes[index].dispose();
  16692. }
  16693. }
  16694. }
  16695. return meshSubclass;
  16696. };
  16697. // Consts
  16698. Mesh._FRONTSIDE = 0;
  16699. Mesh._BACKSIDE = 1;
  16700. Mesh._DOUBLESIDE = 2;
  16701. Mesh._DEFAULTSIDE = 0;
  16702. Mesh._NO_CAP = 0;
  16703. Mesh._CAP_START = 1;
  16704. Mesh._CAP_END = 2;
  16705. Mesh._CAP_ALL = 3;
  16706. return Mesh;
  16707. })(BABYLON.AbstractMesh);
  16708. BABYLON.Mesh = Mesh;
  16709. })(BABYLON || (BABYLON = {}));
  16710. var BABYLON;
  16711. (function (BABYLON) {
  16712. var SubMesh = (function () {
  16713. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16714. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16715. this.materialIndex = materialIndex;
  16716. this.verticesStart = verticesStart;
  16717. this.verticesCount = verticesCount;
  16718. this.indexStart = indexStart;
  16719. this.indexCount = indexCount;
  16720. this._renderId = 0;
  16721. this._mesh = mesh;
  16722. this._renderingMesh = renderingMesh || mesh;
  16723. mesh.subMeshes.push(this);
  16724. this._trianglePlanes = [];
  16725. this._id = mesh.subMeshes.length - 1;
  16726. if (createBoundingBox) {
  16727. this.refreshBoundingInfo();
  16728. mesh.computeWorldMatrix(true);
  16729. }
  16730. }
  16731. SubMesh.prototype.getBoundingInfo = function () {
  16732. return this._boundingInfo;
  16733. };
  16734. SubMesh.prototype.getMesh = function () {
  16735. return this._mesh;
  16736. };
  16737. SubMesh.prototype.getRenderingMesh = function () {
  16738. return this._renderingMesh;
  16739. };
  16740. SubMesh.prototype.getMaterial = function () {
  16741. var rootMaterial = this._renderingMesh.material;
  16742. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16743. var multiMaterial = rootMaterial;
  16744. return multiMaterial.getSubMaterial(this.materialIndex);
  16745. }
  16746. if (!rootMaterial) {
  16747. return this._mesh.getScene().defaultMaterial;
  16748. }
  16749. return rootMaterial;
  16750. };
  16751. // Methods
  16752. SubMesh.prototype.refreshBoundingInfo = function () {
  16753. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16754. if (!data) {
  16755. this._boundingInfo = this._mesh._boundingInfo;
  16756. return;
  16757. }
  16758. var indices = this._renderingMesh.getIndices();
  16759. var extend;
  16760. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16761. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16762. }
  16763. else {
  16764. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16765. }
  16766. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16767. };
  16768. SubMesh.prototype._checkCollision = function (collider) {
  16769. return this._boundingInfo._checkCollision(collider);
  16770. };
  16771. SubMesh.prototype.updateBoundingInfo = function (world) {
  16772. if (!this._boundingInfo) {
  16773. this.refreshBoundingInfo();
  16774. }
  16775. this._boundingInfo._update(world);
  16776. };
  16777. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16778. return this._boundingInfo.isInFrustum(frustumPlanes);
  16779. };
  16780. SubMesh.prototype.render = function (enableAlphaMode) {
  16781. this._renderingMesh.render(this, enableAlphaMode);
  16782. };
  16783. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16784. if (!this._linesIndexBuffer) {
  16785. var linesIndices = [];
  16786. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16787. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16788. }
  16789. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16790. this.linesIndexCount = linesIndices.length;
  16791. }
  16792. return this._linesIndexBuffer;
  16793. };
  16794. SubMesh.prototype.canIntersects = function (ray) {
  16795. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16796. };
  16797. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16798. var intersectInfo = null;
  16799. // Triangles test
  16800. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16801. var p0 = positions[indices[index]];
  16802. var p1 = positions[indices[index + 1]];
  16803. var p2 = positions[indices[index + 2]];
  16804. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16805. if (currentIntersectInfo) {
  16806. if (currentIntersectInfo.distance < 0) {
  16807. continue;
  16808. }
  16809. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16810. intersectInfo = currentIntersectInfo;
  16811. intersectInfo.faceId = index / 3;
  16812. if (fastCheck) {
  16813. break;
  16814. }
  16815. }
  16816. }
  16817. }
  16818. return intersectInfo;
  16819. };
  16820. // Clone
  16821. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16822. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16823. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16824. return result;
  16825. };
  16826. // Dispose
  16827. SubMesh.prototype.dispose = function () {
  16828. if (this._linesIndexBuffer) {
  16829. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16830. this._linesIndexBuffer = null;
  16831. }
  16832. // Remove from mesh
  16833. var index = this._mesh.subMeshes.indexOf(this);
  16834. this._mesh.subMeshes.splice(index, 1);
  16835. };
  16836. // Statics
  16837. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16838. var minVertexIndex = Number.MAX_VALUE;
  16839. var maxVertexIndex = -Number.MAX_VALUE;
  16840. renderingMesh = renderingMesh || mesh;
  16841. var indices = renderingMesh.getIndices();
  16842. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16843. var vertexIndex = indices[index];
  16844. if (vertexIndex < minVertexIndex)
  16845. minVertexIndex = vertexIndex;
  16846. if (vertexIndex > maxVertexIndex)
  16847. maxVertexIndex = vertexIndex;
  16848. }
  16849. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16850. };
  16851. return SubMesh;
  16852. })();
  16853. BABYLON.SubMesh = SubMesh;
  16854. })(BABYLON || (BABYLON = {}));
  16855. var BABYLON;
  16856. (function (BABYLON) {
  16857. var BaseTexture = (function () {
  16858. function BaseTexture(scene) {
  16859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16860. this.hasAlpha = false;
  16861. this.getAlphaFromRGB = false;
  16862. this.level = 1;
  16863. this.isCube = false;
  16864. this.isRenderTarget = false;
  16865. this.animations = new Array();
  16866. this.coordinatesIndex = 0;
  16867. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16868. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16869. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16870. this.anisotropicFilteringLevel = 4;
  16871. this._scene = scene;
  16872. this._scene.textures.push(this);
  16873. }
  16874. BaseTexture.prototype.getScene = function () {
  16875. return this._scene;
  16876. };
  16877. BaseTexture.prototype.getTextureMatrix = function () {
  16878. return null;
  16879. };
  16880. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16881. return null;
  16882. };
  16883. BaseTexture.prototype.getInternalTexture = function () {
  16884. return this._texture;
  16885. };
  16886. BaseTexture.prototype.isReady = function () {
  16887. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16888. return true;
  16889. }
  16890. if (this._texture) {
  16891. return this._texture.isReady;
  16892. }
  16893. return false;
  16894. };
  16895. BaseTexture.prototype.getSize = function () {
  16896. if (this._texture._width) {
  16897. return { width: this._texture._width, height: this._texture._height };
  16898. }
  16899. if (this._texture._size) {
  16900. return { width: this._texture._size, height: this._texture._size };
  16901. }
  16902. return { width: 0, height: 0 };
  16903. };
  16904. BaseTexture.prototype.getBaseSize = function () {
  16905. if (!this.isReady())
  16906. return { width: 0, height: 0 };
  16907. if (this._texture._size) {
  16908. return { width: this._texture._size, height: this._texture._size };
  16909. }
  16910. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16911. };
  16912. BaseTexture.prototype.scale = function (ratio) {
  16913. };
  16914. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16915. get: function () {
  16916. return false;
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16922. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16923. for (var index = 0; index < texturesCache.length; index++) {
  16924. var texturesCacheEntry = texturesCache[index];
  16925. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16926. texturesCache.splice(index, 1);
  16927. return;
  16928. }
  16929. }
  16930. };
  16931. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16932. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16933. for (var index = 0; index < texturesCache.length; index++) {
  16934. var texturesCacheEntry = texturesCache[index];
  16935. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16936. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16937. texturesCacheEntry.references++;
  16938. return texturesCacheEntry;
  16939. }
  16940. }
  16941. }
  16942. return null;
  16943. };
  16944. BaseTexture.prototype.delayLoad = function () {
  16945. };
  16946. BaseTexture.prototype.clone = function () {
  16947. return null;
  16948. };
  16949. BaseTexture.prototype.releaseInternalTexture = function () {
  16950. if (this._texture) {
  16951. this._scene.getEngine().releaseInternalTexture(this._texture);
  16952. delete this._texture;
  16953. }
  16954. };
  16955. BaseTexture.prototype.dispose = function () {
  16956. // Remove from scene
  16957. var index = this._scene.textures.indexOf(this);
  16958. if (index >= 0) {
  16959. this._scene.textures.splice(index, 1);
  16960. }
  16961. if (this._texture === undefined) {
  16962. return;
  16963. }
  16964. // Callback
  16965. if (this.onDispose) {
  16966. this.onDispose();
  16967. }
  16968. };
  16969. return BaseTexture;
  16970. })();
  16971. BABYLON.BaseTexture = BaseTexture;
  16972. })(BABYLON || (BABYLON = {}));
  16973. var BABYLON;
  16974. (function (BABYLON) {
  16975. var Texture = (function (_super) {
  16976. __extends(Texture, _super);
  16977. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16978. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16979. if (onLoad === void 0) { onLoad = null; }
  16980. if (onError === void 0) { onError = null; }
  16981. if (buffer === void 0) { buffer = null; }
  16982. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16983. _super.call(this, scene);
  16984. this.uOffset = 0;
  16985. this.vOffset = 0;
  16986. this.uScale = 1.0;
  16987. this.vScale = 1.0;
  16988. this.uAng = 0;
  16989. this.vAng = 0;
  16990. this.wAng = 0;
  16991. this.name = url;
  16992. this.url = url;
  16993. this._noMipmap = noMipmap;
  16994. this._invertY = invertY;
  16995. this._samplingMode = samplingMode;
  16996. this._buffer = buffer;
  16997. this._deleteBuffer = deleteBuffer;
  16998. if (!url) {
  16999. return;
  17000. }
  17001. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17002. if (!this._texture) {
  17003. if (!scene.useDelayedTextureLoading) {
  17004. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17005. if (deleteBuffer) {
  17006. delete this._buffer;
  17007. }
  17008. }
  17009. else {
  17010. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17011. }
  17012. }
  17013. else {
  17014. BABYLON.Tools.SetImmediate(function () {
  17015. if (onLoad) {
  17016. onLoad();
  17017. }
  17018. });
  17019. }
  17020. }
  17021. Texture.prototype.delayLoad = function () {
  17022. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17023. return;
  17024. }
  17025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17026. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17027. if (!this._texture) {
  17028. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17029. if (this._deleteBuffer) {
  17030. delete this._buffer;
  17031. }
  17032. }
  17033. };
  17034. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17035. if (!this._texture) {
  17036. return;
  17037. }
  17038. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17039. };
  17040. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17041. x *= this.uScale;
  17042. y *= this.vScale;
  17043. x -= 0.5 * this.uScale;
  17044. y -= 0.5 * this.vScale;
  17045. z -= 0.5;
  17046. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17047. t.x += 0.5 * this.uScale + this.uOffset;
  17048. t.y += 0.5 * this.vScale + this.vOffset;
  17049. t.z += 0.5;
  17050. };
  17051. Texture.prototype.getTextureMatrix = function () {
  17052. if (this.uOffset === this._cachedUOffset &&
  17053. this.vOffset === this._cachedVOffset &&
  17054. this.uScale === this._cachedUScale &&
  17055. this.vScale === this._cachedVScale &&
  17056. this.uAng === this._cachedUAng &&
  17057. this.vAng === this._cachedVAng &&
  17058. this.wAng === this._cachedWAng) {
  17059. return this._cachedTextureMatrix;
  17060. }
  17061. this._cachedUOffset = this.uOffset;
  17062. this._cachedVOffset = this.vOffset;
  17063. this._cachedUScale = this.uScale;
  17064. this._cachedVScale = this.vScale;
  17065. this._cachedUAng = this.uAng;
  17066. this._cachedVAng = this.vAng;
  17067. this._cachedWAng = this.wAng;
  17068. if (!this._cachedTextureMatrix) {
  17069. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17070. this._rowGenerationMatrix = new BABYLON.Matrix();
  17071. this._t0 = BABYLON.Vector3.Zero();
  17072. this._t1 = BABYLON.Vector3.Zero();
  17073. this._t2 = BABYLON.Vector3.Zero();
  17074. }
  17075. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17076. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17077. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17078. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17079. this._t1.subtractInPlace(this._t0);
  17080. this._t2.subtractInPlace(this._t0);
  17081. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17082. this._cachedTextureMatrix.m[0] = this._t1.x;
  17083. this._cachedTextureMatrix.m[1] = this._t1.y;
  17084. this._cachedTextureMatrix.m[2] = this._t1.z;
  17085. this._cachedTextureMatrix.m[4] = this._t2.x;
  17086. this._cachedTextureMatrix.m[5] = this._t2.y;
  17087. this._cachedTextureMatrix.m[6] = this._t2.z;
  17088. this._cachedTextureMatrix.m[8] = this._t0.x;
  17089. this._cachedTextureMatrix.m[9] = this._t0.y;
  17090. this._cachedTextureMatrix.m[10] = this._t0.z;
  17091. return this._cachedTextureMatrix;
  17092. };
  17093. Texture.prototype.getReflectionTextureMatrix = function () {
  17094. if (this.uOffset === this._cachedUOffset &&
  17095. this.vOffset === this._cachedVOffset &&
  17096. this.uScale === this._cachedUScale &&
  17097. this.vScale === this._cachedVScale &&
  17098. this.coordinatesMode === this._cachedCoordinatesMode) {
  17099. return this._cachedTextureMatrix;
  17100. }
  17101. if (!this._cachedTextureMatrix) {
  17102. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17103. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17104. }
  17105. this._cachedCoordinatesMode = this.coordinatesMode;
  17106. switch (this.coordinatesMode) {
  17107. case Texture.SPHERICAL_MODE:
  17108. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17109. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  17110. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  17111. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  17112. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  17113. break;
  17114. case Texture.PLANAR_MODE:
  17115. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17116. this._cachedTextureMatrix[0] = this.uScale;
  17117. this._cachedTextureMatrix[5] = this.vScale;
  17118. this._cachedTextureMatrix[12] = this.uOffset;
  17119. this._cachedTextureMatrix[13] = this.vOffset;
  17120. break;
  17121. case Texture.PROJECTION_MODE:
  17122. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17123. this._projectionModeMatrix.m[0] = 0.5;
  17124. this._projectionModeMatrix.m[5] = -0.5;
  17125. this._projectionModeMatrix.m[10] = 0.0;
  17126. this._projectionModeMatrix.m[12] = 0.5;
  17127. this._projectionModeMatrix.m[13] = 0.5;
  17128. this._projectionModeMatrix.m[14] = 1.0;
  17129. this._projectionModeMatrix.m[15] = 1.0;
  17130. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17131. break;
  17132. default:
  17133. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17134. break;
  17135. }
  17136. return this._cachedTextureMatrix;
  17137. };
  17138. Texture.prototype.clone = function () {
  17139. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17140. // Base texture
  17141. newTexture.hasAlpha = this.hasAlpha;
  17142. newTexture.level = this.level;
  17143. newTexture.wrapU = this.wrapU;
  17144. newTexture.wrapV = this.wrapV;
  17145. newTexture.coordinatesIndex = this.coordinatesIndex;
  17146. newTexture.coordinatesMode = this.coordinatesMode;
  17147. // Texture
  17148. newTexture.uOffset = this.uOffset;
  17149. newTexture.vOffset = this.vOffset;
  17150. newTexture.uScale = this.uScale;
  17151. newTexture.vScale = this.vScale;
  17152. newTexture.uAng = this.uAng;
  17153. newTexture.vAng = this.vAng;
  17154. newTexture.wAng = this.wAng;
  17155. return newTexture;
  17156. };
  17157. // Statics
  17158. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17159. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17160. if (onLoad === void 0) { onLoad = null; }
  17161. if (onError === void 0) { onError = null; }
  17162. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17163. };
  17164. // Constants
  17165. Texture.NEAREST_SAMPLINGMODE = 1;
  17166. Texture.BILINEAR_SAMPLINGMODE = 2;
  17167. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17168. Texture.EXPLICIT_MODE = 0;
  17169. Texture.SPHERICAL_MODE = 1;
  17170. Texture.PLANAR_MODE = 2;
  17171. Texture.CUBIC_MODE = 3;
  17172. Texture.PROJECTION_MODE = 4;
  17173. Texture.SKYBOX_MODE = 5;
  17174. Texture.INVCUBIC_MODE = 6;
  17175. Texture.CLAMP_ADDRESSMODE = 0;
  17176. Texture.WRAP_ADDRESSMODE = 1;
  17177. Texture.MIRROR_ADDRESSMODE = 2;
  17178. return Texture;
  17179. })(BABYLON.BaseTexture);
  17180. BABYLON.Texture = Texture;
  17181. })(BABYLON || (BABYLON = {}));
  17182. var BABYLON;
  17183. (function (BABYLON) {
  17184. var CubeTexture = (function (_super) {
  17185. __extends(CubeTexture, _super);
  17186. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  17187. _super.call(this, scene);
  17188. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17189. this.name = rootUrl;
  17190. this.url = rootUrl;
  17191. this._noMipmap = noMipmap;
  17192. this.hasAlpha = false;
  17193. if (!rootUrl) {
  17194. return;
  17195. }
  17196. this._texture = this._getFromCache(rootUrl, noMipmap);
  17197. if (!extensions) {
  17198. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17199. }
  17200. this._extensions = extensions;
  17201. if (!this._texture) {
  17202. if (!scene.useDelayedTextureLoading) {
  17203. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  17204. }
  17205. else {
  17206. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17207. }
  17208. }
  17209. this.isCube = true;
  17210. this._textureMatrix = BABYLON.Matrix.Identity();
  17211. }
  17212. CubeTexture.prototype.clone = function () {
  17213. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  17214. // Base texture
  17215. newTexture.level = this.level;
  17216. newTexture.wrapU = this.wrapU;
  17217. newTexture.wrapV = this.wrapV;
  17218. newTexture.coordinatesIndex = this.coordinatesIndex;
  17219. newTexture.coordinatesMode = this.coordinatesMode;
  17220. return newTexture;
  17221. };
  17222. // Methods
  17223. CubeTexture.prototype.delayLoad = function () {
  17224. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17225. return;
  17226. }
  17227. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17228. this._texture = this._getFromCache(this.url, this._noMipmap);
  17229. if (!this._texture) {
  17230. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17231. }
  17232. };
  17233. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17234. return this._textureMatrix;
  17235. };
  17236. return CubeTexture;
  17237. })(BABYLON.BaseTexture);
  17238. BABYLON.CubeTexture = CubeTexture;
  17239. })(BABYLON || (BABYLON = {}));
  17240. var BABYLON;
  17241. (function (BABYLON) {
  17242. var RenderTargetTexture = (function (_super) {
  17243. __extends(RenderTargetTexture, _super);
  17244. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17245. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17246. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17247. if (isCube === void 0) { isCube = false; }
  17248. _super.call(this, null, scene, !generateMipMaps);
  17249. this.isCube = isCube;
  17250. this.renderList = new Array();
  17251. this.renderParticles = true;
  17252. this.renderSprites = false;
  17253. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17254. this._currentRefreshId = -1;
  17255. this._refreshRate = 1;
  17256. this.name = name;
  17257. this.isRenderTarget = true;
  17258. this._size = size;
  17259. this._generateMipMaps = generateMipMaps;
  17260. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17261. if (isCube) {
  17262. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17263. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17264. this._textureMatrix = BABYLON.Matrix.Identity();
  17265. }
  17266. else {
  17267. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17268. }
  17269. // Rendering groups
  17270. this._renderingManager = new BABYLON.RenderingManager(scene);
  17271. }
  17272. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONCE", {
  17273. get: function () {
  17274. return RenderTargetTexture._REFRESHRATE_RENDERONCE;
  17275. },
  17276. enumerable: true,
  17277. configurable: true
  17278. });
  17279. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYFRAME", {
  17280. get: function () {
  17281. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME;
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDERONEVERYTWOFRAME", {
  17287. get: function () {
  17288. return RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME;
  17289. },
  17290. enumerable: true,
  17291. configurable: true
  17292. });
  17293. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17294. this._currentRefreshId = -1;
  17295. };
  17296. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17297. get: function () {
  17298. return this._refreshRate;
  17299. },
  17300. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17301. set: function (value) {
  17302. this._refreshRate = value;
  17303. this.resetRefreshCounter();
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. RenderTargetTexture.prototype._shouldRender = function () {
  17309. if (this._currentRefreshId === -1) {
  17310. this._currentRefreshId = 1;
  17311. return true;
  17312. }
  17313. if (this.refreshRate === this._currentRefreshId) {
  17314. this._currentRefreshId = 1;
  17315. return true;
  17316. }
  17317. this._currentRefreshId++;
  17318. return false;
  17319. };
  17320. RenderTargetTexture.prototype.isReady = function () {
  17321. if (!this.getScene().renderTargetsEnabled) {
  17322. return false;
  17323. }
  17324. return _super.prototype.isReady.call(this);
  17325. };
  17326. RenderTargetTexture.prototype.getRenderSize = function () {
  17327. return this._size;
  17328. };
  17329. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17330. get: function () {
  17331. return true;
  17332. },
  17333. enumerable: true,
  17334. configurable: true
  17335. });
  17336. RenderTargetTexture.prototype.scale = function (ratio) {
  17337. var newSize = this._size * ratio;
  17338. this.resize(newSize, this._generateMipMaps);
  17339. };
  17340. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17341. if (this.isCube) {
  17342. return this._textureMatrix;
  17343. }
  17344. return _super.prototype.getReflectionTextureMatrix.call(this);
  17345. };
  17346. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17347. this.releaseInternalTexture();
  17348. if (this.isCube) {
  17349. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17350. }
  17351. else {
  17352. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17353. }
  17354. };
  17355. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17356. var scene = this.getScene();
  17357. if (this._waitingRenderList) {
  17358. this.renderList = [];
  17359. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17360. var id = this._waitingRenderList[index];
  17361. this.renderList.push(scene.getMeshByID(id));
  17362. }
  17363. delete this._waitingRenderList;
  17364. }
  17365. if (this.renderList && this.renderList.length === 0) {
  17366. return;
  17367. }
  17368. // Prepare renderingManager
  17369. this._renderingManager.reset();
  17370. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17371. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17372. var mesh = currentRenderList[meshIndex];
  17373. if (mesh) {
  17374. if (!mesh.isReady()) {
  17375. // Reset _currentRefreshId
  17376. this.resetRefreshCounter();
  17377. continue;
  17378. }
  17379. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17380. mesh._activate(scene.getRenderId());
  17381. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17382. var subMesh = mesh.subMeshes[subIndex];
  17383. scene._activeIndices += subMesh.indexCount;
  17384. this._renderingManager.dispatch(subMesh);
  17385. }
  17386. }
  17387. }
  17388. }
  17389. if (this.isCube) {
  17390. for (var face = 0; face < 6; face++) {
  17391. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17392. }
  17393. }
  17394. else {
  17395. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17396. }
  17397. if (this.onAfterUnbind) {
  17398. this.onAfterUnbind();
  17399. }
  17400. scene.resetCachedMaterial();
  17401. };
  17402. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17403. var scene = this.getScene();
  17404. var engine = scene.getEngine();
  17405. // Bind
  17406. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17407. if (this.isCube) {
  17408. engine.bindFramebuffer(this._texture, faceIndex);
  17409. }
  17410. else {
  17411. engine.bindFramebuffer(this._texture);
  17412. }
  17413. }
  17414. if (this.onBeforeRender) {
  17415. this.onBeforeRender(faceIndex);
  17416. }
  17417. // Clear
  17418. if (this.onClear) {
  17419. this.onClear(engine);
  17420. }
  17421. else {
  17422. engine.clear(scene.clearColor, true, true);
  17423. }
  17424. if (!this._doNotChangeAspectRatio) {
  17425. scene.updateTransformMatrix(true);
  17426. }
  17427. // Render
  17428. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17429. if (useCameraPostProcess) {
  17430. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  17431. }
  17432. if (!this._doNotChangeAspectRatio) {
  17433. scene.updateTransformMatrix(true);
  17434. }
  17435. if (this.onAfterRender) {
  17436. this.onAfterRender(faceIndex);
  17437. }
  17438. // Dump ?
  17439. if (dumpForDebug) {
  17440. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17441. }
  17442. // Unbind
  17443. if (!this.isCube || faceIndex === 5) {
  17444. if (this.isCube) {
  17445. if (faceIndex === 5) {
  17446. engine.generateMipMapsForCubemap(this._texture);
  17447. }
  17448. }
  17449. engine.unBindFramebuffer(this._texture, true);
  17450. }
  17451. };
  17452. RenderTargetTexture.prototype.clone = function () {
  17453. var textureSize = this.getSize();
  17454. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17455. // Base texture
  17456. newTexture.hasAlpha = this.hasAlpha;
  17457. newTexture.level = this.level;
  17458. // RenderTarget Texture
  17459. newTexture.coordinatesMode = this.coordinatesMode;
  17460. newTexture.renderList = this.renderList.slice(0);
  17461. return newTexture;
  17462. };
  17463. RenderTargetTexture._REFRESHRATE_RENDERONCE = 0;
  17464. RenderTargetTexture._REFRESHRATE_RENDERONEVERYFRAME = 1;
  17465. RenderTargetTexture._REFRESHRATE_RENDERONEVERYTWOFRAME = 2;
  17466. return RenderTargetTexture;
  17467. })(BABYLON.Texture);
  17468. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17469. })(BABYLON || (BABYLON = {}));
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var ProceduralTexture = (function (_super) {
  17473. __extends(ProceduralTexture, _super);
  17474. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17475. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17476. _super.call(this, null, scene, !generateMipMaps);
  17477. this.isEnabled = true;
  17478. this._currentRefreshId = -1;
  17479. this._refreshRate = 1;
  17480. this._vertexDeclaration = [2];
  17481. this._vertexStrideSize = 2 * 4;
  17482. this._uniforms = new Array();
  17483. this._samplers = new Array();
  17484. this._textures = new Array();
  17485. this._floats = new Array();
  17486. this._floatsArrays = {};
  17487. this._colors3 = new Array();
  17488. this._colors4 = new Array();
  17489. this._vectors2 = new Array();
  17490. this._vectors3 = new Array();
  17491. this._matrices = new Array();
  17492. this._fallbackTextureUsed = false;
  17493. scene._proceduralTextures.push(this);
  17494. this.name = name;
  17495. this.isRenderTarget = true;
  17496. this._size = size;
  17497. this._generateMipMaps = generateMipMaps;
  17498. this.setFragment(fragment);
  17499. this._fallbackTexture = fallbackTexture;
  17500. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17501. // VBO
  17502. var vertices = [];
  17503. vertices.push(1, 1);
  17504. vertices.push(-1, 1);
  17505. vertices.push(-1, -1);
  17506. vertices.push(1, -1);
  17507. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17508. // Indices
  17509. var indices = [];
  17510. indices.push(0);
  17511. indices.push(1);
  17512. indices.push(2);
  17513. indices.push(0);
  17514. indices.push(2);
  17515. indices.push(3);
  17516. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17517. }
  17518. ProceduralTexture.prototype.reset = function () {
  17519. if (this._effect === undefined) {
  17520. return;
  17521. }
  17522. var engine = this.getScene().getEngine();
  17523. engine._releaseEffect(this._effect);
  17524. };
  17525. ProceduralTexture.prototype.isReady = function () {
  17526. var _this = this;
  17527. var engine = this.getScene().getEngine();
  17528. var shaders;
  17529. if (!this._fragment) {
  17530. return false;
  17531. }
  17532. if (this._fallbackTextureUsed) {
  17533. return true;
  17534. }
  17535. if (this._fragment.fragmentElement !== undefined) {
  17536. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17537. }
  17538. else {
  17539. shaders = { vertex: "procedural", fragment: this._fragment };
  17540. }
  17541. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17542. _this.releaseInternalTexture();
  17543. if (_this._fallbackTexture) {
  17544. _this._texture = _this._fallbackTexture._texture;
  17545. _this._texture.references++;
  17546. }
  17547. _this._fallbackTextureUsed = true;
  17548. });
  17549. return this._effect.isReady();
  17550. };
  17551. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17552. this._currentRefreshId = -1;
  17553. };
  17554. ProceduralTexture.prototype.setFragment = function (fragment) {
  17555. this._fragment = fragment;
  17556. };
  17557. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17558. get: function () {
  17559. return this._refreshRate;
  17560. },
  17561. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17562. set: function (value) {
  17563. this._refreshRate = value;
  17564. this.resetRefreshCounter();
  17565. },
  17566. enumerable: true,
  17567. configurable: true
  17568. });
  17569. ProceduralTexture.prototype._shouldRender = function () {
  17570. if (!this.isEnabled || !this.isReady() || !this._texture) {
  17571. return false;
  17572. }
  17573. if (this._fallbackTextureUsed) {
  17574. return false;
  17575. }
  17576. if (this._currentRefreshId === -1) {
  17577. this._currentRefreshId = 1;
  17578. return true;
  17579. }
  17580. if (this.refreshRate === this._currentRefreshId) {
  17581. this._currentRefreshId = 1;
  17582. return true;
  17583. }
  17584. this._currentRefreshId++;
  17585. return false;
  17586. };
  17587. ProceduralTexture.prototype.getRenderSize = function () {
  17588. return this._size;
  17589. };
  17590. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17591. if (this._fallbackTextureUsed) {
  17592. return;
  17593. }
  17594. this.releaseInternalTexture();
  17595. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17596. };
  17597. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17598. if (this._uniforms.indexOf(uniformName) === -1) {
  17599. this._uniforms.push(uniformName);
  17600. }
  17601. };
  17602. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17603. if (this._samplers.indexOf(name) === -1) {
  17604. this._samplers.push(name);
  17605. }
  17606. this._textures[name] = texture;
  17607. return this;
  17608. };
  17609. ProceduralTexture.prototype.setFloat = function (name, value) {
  17610. this._checkUniform(name);
  17611. this._floats[name] = value;
  17612. return this;
  17613. };
  17614. ProceduralTexture.prototype.setFloats = function (name, value) {
  17615. this._checkUniform(name);
  17616. this._floatsArrays[name] = value;
  17617. return this;
  17618. };
  17619. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17620. this._checkUniform(name);
  17621. this._colors3[name] = value;
  17622. return this;
  17623. };
  17624. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17625. this._checkUniform(name);
  17626. this._colors4[name] = value;
  17627. return this;
  17628. };
  17629. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17630. this._checkUniform(name);
  17631. this._vectors2[name] = value;
  17632. return this;
  17633. };
  17634. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17635. this._checkUniform(name);
  17636. this._vectors3[name] = value;
  17637. return this;
  17638. };
  17639. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17640. this._checkUniform(name);
  17641. this._matrices[name] = value;
  17642. return this;
  17643. };
  17644. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17645. var scene = this.getScene();
  17646. var engine = scene.getEngine();
  17647. engine.bindFramebuffer(this._texture);
  17648. // Clear
  17649. engine.clear(scene.clearColor, true, true);
  17650. // Render
  17651. engine.enableEffect(this._effect);
  17652. engine.setState(false);
  17653. // Texture
  17654. for (var name in this._textures) {
  17655. this._effect.setTexture(name, this._textures[name]);
  17656. }
  17657. // Float
  17658. for (name in this._floats) {
  17659. this._effect.setFloat(name, this._floats[name]);
  17660. }
  17661. // Floats
  17662. for (name in this._floatsArrays) {
  17663. this._effect.setArray(name, this._floatsArrays[name]);
  17664. }
  17665. // Color3
  17666. for (name in this._colors3) {
  17667. this._effect.setColor3(name, this._colors3[name]);
  17668. }
  17669. // Color4
  17670. for (name in this._colors4) {
  17671. var color = this._colors4[name];
  17672. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17673. }
  17674. // Vector2
  17675. for (name in this._vectors2) {
  17676. this._effect.setVector2(name, this._vectors2[name]);
  17677. }
  17678. // Vector3
  17679. for (name in this._vectors3) {
  17680. this._effect.setVector3(name, this._vectors3[name]);
  17681. }
  17682. // Matrix
  17683. for (name in this._matrices) {
  17684. this._effect.setMatrix(name, this._matrices[name]);
  17685. }
  17686. // VBOs
  17687. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17688. // Draw order
  17689. engine.draw(true, 0, 6);
  17690. // Unbind
  17691. engine.unBindFramebuffer(this._texture);
  17692. };
  17693. ProceduralTexture.prototype.clone = function () {
  17694. var textureSize = this.getSize();
  17695. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17696. // Base texture
  17697. newTexture.hasAlpha = this.hasAlpha;
  17698. newTexture.level = this.level;
  17699. // RenderTarget Texture
  17700. newTexture.coordinatesMode = this.coordinatesMode;
  17701. return newTexture;
  17702. };
  17703. ProceduralTexture.prototype.dispose = function () {
  17704. var index = this.getScene()._proceduralTextures.indexOf(this);
  17705. if (index >= 0) {
  17706. this.getScene()._proceduralTextures.splice(index, 1);
  17707. }
  17708. _super.prototype.dispose.call(this);
  17709. };
  17710. return ProceduralTexture;
  17711. })(BABYLON.Texture);
  17712. BABYLON.ProceduralTexture = ProceduralTexture;
  17713. })(BABYLON || (BABYLON = {}));
  17714. var BABYLON;
  17715. (function (BABYLON) {
  17716. var MirrorTexture = (function (_super) {
  17717. __extends(MirrorTexture, _super);
  17718. function MirrorTexture(name, size, scene, generateMipMaps) {
  17719. var _this = this;
  17720. _super.call(this, name, size, scene, generateMipMaps, true);
  17721. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17722. this._transformMatrix = BABYLON.Matrix.Zero();
  17723. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17724. this.onBeforeRender = function () {
  17725. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17726. _this._savedViewMatrix = scene.getViewMatrix();
  17727. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17728. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17729. scene.clipPlane = _this.mirrorPlane;
  17730. scene.getEngine().cullBackFaces = false;
  17731. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17732. };
  17733. this.onAfterRender = function () {
  17734. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17735. scene.getEngine().cullBackFaces = true;
  17736. scene._mirroredCameraPosition = null;
  17737. delete scene.clipPlane;
  17738. };
  17739. }
  17740. MirrorTexture.prototype.clone = function () {
  17741. var textureSize = this.getSize();
  17742. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17743. // Base texture
  17744. newTexture.hasAlpha = this.hasAlpha;
  17745. newTexture.level = this.level;
  17746. // Mirror Texture
  17747. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17748. newTexture.renderList = this.renderList.slice(0);
  17749. return newTexture;
  17750. };
  17751. return MirrorTexture;
  17752. })(BABYLON.RenderTargetTexture);
  17753. BABYLON.MirrorTexture = MirrorTexture;
  17754. })(BABYLON || (BABYLON = {}));
  17755. var BABYLON;
  17756. (function (BABYLON) {
  17757. var DynamicTexture = (function (_super) {
  17758. __extends(DynamicTexture, _super);
  17759. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17761. _super.call(this, null, scene, !generateMipMaps);
  17762. this.name = name;
  17763. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17764. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17765. this._generateMipMaps = generateMipMaps;
  17766. if (options.getContext) {
  17767. this._canvas = options;
  17768. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17769. }
  17770. else {
  17771. this._canvas = document.createElement("canvas");
  17772. if (options.width) {
  17773. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17774. }
  17775. else {
  17776. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17777. }
  17778. }
  17779. var textureSize = this.getSize();
  17780. this._canvas.width = textureSize.width;
  17781. this._canvas.height = textureSize.height;
  17782. this._context = this._canvas.getContext("2d");
  17783. }
  17784. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17785. get: function () {
  17786. return true;
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. DynamicTexture.prototype.scale = function (ratio) {
  17792. var textureSize = this.getSize();
  17793. textureSize.width *= ratio;
  17794. textureSize.height *= ratio;
  17795. this._canvas.width = textureSize.width;
  17796. this._canvas.height = textureSize.height;
  17797. this.releaseInternalTexture();
  17798. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17799. };
  17800. DynamicTexture.prototype.getContext = function () {
  17801. return this._context;
  17802. };
  17803. DynamicTexture.prototype.clear = function () {
  17804. var size = this.getSize();
  17805. this._context.fillRect(0, 0, size.width, size.height);
  17806. };
  17807. DynamicTexture.prototype.update = function (invertY) {
  17808. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17809. };
  17810. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17811. if (update === void 0) { update = true; }
  17812. var size = this.getSize();
  17813. if (clearColor) {
  17814. this._context.fillStyle = clearColor;
  17815. this._context.fillRect(0, 0, size.width, size.height);
  17816. }
  17817. this._context.font = font;
  17818. if (x === null) {
  17819. var textSize = this._context.measureText(text);
  17820. x = (size.width - textSize.width) / 2;
  17821. }
  17822. this._context.fillStyle = color;
  17823. this._context.fillText(text, x, y);
  17824. if (update) {
  17825. this.update(invertY);
  17826. }
  17827. };
  17828. DynamicTexture.prototype.clone = function () {
  17829. var textureSize = this.getSize();
  17830. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17831. // Base texture
  17832. newTexture.hasAlpha = this.hasAlpha;
  17833. newTexture.level = this.level;
  17834. // Dynamic Texture
  17835. newTexture.wrapU = this.wrapU;
  17836. newTexture.wrapV = this.wrapV;
  17837. return newTexture;
  17838. };
  17839. return DynamicTexture;
  17840. })(BABYLON.Texture);
  17841. BABYLON.DynamicTexture = DynamicTexture;
  17842. })(BABYLON || (BABYLON = {}));
  17843. var BABYLON;
  17844. (function (BABYLON) {
  17845. var VideoTexture = (function (_super) {
  17846. __extends(VideoTexture, _super);
  17847. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17848. var _this = this;
  17849. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17850. if (invertY === void 0) { invertY = false; }
  17851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17852. _super.call(this, null, scene, !generateMipMaps, invertY);
  17853. this._autoLaunch = true;
  17854. this.name = name;
  17855. this.video = document.createElement("video");
  17856. this.video.autoplay = false;
  17857. this.video.loop = true;
  17858. this.video.addEventListener("canplaythrough", function () {
  17859. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17860. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17861. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17862. }
  17863. else {
  17864. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17865. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17866. generateMipMaps = false;
  17867. }
  17868. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17869. _this._texture.isReady = true;
  17870. });
  17871. urls.forEach(function (url) {
  17872. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17873. var source = document.createElement("source");
  17874. source.src = url;
  17875. _this.video.appendChild(source);
  17876. });
  17877. this._lastUpdate = BABYLON.Tools.Now;
  17878. }
  17879. VideoTexture.prototype.update = function () {
  17880. if (this._autoLaunch) {
  17881. this._autoLaunch = false;
  17882. this.video.play();
  17883. }
  17884. var now = BABYLON.Tools.Now;
  17885. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17886. return false;
  17887. }
  17888. this._lastUpdate = now;
  17889. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17890. return true;
  17891. };
  17892. return VideoTexture;
  17893. })(BABYLON.Texture);
  17894. BABYLON.VideoTexture = VideoTexture;
  17895. })(BABYLON || (BABYLON = {}));
  17896. var BABYLON;
  17897. (function (BABYLON) {
  17898. var CustomProceduralTexture = (function (_super) {
  17899. __extends(CustomProceduralTexture, _super);
  17900. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17901. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17902. this._animate = true;
  17903. this._time = 0;
  17904. this._texturePath = texturePath;
  17905. //Try to load json
  17906. this.loadJson(texturePath);
  17907. this.refreshRate = 1;
  17908. }
  17909. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17910. var _this = this;
  17911. var that = this;
  17912. function noConfigFile() {
  17913. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17914. try {
  17915. that.setFragment(that._texturePath);
  17916. }
  17917. catch (ex) {
  17918. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17919. }
  17920. }
  17921. var configFileUrl = jsonUrl + "/config.json";
  17922. var xhr = new XMLHttpRequest();
  17923. xhr.open("GET", configFileUrl, true);
  17924. xhr.addEventListener("load", function () {
  17925. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17926. try {
  17927. _this._config = JSON.parse(xhr.response);
  17928. _this.updateShaderUniforms();
  17929. _this.updateTextures();
  17930. _this.setFragment(_this._texturePath + "/custom");
  17931. _this._animate = _this._config.animate;
  17932. _this.refreshRate = _this._config.refreshrate;
  17933. }
  17934. catch (ex) {
  17935. noConfigFile();
  17936. }
  17937. }
  17938. else {
  17939. noConfigFile();
  17940. }
  17941. }, false);
  17942. xhr.addEventListener("error", function () {
  17943. noConfigFile();
  17944. }, false);
  17945. try {
  17946. xhr.send();
  17947. }
  17948. catch (ex) {
  17949. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17950. }
  17951. };
  17952. CustomProceduralTexture.prototype.isReady = function () {
  17953. if (!_super.prototype.isReady.call(this)) {
  17954. return false;
  17955. }
  17956. for (var name in this._textures) {
  17957. var texture = this._textures[name];
  17958. if (!texture.isReady()) {
  17959. return false;
  17960. }
  17961. }
  17962. return true;
  17963. };
  17964. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17965. if (this._animate) {
  17966. this._time += this.getScene().getAnimationRatio() * 0.03;
  17967. this.updateShaderUniforms();
  17968. }
  17969. _super.prototype.render.call(this, useCameraPostProcess);
  17970. };
  17971. CustomProceduralTexture.prototype.updateTextures = function () {
  17972. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17973. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17974. }
  17975. };
  17976. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17977. if (this._config) {
  17978. for (var j = 0; j < this._config.uniforms.length; j++) {
  17979. var uniform = this._config.uniforms[j];
  17980. switch (uniform.type) {
  17981. case "float":
  17982. this.setFloat(uniform.name, uniform.value);
  17983. break;
  17984. case "color3":
  17985. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17986. break;
  17987. case "color4":
  17988. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17989. break;
  17990. case "vector2":
  17991. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17992. break;
  17993. case "vector3":
  17994. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17995. break;
  17996. }
  17997. }
  17998. }
  17999. this.setFloat("time", this._time);
  18000. };
  18001. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18002. get: function () {
  18003. return this._animate;
  18004. },
  18005. set: function (value) {
  18006. this._animate = value;
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. return CustomProceduralTexture;
  18012. })(BABYLON.ProceduralTexture);
  18013. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18014. })(BABYLON || (BABYLON = {}));
  18015. var BABYLON;
  18016. (function (BABYLON) {
  18017. var WoodProceduralTexture = (function (_super) {
  18018. __extends(WoodProceduralTexture, _super);
  18019. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18020. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  18021. this._ampScale = 100.0;
  18022. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  18023. this.updateShaderUniforms();
  18024. this.refreshRate = 0;
  18025. }
  18026. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  18027. this.setFloat("ampScale", this._ampScale);
  18028. this.setColor3("woodColor", this._woodColor);
  18029. };
  18030. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  18031. get: function () {
  18032. return this._ampScale;
  18033. },
  18034. set: function (value) {
  18035. this._ampScale = value;
  18036. this.updateShaderUniforms();
  18037. },
  18038. enumerable: true,
  18039. configurable: true
  18040. });
  18041. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  18042. get: function () {
  18043. return this._woodColor;
  18044. },
  18045. set: function (value) {
  18046. this._woodColor = value;
  18047. this.updateShaderUniforms();
  18048. },
  18049. enumerable: true,
  18050. configurable: true
  18051. });
  18052. return WoodProceduralTexture;
  18053. })(BABYLON.ProceduralTexture);
  18054. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  18055. var FireProceduralTexture = (function (_super) {
  18056. __extends(FireProceduralTexture, _super);
  18057. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18058. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  18059. this._time = 0.0;
  18060. this._speed = new BABYLON.Vector2(0.5, 0.3);
  18061. this._autoGenerateTime = true;
  18062. this._alphaThreshold = 0.5;
  18063. this._fireColors = FireProceduralTexture.RedFireColors;
  18064. this.updateShaderUniforms();
  18065. this.refreshRate = 1;
  18066. }
  18067. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  18068. this.setFloat("time", this._time);
  18069. this.setVector2("speed", this._speed);
  18070. this.setColor3("c1", this._fireColors[0]);
  18071. this.setColor3("c2", this._fireColors[1]);
  18072. this.setColor3("c3", this._fireColors[2]);
  18073. this.setColor3("c4", this._fireColors[3]);
  18074. this.setColor3("c5", this._fireColors[4]);
  18075. this.setColor3("c6", this._fireColors[5]);
  18076. this.setFloat("alphaThreshold", this._alphaThreshold);
  18077. };
  18078. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18079. if (this._autoGenerateTime) {
  18080. this._time += this.getScene().getAnimationRatio() * 0.03;
  18081. this.updateShaderUniforms();
  18082. }
  18083. _super.prototype.render.call(this, useCameraPostProcess);
  18084. };
  18085. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  18086. get: function () {
  18087. return [
  18088. new BABYLON.Color3(0.5, 0.0, 1.0),
  18089. new BABYLON.Color3(0.9, 0.0, 1.0),
  18090. new BABYLON.Color3(0.2, 0.0, 1.0),
  18091. new BABYLON.Color3(1.0, 0.9, 1.0),
  18092. new BABYLON.Color3(0.1, 0.1, 1.0),
  18093. new BABYLON.Color3(0.9, 0.9, 1.0)
  18094. ];
  18095. },
  18096. enumerable: true,
  18097. configurable: true
  18098. });
  18099. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  18100. get: function () {
  18101. return [
  18102. new BABYLON.Color3(0.5, 1.0, 0.0),
  18103. new BABYLON.Color3(0.5, 1.0, 0.0),
  18104. new BABYLON.Color3(0.3, 0.4, 0.0),
  18105. new BABYLON.Color3(0.5, 1.0, 0.0),
  18106. new BABYLON.Color3(0.2, 0.0, 0.0),
  18107. new BABYLON.Color3(0.5, 1.0, 0.0)
  18108. ];
  18109. },
  18110. enumerable: true,
  18111. configurable: true
  18112. });
  18113. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  18114. get: function () {
  18115. return [
  18116. new BABYLON.Color3(0.5, 0.0, 0.1),
  18117. new BABYLON.Color3(0.9, 0.0, 0.0),
  18118. new BABYLON.Color3(0.2, 0.0, 0.0),
  18119. new BABYLON.Color3(1.0, 0.9, 0.0),
  18120. new BABYLON.Color3(0.1, 0.1, 0.1),
  18121. new BABYLON.Color3(0.9, 0.9, 0.9)
  18122. ];
  18123. },
  18124. enumerable: true,
  18125. configurable: true
  18126. });
  18127. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  18128. get: function () {
  18129. return [
  18130. new BABYLON.Color3(0.1, 0.0, 0.5),
  18131. new BABYLON.Color3(0.0, 0.0, 0.5),
  18132. new BABYLON.Color3(0.1, 0.0, 0.2),
  18133. new BABYLON.Color3(0.0, 0.0, 1.0),
  18134. new BABYLON.Color3(0.1, 0.2, 0.3),
  18135. new BABYLON.Color3(0.0, 0.2, 0.9)
  18136. ];
  18137. },
  18138. enumerable: true,
  18139. configurable: true
  18140. });
  18141. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  18142. get: function () {
  18143. return this._fireColors;
  18144. },
  18145. set: function (value) {
  18146. this._fireColors = value;
  18147. this.updateShaderUniforms();
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  18153. get: function () {
  18154. return this._time;
  18155. },
  18156. set: function (value) {
  18157. this._time = value;
  18158. this.updateShaderUniforms();
  18159. },
  18160. enumerable: true,
  18161. configurable: true
  18162. });
  18163. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  18164. get: function () {
  18165. return this._speed;
  18166. },
  18167. set: function (value) {
  18168. this._speed = value;
  18169. this.updateShaderUniforms();
  18170. },
  18171. enumerable: true,
  18172. configurable: true
  18173. });
  18174. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  18175. get: function () {
  18176. return this._alphaThreshold;
  18177. },
  18178. set: function (value) {
  18179. this._alphaThreshold = value;
  18180. this.updateShaderUniforms();
  18181. },
  18182. enumerable: true,
  18183. configurable: true
  18184. });
  18185. return FireProceduralTexture;
  18186. })(BABYLON.ProceduralTexture);
  18187. BABYLON.FireProceduralTexture = FireProceduralTexture;
  18188. var CloudProceduralTexture = (function (_super) {
  18189. __extends(CloudProceduralTexture, _super);
  18190. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18191. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  18192. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  18193. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  18194. this.updateShaderUniforms();
  18195. this.refreshRate = 0;
  18196. }
  18197. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  18198. this.setColor4("skyColor", this._skyColor);
  18199. this.setColor4("cloudColor", this._cloudColor);
  18200. };
  18201. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  18202. get: function () {
  18203. return this._skyColor;
  18204. },
  18205. set: function (value) {
  18206. this._skyColor = value;
  18207. this.updateShaderUniforms();
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  18213. get: function () {
  18214. return this._cloudColor;
  18215. },
  18216. set: function (value) {
  18217. this._cloudColor = value;
  18218. this.updateShaderUniforms();
  18219. },
  18220. enumerable: true,
  18221. configurable: true
  18222. });
  18223. return CloudProceduralTexture;
  18224. })(BABYLON.ProceduralTexture);
  18225. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  18226. var GrassProceduralTexture = (function (_super) {
  18227. __extends(GrassProceduralTexture, _super);
  18228. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18229. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  18230. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  18231. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  18232. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  18233. this._groundColor = new BABYLON.Color3(1, 1, 1);
  18234. this._grassColors = [
  18235. new BABYLON.Color3(0.29, 0.38, 0.02),
  18236. new BABYLON.Color3(0.36, 0.49, 0.09),
  18237. new BABYLON.Color3(0.51, 0.6, 0.28)
  18238. ];
  18239. this.updateShaderUniforms();
  18240. this.refreshRate = 0;
  18241. }
  18242. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  18243. this.setColor3("herb1Color", this._grassColors[0]);
  18244. this.setColor3("herb2Color", this._grassColors[1]);
  18245. this.setColor3("herb3Color", this._grassColors[2]);
  18246. this.setColor3("groundColor", this._groundColor);
  18247. };
  18248. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  18249. get: function () {
  18250. return this._grassColors;
  18251. },
  18252. set: function (value) {
  18253. this._grassColors = value;
  18254. this.updateShaderUniforms();
  18255. },
  18256. enumerable: true,
  18257. configurable: true
  18258. });
  18259. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  18260. get: function () {
  18261. return this._groundColor;
  18262. },
  18263. set: function (value) {
  18264. this.groundColor = value;
  18265. this.updateShaderUniforms();
  18266. },
  18267. enumerable: true,
  18268. configurable: true
  18269. });
  18270. return GrassProceduralTexture;
  18271. })(BABYLON.ProceduralTexture);
  18272. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  18273. var RoadProceduralTexture = (function (_super) {
  18274. __extends(RoadProceduralTexture, _super);
  18275. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18276. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  18277. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  18278. this.updateShaderUniforms();
  18279. this.refreshRate = 0;
  18280. }
  18281. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  18282. this.setColor3("roadColor", this._roadColor);
  18283. };
  18284. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  18285. get: function () {
  18286. return this._roadColor;
  18287. },
  18288. set: function (value) {
  18289. this._roadColor = value;
  18290. this.updateShaderUniforms();
  18291. },
  18292. enumerable: true,
  18293. configurable: true
  18294. });
  18295. return RoadProceduralTexture;
  18296. })(BABYLON.ProceduralTexture);
  18297. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  18298. var BrickProceduralTexture = (function (_super) {
  18299. __extends(BrickProceduralTexture, _super);
  18300. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18301. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  18302. this._numberOfBricksHeight = 15;
  18303. this._numberOfBricksWidth = 5;
  18304. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18305. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18306. this.updateShaderUniforms();
  18307. this.refreshRate = 0;
  18308. }
  18309. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  18310. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  18311. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  18312. this.setColor3("brickColor", this._brickColor);
  18313. this.setColor3("jointColor", this._jointColor);
  18314. };
  18315. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  18316. get: function () {
  18317. return this._numberOfBricksHeight;
  18318. },
  18319. set: function (value) {
  18320. this._numberOfBricksHeight = value;
  18321. this.updateShaderUniforms();
  18322. },
  18323. enumerable: true,
  18324. configurable: true
  18325. });
  18326. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  18327. get: function () {
  18328. return this._numberOfBricksWidth;
  18329. },
  18330. set: function (value) {
  18331. this._numberOfBricksWidth = value;
  18332. this.updateShaderUniforms();
  18333. },
  18334. enumerable: true,
  18335. configurable: true
  18336. });
  18337. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  18338. get: function () {
  18339. return this._jointColor;
  18340. },
  18341. set: function (value) {
  18342. this._jointColor = value;
  18343. this.updateShaderUniforms();
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  18349. get: function () {
  18350. return this._brickColor;
  18351. },
  18352. set: function (value) {
  18353. this._brickColor = value;
  18354. this.updateShaderUniforms();
  18355. },
  18356. enumerable: true,
  18357. configurable: true
  18358. });
  18359. return BrickProceduralTexture;
  18360. })(BABYLON.ProceduralTexture);
  18361. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  18362. var MarbleProceduralTexture = (function (_super) {
  18363. __extends(MarbleProceduralTexture, _super);
  18364. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  18365. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  18366. this._numberOfTilesHeight = 3;
  18367. this._numberOfTilesWidth = 3;
  18368. this._amplitude = 9.0;
  18369. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  18370. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  18371. this.updateShaderUniforms();
  18372. this.refreshRate = 0;
  18373. }
  18374. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  18375. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  18376. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  18377. this.setFloat("amplitude", this._amplitude);
  18378. this.setColor3("marbleColor", this._marbleColor);
  18379. this.setColor3("jointColor", this._jointColor);
  18380. };
  18381. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  18382. get: function () {
  18383. return this._numberOfTilesHeight;
  18384. },
  18385. set: function (value) {
  18386. this._numberOfTilesHeight = value;
  18387. this.updateShaderUniforms();
  18388. },
  18389. enumerable: true,
  18390. configurable: true
  18391. });
  18392. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  18393. get: function () {
  18394. return this._numberOfTilesWidth;
  18395. },
  18396. set: function (value) {
  18397. this._numberOfTilesWidth = value;
  18398. this.updateShaderUniforms();
  18399. },
  18400. enumerable: true,
  18401. configurable: true
  18402. });
  18403. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  18404. get: function () {
  18405. return this._jointColor;
  18406. },
  18407. set: function (value) {
  18408. this._jointColor = value;
  18409. this.updateShaderUniforms();
  18410. },
  18411. enumerable: true,
  18412. configurable: true
  18413. });
  18414. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  18415. get: function () {
  18416. return this._marbleColor;
  18417. },
  18418. set: function (value) {
  18419. this._marbleColor = value;
  18420. this.updateShaderUniforms();
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. return MarbleProceduralTexture;
  18426. })(BABYLON.ProceduralTexture);
  18427. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  18428. })(BABYLON || (BABYLON = {}));
  18429. var BABYLON;
  18430. (function (BABYLON) {
  18431. var EffectFallbacks = (function () {
  18432. function EffectFallbacks() {
  18433. this._defines = {};
  18434. this._currentRank = 32;
  18435. this._maxRank = -1;
  18436. }
  18437. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18438. if (!this._defines[rank]) {
  18439. if (rank < this._currentRank) {
  18440. this._currentRank = rank;
  18441. }
  18442. if (rank > this._maxRank) {
  18443. this._maxRank = rank;
  18444. }
  18445. this._defines[rank] = new Array();
  18446. }
  18447. this._defines[rank].push(define);
  18448. };
  18449. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18450. get: function () {
  18451. return this._currentRank <= this._maxRank;
  18452. },
  18453. enumerable: true,
  18454. configurable: true
  18455. });
  18456. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18457. var currentFallbacks = this._defines[this._currentRank];
  18458. for (var index = 0; index < currentFallbacks.length; index++) {
  18459. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18460. }
  18461. this._currentRank++;
  18462. return currentDefines;
  18463. };
  18464. return EffectFallbacks;
  18465. })();
  18466. BABYLON.EffectFallbacks = EffectFallbacks;
  18467. var Effect = (function () {
  18468. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18469. var _this = this;
  18470. this._isReady = false;
  18471. this._compilationError = "";
  18472. this._valueCache = [];
  18473. this._engine = engine;
  18474. this.name = baseName;
  18475. this.defines = defines;
  18476. this._uniformsNames = uniformsNames.concat(samplers);
  18477. this._samplers = samplers;
  18478. this._attributesNames = attributesNames;
  18479. this.onError = onError;
  18480. this.onCompiled = onCompiled;
  18481. var vertexSource;
  18482. var fragmentSource;
  18483. if (baseName.vertexElement) {
  18484. vertexSource = document.getElementById(baseName.vertexElement);
  18485. if (!vertexSource) {
  18486. vertexSource = baseName.vertexElement;
  18487. }
  18488. }
  18489. else {
  18490. vertexSource = baseName.vertex || baseName;
  18491. }
  18492. if (baseName.fragmentElement) {
  18493. fragmentSource = document.getElementById(baseName.fragmentElement);
  18494. if (!fragmentSource) {
  18495. fragmentSource = baseName.fragmentElement;
  18496. }
  18497. }
  18498. else {
  18499. fragmentSource = baseName.fragment || baseName;
  18500. }
  18501. this._loadVertexShader(vertexSource, function (vertexCode) {
  18502. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18503. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18504. });
  18505. });
  18506. }
  18507. // Properties
  18508. Effect.prototype.isReady = function () {
  18509. return this._isReady;
  18510. };
  18511. Effect.prototype.getProgram = function () {
  18512. return this._program;
  18513. };
  18514. Effect.prototype.getAttributesNames = function () {
  18515. return this._attributesNames;
  18516. };
  18517. Effect.prototype.getAttributeLocation = function (index) {
  18518. return this._attributes[index];
  18519. };
  18520. Effect.prototype.getAttributeLocationByName = function (name) {
  18521. var index = this._attributesNames.indexOf(name);
  18522. return this._attributes[index];
  18523. };
  18524. Effect.prototype.getAttributesCount = function () {
  18525. return this._attributes.length;
  18526. };
  18527. Effect.prototype.getUniformIndex = function (uniformName) {
  18528. return this._uniformsNames.indexOf(uniformName);
  18529. };
  18530. Effect.prototype.getUniform = function (uniformName) {
  18531. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18532. };
  18533. Effect.prototype.getSamplers = function () {
  18534. return this._samplers;
  18535. };
  18536. Effect.prototype.getCompilationError = function () {
  18537. return this._compilationError;
  18538. };
  18539. // Methods
  18540. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18541. // DOM element ?
  18542. if (vertex instanceof HTMLElement) {
  18543. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18544. callback(vertexCode);
  18545. return;
  18546. }
  18547. // Is in local store ?
  18548. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18549. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18550. return;
  18551. }
  18552. var vertexShaderUrl;
  18553. if (vertex[0] === "." || vertex[0] === "/") {
  18554. vertexShaderUrl = vertex;
  18555. }
  18556. else {
  18557. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18558. }
  18559. // Vertex shader
  18560. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18561. };
  18562. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18563. // DOM element ?
  18564. if (fragment instanceof HTMLElement) {
  18565. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18566. callback(fragmentCode);
  18567. return;
  18568. }
  18569. // Is in local store ?
  18570. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18571. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18572. return;
  18573. }
  18574. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18575. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18576. return;
  18577. }
  18578. var fragmentShaderUrl;
  18579. if (fragment[0] === "." || fragment[0] === "/") {
  18580. fragmentShaderUrl = fragment;
  18581. }
  18582. else {
  18583. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18584. }
  18585. // Fragment shader
  18586. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18587. };
  18588. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18589. try {
  18590. var engine = this._engine;
  18591. if (!engine.getCaps().highPrecisionShaderSupported) {
  18592. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18593. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18594. }
  18595. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18596. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18597. this._attributes = engine.getAttributes(this._program, attributesNames);
  18598. for (var index = 0; index < this._samplers.length; index++) {
  18599. var sampler = this.getUniform(this._samplers[index]);
  18600. if (sampler == null) {
  18601. this._samplers.splice(index, 1);
  18602. index--;
  18603. }
  18604. }
  18605. engine.bindSamplers(this);
  18606. this._isReady = true;
  18607. if (this.onCompiled) {
  18608. this.onCompiled(this);
  18609. }
  18610. }
  18611. catch (e) {
  18612. // Is it a problem with precision?
  18613. if (e.message.indexOf("highp") !== -1) {
  18614. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18615. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18616. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18617. return;
  18618. }
  18619. // Let's go through fallbacks then
  18620. if (fallbacks && fallbacks.isMoreFallbacks) {
  18621. defines = fallbacks.reduce(defines);
  18622. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18623. }
  18624. else {
  18625. BABYLON.Tools.Error("Unable to compile effect: ");
  18626. if (this.name.vertexElement) {
  18627. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18628. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18629. }
  18630. else if (this.name.vertex) {
  18631. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18632. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18633. }
  18634. else {
  18635. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18636. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18637. }
  18638. BABYLON.Tools.Error("Defines: " + defines);
  18639. BABYLON.Tools.Error("Error: " + e.message);
  18640. this._compilationError = e.message;
  18641. if (this.onError) {
  18642. this.onError(this, this._compilationError);
  18643. }
  18644. }
  18645. }
  18646. };
  18647. Effect.prototype._bindTexture = function (channel, texture) {
  18648. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18649. };
  18650. Effect.prototype.setTexture = function (channel, texture) {
  18651. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18652. };
  18653. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18654. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18655. };
  18656. //public _cacheMatrix(uniformName, matrix) {
  18657. // if (!this._valueCache[uniformName]) {
  18658. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18659. // }
  18660. // for (var index = 0; index < 16; index++) {
  18661. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18662. // }
  18663. //};
  18664. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18665. if (!this._valueCache[uniformName]) {
  18666. this._valueCache[uniformName] = [x, y];
  18667. return;
  18668. }
  18669. this._valueCache[uniformName][0] = x;
  18670. this._valueCache[uniformName][1] = y;
  18671. };
  18672. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18673. if (!this._valueCache[uniformName]) {
  18674. this._valueCache[uniformName] = [x, y, z];
  18675. return;
  18676. }
  18677. this._valueCache[uniformName][0] = x;
  18678. this._valueCache[uniformName][1] = y;
  18679. this._valueCache[uniformName][2] = z;
  18680. };
  18681. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18682. if (!this._valueCache[uniformName]) {
  18683. this._valueCache[uniformName] = [x, y, z, w];
  18684. return;
  18685. }
  18686. this._valueCache[uniformName][0] = x;
  18687. this._valueCache[uniformName][1] = y;
  18688. this._valueCache[uniformName][2] = z;
  18689. this._valueCache[uniformName][3] = w;
  18690. };
  18691. Effect.prototype.setArray = function (uniformName, array) {
  18692. this._engine.setArray(this.getUniform(uniformName), array);
  18693. return this;
  18694. };
  18695. Effect.prototype.setArray2 = function (uniformName, array) {
  18696. this._engine.setArray2(this.getUniform(uniformName), array);
  18697. return this;
  18698. };
  18699. Effect.prototype.setArray3 = function (uniformName, array) {
  18700. this._engine.setArray3(this.getUniform(uniformName), array);
  18701. return this;
  18702. };
  18703. Effect.prototype.setArray4 = function (uniformName, array) {
  18704. this._engine.setArray4(this.getUniform(uniformName), array);
  18705. return this;
  18706. };
  18707. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18708. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18709. return this;
  18710. };
  18711. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18712. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18713. // return;
  18714. //this._cacheMatrix(uniformName, matrix);
  18715. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18716. return this;
  18717. };
  18718. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18719. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18720. return this;
  18721. };
  18722. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18723. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18724. return this;
  18725. };
  18726. Effect.prototype.setFloat = function (uniformName, value) {
  18727. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18728. return this;
  18729. this._valueCache[uniformName] = value;
  18730. this._engine.setFloat(this.getUniform(uniformName), value);
  18731. return this;
  18732. };
  18733. Effect.prototype.setBool = function (uniformName, bool) {
  18734. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18735. return this;
  18736. this._valueCache[uniformName] = bool;
  18737. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18738. return this;
  18739. };
  18740. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18741. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18742. return this;
  18743. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18744. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18745. return this;
  18746. };
  18747. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18748. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18749. return this;
  18750. this._cacheFloat2(uniformName, x, y);
  18751. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18752. return this;
  18753. };
  18754. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18755. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18756. return this;
  18757. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18758. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18759. return this;
  18760. };
  18761. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18762. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18763. return this;
  18764. this._cacheFloat3(uniformName, x, y, z);
  18765. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18766. return this;
  18767. };
  18768. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18769. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18770. return this;
  18771. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18772. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18773. return this;
  18774. };
  18775. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18776. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18777. return this;
  18778. this._cacheFloat4(uniformName, x, y, z, w);
  18779. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18780. return this;
  18781. };
  18782. Effect.prototype.setColor3 = function (uniformName, color3) {
  18783. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18784. return this;
  18785. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18786. this._engine.setColor3(this.getUniform(uniformName), color3);
  18787. return this;
  18788. };
  18789. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18790. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  18791. return this;
  18792. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18793. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18794. return this;
  18795. };
  18796. // Statics
  18797. Effect.ShadersStore = {};
  18798. return Effect;
  18799. })();
  18800. BABYLON.Effect = Effect;
  18801. })(BABYLON || (BABYLON = {}));
  18802. var BABYLON;
  18803. (function (BABYLON) {
  18804. var Material = (function () {
  18805. function Material(name, scene, doNotAdd) {
  18806. this.name = name;
  18807. this.checkReadyOnEveryCall = true;
  18808. this.checkReadyOnlyOnce = false;
  18809. this.state = "";
  18810. this.alpha = 1.0;
  18811. this.backFaceCulling = true;
  18812. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18813. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18814. this.disableDepthWrite = false;
  18815. this.fogEnabled = true;
  18816. this._wasPreviouslyReady = false;
  18817. this._fillMode = Material.TriangleFillMode;
  18818. this.pointSize = 1.0;
  18819. this.zOffset = 0;
  18820. this.id = name;
  18821. this._scene = scene;
  18822. if (!doNotAdd) {
  18823. scene.materials.push(this);
  18824. }
  18825. }
  18826. Object.defineProperty(Material, "TriangleFillMode", {
  18827. get: function () {
  18828. return Material._TriangleFillMode;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. Object.defineProperty(Material, "WireFrameFillMode", {
  18834. get: function () {
  18835. return Material._WireFrameFillMode;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(Material, "PointFillMode", {
  18841. get: function () {
  18842. return Material._PointFillMode;
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18848. get: function () {
  18849. return Material._ClockWiseSideOrientation;
  18850. },
  18851. enumerable: true,
  18852. configurable: true
  18853. });
  18854. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18855. get: function () {
  18856. return Material._CounterClockWiseSideOrientation;
  18857. },
  18858. enumerable: true,
  18859. configurable: true
  18860. });
  18861. Object.defineProperty(Material.prototype, "wireframe", {
  18862. get: function () {
  18863. return this._fillMode === Material.WireFrameFillMode;
  18864. },
  18865. set: function (value) {
  18866. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18867. },
  18868. enumerable: true,
  18869. configurable: true
  18870. });
  18871. Object.defineProperty(Material.prototype, "pointsCloud", {
  18872. get: function () {
  18873. return this._fillMode === Material.PointFillMode;
  18874. },
  18875. set: function (value) {
  18876. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18877. },
  18878. enumerable: true,
  18879. configurable: true
  18880. });
  18881. Object.defineProperty(Material.prototype, "fillMode", {
  18882. get: function () {
  18883. return this._fillMode;
  18884. },
  18885. set: function (value) {
  18886. this._fillMode = value;
  18887. },
  18888. enumerable: true,
  18889. configurable: true
  18890. });
  18891. Material.prototype.isReady = function (mesh, useInstances) {
  18892. return true;
  18893. };
  18894. Material.prototype.getEffect = function () {
  18895. return this._effect;
  18896. };
  18897. Material.prototype.getScene = function () {
  18898. return this._scene;
  18899. };
  18900. Material.prototype.needAlphaBlending = function () {
  18901. return (this.alpha < 1.0);
  18902. };
  18903. Material.prototype.needAlphaTesting = function () {
  18904. return false;
  18905. };
  18906. Material.prototype.getAlphaTestTexture = function () {
  18907. return null;
  18908. };
  18909. Material.prototype.trackCreation = function (onCompiled, onError) {
  18910. };
  18911. Material.prototype._preBind = function () {
  18912. var engine = this._scene.getEngine();
  18913. engine.enableEffect(this._effect);
  18914. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18915. };
  18916. Material.prototype.bind = function (world, mesh) {
  18917. this._scene._cachedMaterial = this;
  18918. if (this.onBind) {
  18919. this.onBind(this, mesh);
  18920. }
  18921. if (this.disableDepthWrite) {
  18922. var engine = this._scene.getEngine();
  18923. this._cachedDepthWriteState = engine.getDepthWrite();
  18924. engine.setDepthWrite(false);
  18925. }
  18926. };
  18927. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18928. };
  18929. Material.prototype.unbind = function () {
  18930. if (this.disableDepthWrite) {
  18931. var engine = this._scene.getEngine();
  18932. engine.setDepthWrite(this._cachedDepthWriteState);
  18933. }
  18934. };
  18935. Material.prototype.clone = function (name) {
  18936. return null;
  18937. };
  18938. Material.prototype.getBindedMeshes = function () {
  18939. var result = new Array();
  18940. for (var index = 0; index < this._scene.meshes.length; index++) {
  18941. var mesh = this._scene.meshes[index];
  18942. if (mesh.material === this) {
  18943. result.push(mesh);
  18944. }
  18945. }
  18946. return result;
  18947. };
  18948. Material.prototype.dispose = function (forceDisposeEffect) {
  18949. // Remove from scene
  18950. var index = this._scene.materials.indexOf(this);
  18951. if (index >= 0) {
  18952. this._scene.materials.splice(index, 1);
  18953. }
  18954. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18955. if (forceDisposeEffect && this._effect) {
  18956. this._scene.getEngine()._releaseEffect(this._effect);
  18957. this._effect = null;
  18958. }
  18959. // Remove from meshes
  18960. for (index = 0; index < this._scene.meshes.length; index++) {
  18961. var mesh = this._scene.meshes[index];
  18962. if (mesh.material === this) {
  18963. mesh.material = null;
  18964. }
  18965. }
  18966. // Callback
  18967. if (this.onDispose) {
  18968. this.onDispose();
  18969. }
  18970. };
  18971. Material.prototype.copyTo = function (other) {
  18972. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18973. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18974. other.alpha = this.alpha;
  18975. other.fillMode = this.fillMode;
  18976. other.backFaceCulling = this.backFaceCulling;
  18977. other.wireframe = this.wireframe;
  18978. other.fogEnabled = this.fogEnabled;
  18979. other.wireframe = this.wireframe;
  18980. other.zOffset = this.zOffset;
  18981. other.alphaMode = this.alphaMode;
  18982. other.sideOrientation = this.sideOrientation;
  18983. other.disableDepthWrite = this.disableDepthWrite;
  18984. other.pointSize = this.pointSize;
  18985. other.pointsCloud = this.pointsCloud;
  18986. };
  18987. Material._TriangleFillMode = 0;
  18988. Material._WireFrameFillMode = 1;
  18989. Material._PointFillMode = 2;
  18990. Material._ClockWiseSideOrientation = 0;
  18991. Material._CounterClockWiseSideOrientation = 1;
  18992. return Material;
  18993. })();
  18994. BABYLON.Material = Material;
  18995. })(BABYLON || (BABYLON = {}));
  18996. var BABYLON;
  18997. (function (BABYLON) {
  18998. var maxSimultaneousLights = 4;
  18999. var FresnelParameters = (function () {
  19000. function FresnelParameters() {
  19001. this.isEnabled = true;
  19002. this.leftColor = BABYLON.Color3.White();
  19003. this.rightColor = BABYLON.Color3.Black();
  19004. this.bias = 0;
  19005. this.power = 1;
  19006. }
  19007. FresnelParameters.prototype.clone = function () {
  19008. var newFresnelParameters = new FresnelParameters();
  19009. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19010. return new FresnelParameters;
  19011. };
  19012. return FresnelParameters;
  19013. })();
  19014. BABYLON.FresnelParameters = FresnelParameters;
  19015. var StandardMaterialDefines = (function () {
  19016. function StandardMaterialDefines() {
  19017. this.DIFFUSE = false;
  19018. this.AMBIENT = false;
  19019. this.OPACITY = false;
  19020. this.OPACITYRGB = false;
  19021. this.REFLECTION = false;
  19022. this.EMISSIVE = false;
  19023. this.SPECULAR = false;
  19024. this.BUMP = false;
  19025. this.SPECULAROVERALPHA = false;
  19026. this.CLIPPLANE = false;
  19027. this.ALPHATEST = false;
  19028. this.ALPHAFROMDIFFUSE = false;
  19029. this.POINTSIZE = false;
  19030. this.FOG = false;
  19031. this.LIGHT0 = false;
  19032. this.LIGHT1 = false;
  19033. this.LIGHT2 = false;
  19034. this.LIGHT3 = false;
  19035. this.SPOTLIGHT0 = false;
  19036. this.SPOTLIGHT1 = false;
  19037. this.SPOTLIGHT2 = false;
  19038. this.SPOTLIGHT3 = false;
  19039. this.HEMILIGHT0 = false;
  19040. this.HEMILIGHT1 = false;
  19041. this.HEMILIGHT2 = false;
  19042. this.HEMILIGHT3 = false;
  19043. this.POINTDIRLIGHT0 = false;
  19044. this.POINTDIRLIGHT1 = false;
  19045. this.POINTDIRLIGHT2 = false;
  19046. this.POINTDIRLIGHT3 = false;
  19047. this.SPECULARTERM = false;
  19048. this.SHADOW0 = false;
  19049. this.SHADOW1 = false;
  19050. this.SHADOW2 = false;
  19051. this.SHADOW3 = false;
  19052. this.SHADOWS = false;
  19053. this.SHADOWVSM0 = false;
  19054. this.SHADOWVSM1 = false;
  19055. this.SHADOWVSM2 = false;
  19056. this.SHADOWVSM3 = false;
  19057. this.SHADOWPCF0 = false;
  19058. this.SHADOWPCF1 = false;
  19059. this.SHADOWPCF2 = false;
  19060. this.SHADOWPCF3 = false;
  19061. this.DIFFUSEFRESNEL = false;
  19062. this.OPACITYFRESNEL = false;
  19063. this.REFLECTIONFRESNEL = false;
  19064. this.EMISSIVEFRESNEL = false;
  19065. this.FRESNEL = false;
  19066. this.NORMAL = false;
  19067. this.UV1 = false;
  19068. this.UV2 = false;
  19069. this.VERTEXCOLOR = false;
  19070. this.VERTEXALPHA = false;
  19071. this.BONES = false;
  19072. this.BONES4 = false;
  19073. this.BonesPerMesh = 0;
  19074. this.INSTANCES = false;
  19075. this.GLOSSINESS = false;
  19076. this.ROUGHNESS = false;
  19077. this.EMISSIVEASILLUMINATION = false;
  19078. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19079. this.LIGHTMAP = false;
  19080. this.INVERTCUBICMAP = false;
  19081. this._keys = Object.keys(this);
  19082. }
  19083. StandardMaterialDefines.prototype.isEqual = function (other) {
  19084. for (var index = 0; index < this._keys.length; index++) {
  19085. var prop = this._keys[index];
  19086. if (this[prop] !== other[prop]) {
  19087. return false;
  19088. }
  19089. }
  19090. return true;
  19091. };
  19092. StandardMaterialDefines.prototype.cloneTo = function (other) {
  19093. for (var index = 0; index < this._keys.length; index++) {
  19094. var prop = this._keys[index];
  19095. other[prop] = this[prop];
  19096. }
  19097. };
  19098. StandardMaterialDefines.prototype.reset = function () {
  19099. for (var index = 0; index < this._keys.length; index++) {
  19100. var prop = this._keys[index];
  19101. if (prop === "BonesPerMesh") {
  19102. this[prop] = 0;
  19103. continue;
  19104. }
  19105. this[prop] = false;
  19106. }
  19107. };
  19108. StandardMaterialDefines.prototype.toString = function () {
  19109. var result = "";
  19110. for (var index = 0; index < this._keys.length; index++) {
  19111. var prop = this._keys[index];
  19112. if (prop === "BonesPerMesh" && this[prop] > 0) {
  19113. result += "#define BonesPerMesh " + this[prop] + "\n";
  19114. continue;
  19115. }
  19116. if (this[prop]) {
  19117. result += "#define " + prop + "\n";
  19118. }
  19119. }
  19120. return result;
  19121. };
  19122. return StandardMaterialDefines;
  19123. })();
  19124. var StandardMaterial = (function (_super) {
  19125. __extends(StandardMaterial, _super);
  19126. function StandardMaterial(name, scene) {
  19127. var _this = this;
  19128. _super.call(this, name, scene);
  19129. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19130. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19131. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19132. this.specularPower = 64;
  19133. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19134. this.useAlphaFromDiffuseTexture = false;
  19135. this.useEmissiveAsIllumination = false;
  19136. this.useReflectionFresnelFromSpecular = false;
  19137. this.useSpecularOverAlpha = true;
  19138. this.roughness = 0;
  19139. this.lightmapThreshold = 0;
  19140. this.useGlossinessFromSpecularMapAlpha = false;
  19141. this._renderTargets = new BABYLON.SmartArray(16);
  19142. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19143. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19144. this._scaledDiffuse = new BABYLON.Color3();
  19145. this._scaledSpecular = new BABYLON.Color3();
  19146. this._defines = new StandardMaterialDefines();
  19147. this._cachedDefines = new StandardMaterialDefines();
  19148. this._cachedDefines.BonesPerMesh = -1;
  19149. this.getRenderTargetTextures = function () {
  19150. _this._renderTargets.reset();
  19151. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19152. _this._renderTargets.push(_this.reflectionTexture);
  19153. }
  19154. return _this._renderTargets;
  19155. };
  19156. }
  19157. StandardMaterial.prototype.needAlphaBlending = function () {
  19158. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19159. };
  19160. StandardMaterial.prototype.needAlphaTesting = function () {
  19161. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19162. };
  19163. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19164. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19165. };
  19166. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19167. return this.diffuseTexture;
  19168. };
  19169. // Methods
  19170. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19171. if (this.checkReadyOnlyOnce) {
  19172. if (this._wasPreviouslyReady) {
  19173. return true;
  19174. }
  19175. }
  19176. var scene = this.getScene();
  19177. if (!this.checkReadyOnEveryCall) {
  19178. if (this._renderId === scene.getRenderId()) {
  19179. return true;
  19180. }
  19181. }
  19182. var engine = scene.getEngine();
  19183. var needNormals = false;
  19184. var needUVs = false;
  19185. this._defines.reset();
  19186. // Textures
  19187. if (scene.texturesEnabled) {
  19188. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19189. if (!this.diffuseTexture.isReady()) {
  19190. return false;
  19191. }
  19192. else {
  19193. needUVs = true;
  19194. this._defines.DIFFUSE = true;
  19195. }
  19196. }
  19197. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19198. if (!this.ambientTexture.isReady()) {
  19199. return false;
  19200. }
  19201. else {
  19202. needUVs = true;
  19203. this._defines.AMBIENT = true;
  19204. }
  19205. }
  19206. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19207. if (!this.opacityTexture.isReady()) {
  19208. return false;
  19209. }
  19210. else {
  19211. needUVs = true;
  19212. this._defines.OPACITY = true;
  19213. if (this.opacityTexture.getAlphaFromRGB) {
  19214. this._defines.OPACITYRGB = true;
  19215. }
  19216. }
  19217. }
  19218. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19219. if (!this.reflectionTexture.isReady()) {
  19220. return false;
  19221. }
  19222. else {
  19223. needNormals = true;
  19224. needUVs = true;
  19225. this._defines.REFLECTION = true;
  19226. if (this.roughness > 0) {
  19227. this._defines.ROUGHNESS = true;
  19228. }
  19229. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19230. this._defines.INVERTCUBICMAP = true;
  19231. }
  19232. }
  19233. }
  19234. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19235. if (!this.emissiveTexture.isReady()) {
  19236. return false;
  19237. }
  19238. else {
  19239. needUVs = true;
  19240. this._defines.EMISSIVE = true;
  19241. }
  19242. }
  19243. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19244. if (!this.lightmapTexture.isReady()) {
  19245. return false;
  19246. }
  19247. else {
  19248. needUVs = true;
  19249. this._defines.LIGHTMAP = true;
  19250. }
  19251. }
  19252. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19253. if (!this.specularTexture.isReady()) {
  19254. return false;
  19255. }
  19256. else {
  19257. needUVs = true;
  19258. this._defines.SPECULAR = true;
  19259. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19260. }
  19261. }
  19262. }
  19263. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19264. if (!this.bumpTexture.isReady()) {
  19265. return false;
  19266. }
  19267. else {
  19268. needUVs = true;
  19269. this._defines.BUMP = true;
  19270. }
  19271. }
  19272. // Effect
  19273. if (scene.clipPlane) {
  19274. this._defines.CLIPPLANE = true;
  19275. }
  19276. if (engine.getAlphaTesting()) {
  19277. this._defines.ALPHATEST = true;
  19278. }
  19279. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19280. this._defines.ALPHAFROMDIFFUSE = true;
  19281. }
  19282. if (this.useEmissiveAsIllumination) {
  19283. this._defines.EMISSIVEASILLUMINATION = true;
  19284. }
  19285. if (this.useReflectionFresnelFromSpecular) {
  19286. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19287. }
  19288. // Point size
  19289. if (this.pointsCloud || scene.forcePointsCloud) {
  19290. this._defines.POINTSIZE = true;
  19291. }
  19292. // Fog
  19293. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19294. this._defines.FOG = true;
  19295. }
  19296. var lightIndex = 0;
  19297. if (scene.lightsEnabled) {
  19298. for (var index = 0; index < scene.lights.length; index++) {
  19299. var light = scene.lights[index];
  19300. if (!light.isEnabled()) {
  19301. continue;
  19302. }
  19303. // Excluded check
  19304. if (light._excludedMeshesIds.length > 0) {
  19305. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19306. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19307. if (excludedMesh) {
  19308. light.excludedMeshes.push(excludedMesh);
  19309. }
  19310. }
  19311. light._excludedMeshesIds = [];
  19312. }
  19313. // Included check
  19314. if (light._includedOnlyMeshesIds.length > 0) {
  19315. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19316. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19317. if (includedOnlyMesh) {
  19318. light.includedOnlyMeshes.push(includedOnlyMesh);
  19319. }
  19320. }
  19321. light._includedOnlyMeshesIds = [];
  19322. }
  19323. if (!light.canAffectMesh(mesh)) {
  19324. continue;
  19325. }
  19326. needNormals = true;
  19327. this._defines["LIGHT" + lightIndex] = true;
  19328. var type;
  19329. if (light instanceof BABYLON.SpotLight) {
  19330. type = "SPOTLIGHT" + lightIndex;
  19331. }
  19332. else if (light instanceof BABYLON.HemisphericLight) {
  19333. type = "HEMILIGHT" + lightIndex;
  19334. }
  19335. else {
  19336. type = "POINTDIRLIGHT" + lightIndex;
  19337. }
  19338. this._defines[type] = true;
  19339. // Specular
  19340. if (!light.specular.equalsFloats(0, 0, 0)) {
  19341. this._defines.SPECULARTERM = true;
  19342. }
  19343. // Shadows
  19344. if (scene.shadowsEnabled) {
  19345. var shadowGenerator = light.getShadowGenerator();
  19346. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19347. this._defines["SHADOW" + lightIndex] = true;
  19348. this._defines.SHADOWS = true;
  19349. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19350. this._defines["SHADOWVSM" + lightIndex] = true;
  19351. }
  19352. if (shadowGenerator.usePoissonSampling) {
  19353. this._defines["SHADOWPCF" + lightIndex] = true;
  19354. }
  19355. }
  19356. }
  19357. lightIndex++;
  19358. if (lightIndex === maxSimultaneousLights)
  19359. break;
  19360. }
  19361. }
  19362. if (StandardMaterial.FresnelEnabled) {
  19363. // Fresnel
  19364. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19365. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19366. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19367. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19368. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19369. this._defines.DIFFUSEFRESNEL = true;
  19370. }
  19371. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19372. this._defines.OPACITYFRESNEL = true;
  19373. }
  19374. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19375. this._defines.REFLECTIONFRESNEL = true;
  19376. }
  19377. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19378. this._defines.EMISSIVEFRESNEL = true;
  19379. }
  19380. needNormals = true;
  19381. this._defines.FRESNEL = true;
  19382. }
  19383. }
  19384. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19385. this._defines.SPECULAROVERALPHA = true;
  19386. }
  19387. // Attribs
  19388. if (mesh) {
  19389. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19390. this._defines.NORMAL = true;
  19391. }
  19392. if (needUVs) {
  19393. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19394. this._defines.UV1 = true;
  19395. }
  19396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19397. this._defines.UV2 = true;
  19398. }
  19399. }
  19400. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19401. this._defines.VERTEXCOLOR = true;
  19402. if (mesh.hasVertexAlpha) {
  19403. this._defines.VERTEXALPHA = true;
  19404. }
  19405. }
  19406. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19407. this._defines.BONES = true;
  19408. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19409. this._defines.BONES4 = true;
  19410. }
  19411. // Instances
  19412. if (useInstances) {
  19413. this._defines.INSTANCES = true;
  19414. }
  19415. }
  19416. // Get correct effect
  19417. if (!this._defines.isEqual(this._cachedDefines)) {
  19418. this._defines.cloneTo(this._cachedDefines);
  19419. scene.resetCachedMaterial();
  19420. // Fallbacks
  19421. var fallbacks = new BABYLON.EffectFallbacks();
  19422. if (this._defines.REFLECTION) {
  19423. fallbacks.addFallback(0, "REFLECTION");
  19424. }
  19425. if (this._defines.SPECULAR) {
  19426. fallbacks.addFallback(0, "SPECULAR");
  19427. }
  19428. if (this._defines.BUMP) {
  19429. fallbacks.addFallback(0, "BUMP");
  19430. }
  19431. if (this._defines.SPECULAROVERALPHA) {
  19432. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  19433. }
  19434. if (this._defines.FOG) {
  19435. fallbacks.addFallback(1, "FOG");
  19436. }
  19437. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19438. if (!this._defines["LIGHT" + lightIndex]) {
  19439. continue;
  19440. }
  19441. if (lightIndex > 0) {
  19442. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19443. }
  19444. if (this._defines["SHADOW" + lightIndex]) {
  19445. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19446. }
  19447. if (this._defines["SHADOWPCF" + lightIndex]) {
  19448. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19449. }
  19450. if (this._defines["SHADOWVSM" + lightIndex]) {
  19451. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19452. }
  19453. }
  19454. if (this._defines.SPECULARTERM) {
  19455. fallbacks.addFallback(0, "SPECULARTERM");
  19456. }
  19457. if (this._defines.DIFFUSEFRESNEL) {
  19458. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  19459. }
  19460. if (this._defines.OPACITYFRESNEL) {
  19461. fallbacks.addFallback(2, "OPACITYFRESNEL");
  19462. }
  19463. if (this._defines.REFLECTIONFRESNEL) {
  19464. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  19465. }
  19466. if (this._defines.EMISSIVEFRESNEL) {
  19467. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  19468. }
  19469. if (this._defines.FRESNEL) {
  19470. fallbacks.addFallback(4, "FRESNEL");
  19471. }
  19472. if (this._defines.BONES4) {
  19473. fallbacks.addFallback(0, "BONES4");
  19474. }
  19475. //Attributes
  19476. var attribs = [BABYLON.VertexBuffer.PositionKind];
  19477. if (this._defines.NORMAL) {
  19478. attribs.push(BABYLON.VertexBuffer.NormalKind);
  19479. }
  19480. if (this._defines.UV1) {
  19481. attribs.push(BABYLON.VertexBuffer.UVKind);
  19482. }
  19483. if (this._defines.UV2) {
  19484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  19485. }
  19486. if (this._defines.VERTEXCOLOR) {
  19487. attribs.push(BABYLON.VertexBuffer.ColorKind);
  19488. }
  19489. if (this._defines.BONES) {
  19490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19492. }
  19493. if (this._defines.INSTANCES) {
  19494. attribs.push("world0");
  19495. attribs.push("world1");
  19496. attribs.push("world2");
  19497. attribs.push("world3");
  19498. }
  19499. // Legacy browser patch
  19500. var shaderName = "default";
  19501. if (!scene.getEngine().getCaps().standardDerivatives) {
  19502. shaderName = "legacydefault";
  19503. }
  19504. var join = this._defines.toString();
  19505. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  19506. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  19507. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  19508. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  19509. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  19510. "vFogInfos", "vFogColor", "pointSize",
  19511. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  19512. "mBones",
  19513. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  19514. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  19515. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor",
  19516. "roughness"
  19517. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  19518. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  19519. ], join, fallbacks, this.onCompiled, this.onError);
  19520. }
  19521. if (!this._effect.isReady()) {
  19522. return false;
  19523. }
  19524. this._renderId = scene.getRenderId();
  19525. this._wasPreviouslyReady = true;
  19526. return true;
  19527. };
  19528. StandardMaterial.prototype.unbind = function () {
  19529. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19530. this._effect.setTexture("reflection2DSampler", null);
  19531. }
  19532. _super.prototype.unbind.call(this);
  19533. };
  19534. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19535. this._effect.setMatrix("world", world);
  19536. };
  19537. StandardMaterial.prototype.bind = function (world, mesh) {
  19538. var scene = this.getScene();
  19539. // Matrices
  19540. this.bindOnlyWorldMatrix(world);
  19541. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19542. // Bones
  19543. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19544. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19545. }
  19546. if (scene.getCachedMaterial() !== this) {
  19547. if (StandardMaterial.FresnelEnabled) {
  19548. // Fresnel
  19549. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19550. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19551. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19552. }
  19553. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19554. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19555. }
  19556. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19557. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19558. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19559. }
  19560. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19561. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19562. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19563. }
  19564. }
  19565. // Textures
  19566. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19567. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19568. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19569. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19570. }
  19571. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19572. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19573. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19574. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19575. }
  19576. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19577. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19578. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19579. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19580. }
  19581. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19582. if (this.reflectionTexture.isCube) {
  19583. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19584. if (this._defines.ROUGHNESS) {
  19585. this._effect.setFloat("roughness", this.roughness);
  19586. }
  19587. }
  19588. else {
  19589. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19590. }
  19591. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19592. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE ? BABYLON.Texture.CUBIC_MODE : this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19593. }
  19594. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19595. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19596. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19597. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19598. }
  19599. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19600. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19601. this._effect.setFloat3("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level, this.lightmapThreshold);
  19602. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19603. }
  19604. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19605. this._effect.setTexture("specularSampler", this.specularTexture);
  19606. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19607. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19608. }
  19609. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19610. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19611. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19612. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19613. }
  19614. // Clip plane
  19615. if (scene.clipPlane) {
  19616. var clipPlane = scene.clipPlane;
  19617. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19618. }
  19619. // Point size
  19620. if (this.pointsCloud) {
  19621. this._effect.setFloat("pointSize", this.pointSize);
  19622. }
  19623. // Colors
  19624. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19625. // Scaling down color according to emissive
  19626. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19627. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19628. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19629. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19630. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19631. if (this._defines.SPECULARTERM) {
  19632. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19633. }
  19634. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19635. }
  19636. // Scaling down color according to emissive
  19637. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19638. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19639. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19640. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19641. if (scene.lightsEnabled) {
  19642. var lightIndex = 0;
  19643. for (var index = 0; index < scene.lights.length; index++) {
  19644. var light = scene.lights[index];
  19645. if (!light.isEnabled()) {
  19646. continue;
  19647. }
  19648. if (!light.canAffectMesh(mesh)) {
  19649. continue;
  19650. }
  19651. if (light instanceof BABYLON.PointLight) {
  19652. // Point Light
  19653. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19654. }
  19655. else if (light instanceof BABYLON.DirectionalLight) {
  19656. // Directional Light
  19657. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19658. }
  19659. else if (light instanceof BABYLON.SpotLight) {
  19660. // Spot Light
  19661. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19662. }
  19663. else if (light instanceof BABYLON.HemisphericLight) {
  19664. // Hemispheric Light
  19665. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19666. }
  19667. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19668. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19669. if (this._defines.SPECULARTERM) {
  19670. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19671. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19672. }
  19673. // Shadows
  19674. if (scene.shadowsEnabled) {
  19675. var shadowGenerator = light.getShadowGenerator();
  19676. if (mesh.receiveShadows && shadowGenerator) {
  19677. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19678. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19679. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19680. }
  19681. }
  19682. lightIndex++;
  19683. if (lightIndex === maxSimultaneousLights)
  19684. break;
  19685. }
  19686. }
  19687. // View
  19688. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19689. this._effect.setMatrix("view", scene.getViewMatrix());
  19690. }
  19691. // Fog
  19692. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19693. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19694. this._effect.setColor3("vFogColor", scene.fogColor);
  19695. }
  19696. _super.prototype.bind.call(this, world, mesh);
  19697. };
  19698. StandardMaterial.prototype.getAnimatables = function () {
  19699. var results = [];
  19700. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19701. results.push(this.diffuseTexture);
  19702. }
  19703. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19704. results.push(this.ambientTexture);
  19705. }
  19706. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19707. results.push(this.opacityTexture);
  19708. }
  19709. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19710. results.push(this.reflectionTexture);
  19711. }
  19712. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19713. results.push(this.emissiveTexture);
  19714. }
  19715. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19716. results.push(this.specularTexture);
  19717. }
  19718. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19719. results.push(this.bumpTexture);
  19720. }
  19721. return results;
  19722. };
  19723. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19724. if (this.diffuseTexture) {
  19725. this.diffuseTexture.dispose();
  19726. }
  19727. if (this.ambientTexture) {
  19728. this.ambientTexture.dispose();
  19729. }
  19730. if (this.opacityTexture) {
  19731. this.opacityTexture.dispose();
  19732. }
  19733. if (this.reflectionTexture) {
  19734. this.reflectionTexture.dispose();
  19735. }
  19736. if (this.emissiveTexture) {
  19737. this.emissiveTexture.dispose();
  19738. }
  19739. if (this.specularTexture) {
  19740. this.specularTexture.dispose();
  19741. }
  19742. if (this.bumpTexture) {
  19743. this.bumpTexture.dispose();
  19744. }
  19745. _super.prototype.dispose.call(this, forceDisposeEffect);
  19746. };
  19747. StandardMaterial.prototype.clone = function (name) {
  19748. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19749. // Base material
  19750. this.copyTo(newStandardMaterial);
  19751. // Standard material
  19752. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19753. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19754. }
  19755. if (this.ambientTexture && this.ambientTexture.clone) {
  19756. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19757. }
  19758. if (this.opacityTexture && this.opacityTexture.clone) {
  19759. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19760. }
  19761. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19762. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19763. }
  19764. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19765. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19766. }
  19767. if (this.specularTexture && this.specularTexture.clone) {
  19768. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19769. }
  19770. if (this.bumpTexture && this.bumpTexture.clone) {
  19771. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19772. }
  19773. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19774. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19775. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19776. newStandardMaterial.lightmapThreshold = this.lightmapThreshold;
  19777. }
  19778. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19779. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19780. newStandardMaterial.specularColor = this.specularColor.clone();
  19781. newStandardMaterial.specularPower = this.specularPower;
  19782. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19783. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19784. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19785. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19786. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19787. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19788. newStandardMaterial.roughness = this.roughness;
  19789. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19790. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19791. }
  19792. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19793. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19794. }
  19795. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19796. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19797. }
  19798. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19799. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19800. }
  19801. return newStandardMaterial;
  19802. };
  19803. // Statics
  19804. // Flags used to enable or disable a type of texture for all Standard Materials
  19805. StandardMaterial.DiffuseTextureEnabled = true;
  19806. StandardMaterial.AmbientTextureEnabled = true;
  19807. StandardMaterial.OpacityTextureEnabled = true;
  19808. StandardMaterial.ReflectionTextureEnabled = true;
  19809. StandardMaterial.EmissiveTextureEnabled = true;
  19810. StandardMaterial.SpecularTextureEnabled = true;
  19811. StandardMaterial.BumpTextureEnabled = true;
  19812. StandardMaterial.FresnelEnabled = true;
  19813. StandardMaterial.LightmapEnabled = true;
  19814. return StandardMaterial;
  19815. })(BABYLON.Material);
  19816. BABYLON.StandardMaterial = StandardMaterial;
  19817. })(BABYLON || (BABYLON = {}));
  19818. var BABYLON;
  19819. (function (BABYLON) {
  19820. var MultiMaterial = (function (_super) {
  19821. __extends(MultiMaterial, _super);
  19822. function MultiMaterial(name, scene) {
  19823. _super.call(this, name, scene, true);
  19824. this.subMaterials = new Array();
  19825. scene.multiMaterials.push(this);
  19826. }
  19827. // Properties
  19828. MultiMaterial.prototype.getSubMaterial = function (index) {
  19829. if (index < 0 || index >= this.subMaterials.length) {
  19830. return this.getScene().defaultMaterial;
  19831. }
  19832. return this.subMaterials[index];
  19833. };
  19834. // Methods
  19835. MultiMaterial.prototype.isReady = function (mesh) {
  19836. for (var index = 0; index < this.subMaterials.length; index++) {
  19837. var subMaterial = this.subMaterials[index];
  19838. if (subMaterial) {
  19839. if (!this.subMaterials[index].isReady(mesh)) {
  19840. return false;
  19841. }
  19842. }
  19843. }
  19844. return true;
  19845. };
  19846. MultiMaterial.prototype.clone = function (name) {
  19847. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19848. for (var index = 0; index < this.subMaterials.length; index++) {
  19849. var subMaterial = this.subMaterials[index];
  19850. newMultiMaterial.subMaterials.push(subMaterial);
  19851. }
  19852. return newMultiMaterial;
  19853. };
  19854. return MultiMaterial;
  19855. })(BABYLON.Material);
  19856. BABYLON.MultiMaterial = MultiMaterial;
  19857. })(BABYLON || (BABYLON = {}));
  19858. var BABYLON;
  19859. (function (BABYLON) {
  19860. var SceneLoader = (function () {
  19861. function SceneLoader() {
  19862. }
  19863. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19864. get: function () {
  19865. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19866. },
  19867. set: function (value) {
  19868. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19874. get: function () {
  19875. return SceneLoader._ShowLoadingScreen;
  19876. },
  19877. set: function (value) {
  19878. SceneLoader._ShowLoadingScreen = value;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19884. var dotPosition = sceneFilename.lastIndexOf(".");
  19885. var queryStringPosition = sceneFilename.indexOf("?");
  19886. if (queryStringPosition === -1) {
  19887. queryStringPosition = sceneFilename.length;
  19888. }
  19889. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19890. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19891. var plugin = this._registeredPlugins[index];
  19892. if (plugin.extensions.indexOf(extension) !== -1) {
  19893. return plugin;
  19894. }
  19895. }
  19896. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19897. };
  19898. // Public functions
  19899. SceneLoader.RegisterPlugin = function (plugin) {
  19900. plugin.extensions = plugin.extensions.toLowerCase();
  19901. SceneLoader._registeredPlugins.push(plugin);
  19902. };
  19903. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19904. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19905. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19906. return;
  19907. }
  19908. var loadingToken = {};
  19909. scene._addPendingData(loadingToken);
  19910. var manifestChecked = function (success) {
  19911. scene.database = database;
  19912. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19913. var importMeshFromData = function (data) {
  19914. var meshes = [];
  19915. var particleSystems = [];
  19916. var skeletons = [];
  19917. try {
  19918. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19919. if (onerror) {
  19920. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19921. }
  19922. scene._removePendingData(loadingToken);
  19923. return;
  19924. }
  19925. }
  19926. catch (e) {
  19927. if (onerror) {
  19928. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19929. }
  19930. scene._removePendingData(loadingToken);
  19931. return;
  19932. }
  19933. if (onsuccess) {
  19934. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19935. onsuccess(meshes, particleSystems, skeletons);
  19936. scene._removePendingData(loadingToken);
  19937. }
  19938. };
  19939. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19940. // Direct load
  19941. importMeshFromData(sceneFilename.substr(5));
  19942. return;
  19943. }
  19944. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19945. importMeshFromData(data);
  19946. }, progressCallBack, database);
  19947. };
  19948. if (scene.getEngine().enableOfflineSupport) {
  19949. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19950. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19951. }
  19952. else {
  19953. manifestChecked(true);
  19954. }
  19955. };
  19956. /**
  19957. * Load a scene
  19958. * @param rootUrl a string that defines the root url for scene and resources
  19959. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19960. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19961. */
  19962. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19963. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19964. };
  19965. /**
  19966. * Append a scene
  19967. * @param rootUrl a string that defines the root url for scene and resources
  19968. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19969. * @param scene is the instance of BABYLON.Scene to append to
  19970. */
  19971. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19972. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19973. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19974. return;
  19975. }
  19976. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19977. var database;
  19978. var loadingToken = {};
  19979. scene._addPendingData(loadingToken);
  19980. if (SceneLoader.ShowLoadingScreen) {
  19981. scene.getEngine().displayLoadingUI();
  19982. }
  19983. var loadSceneFromData = function (data) {
  19984. scene.database = database;
  19985. if (!plugin.load(scene, data, rootUrl)) {
  19986. if (onerror) {
  19987. onerror(scene);
  19988. }
  19989. scene._removePendingData(loadingToken);
  19990. scene.getEngine().hideLoadingUI();
  19991. return;
  19992. }
  19993. if (onsuccess) {
  19994. onsuccess(scene);
  19995. }
  19996. scene._removePendingData(loadingToken);
  19997. if (SceneLoader.ShowLoadingScreen) {
  19998. scene.executeWhenReady(function () {
  19999. scene.getEngine().hideLoadingUI();
  20000. });
  20001. }
  20002. };
  20003. var manifestChecked = function (success) {
  20004. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20005. };
  20006. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20007. // Direct load
  20008. loadSceneFromData(sceneFilename.substr(5));
  20009. return;
  20010. }
  20011. if (rootUrl.indexOf("file:") === -1) {
  20012. if (scene.getEngine().enableOfflineSupport) {
  20013. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20014. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20015. }
  20016. else {
  20017. manifestChecked(true);
  20018. }
  20019. }
  20020. else {
  20021. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20022. }
  20023. };
  20024. // Flags
  20025. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20026. SceneLoader._ShowLoadingScreen = true;
  20027. // Members
  20028. SceneLoader._registeredPlugins = new Array();
  20029. return SceneLoader;
  20030. })();
  20031. BABYLON.SceneLoader = SceneLoader;
  20032. ;
  20033. })(BABYLON || (BABYLON = {}));
  20034. var BABYLON;
  20035. (function (BABYLON) {
  20036. var Internals;
  20037. (function (Internals) {
  20038. var checkColors4 = function (colors, count) {
  20039. // Check if color3 was used
  20040. if (colors.length === count * 3) {
  20041. var colors4 = [];
  20042. for (var index = 0; index < colors.length; index += 3) {
  20043. var newIndex = (index / 3) * 4;
  20044. colors4[newIndex] = colors[index];
  20045. colors4[newIndex + 1] = colors[index + 1];
  20046. colors4[newIndex + 2] = colors[index + 2];
  20047. colors4[newIndex + 3] = 1.0;
  20048. }
  20049. return colors4;
  20050. }
  20051. return colors;
  20052. };
  20053. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  20054. var texture = null;
  20055. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  20056. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20057. texture.name = parsedTexture.name;
  20058. texture.hasAlpha = parsedTexture.hasAlpha;
  20059. texture.level = parsedTexture.level;
  20060. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20061. }
  20062. return texture;
  20063. };
  20064. var loadTexture = function (rootUrl, parsedTexture, scene) {
  20065. if (parsedTexture.isCube) {
  20066. return loadCubeTexture(rootUrl, parsedTexture, scene);
  20067. }
  20068. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20069. return null;
  20070. }
  20071. var texture;
  20072. if (parsedTexture.mirrorPlane) {
  20073. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20074. texture._waitingRenderList = parsedTexture.renderList;
  20075. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20076. }
  20077. else if (parsedTexture.isRenderTarget) {
  20078. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20079. texture._waitingRenderList = parsedTexture.renderList;
  20080. }
  20081. else {
  20082. if (parsedTexture.base64String) {
  20083. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20084. }
  20085. else {
  20086. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  20087. }
  20088. }
  20089. texture.name = parsedTexture.name;
  20090. texture.hasAlpha = parsedTexture.hasAlpha;
  20091. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  20092. texture.level = parsedTexture.level;
  20093. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  20094. texture.coordinatesMode = parsedTexture.coordinatesMode;
  20095. texture.uOffset = parsedTexture.uOffset;
  20096. texture.vOffset = parsedTexture.vOffset;
  20097. texture.uScale = parsedTexture.uScale;
  20098. texture.vScale = parsedTexture.vScale;
  20099. texture.uAng = parsedTexture.uAng;
  20100. texture.vAng = parsedTexture.vAng;
  20101. texture.wAng = parsedTexture.wAng;
  20102. texture.wrapU = parsedTexture.wrapU;
  20103. texture.wrapV = parsedTexture.wrapV;
  20104. // Animations
  20105. if (parsedTexture.animations) {
  20106. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20107. var parsedAnimation = parsedTexture.animations[animationIndex];
  20108. texture.animations.push(parseAnimation(parsedAnimation));
  20109. }
  20110. }
  20111. return texture;
  20112. };
  20113. var parseSkeleton = function (parsedSkeleton, scene) {
  20114. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  20115. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  20116. var parsedBone = parsedSkeleton.bones[index];
  20117. var parentBone = null;
  20118. if (parsedBone.parentBoneIndex > -1) {
  20119. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  20120. }
  20121. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  20122. if (parsedBone.animation) {
  20123. bone.animations.push(parseAnimation(parsedBone.animation));
  20124. }
  20125. }
  20126. return skeleton;
  20127. };
  20128. var parseFresnelParameters = function (parsedFresnelParameters) {
  20129. var fresnelParameters = new BABYLON.FresnelParameters();
  20130. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  20131. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  20132. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  20133. fresnelParameters.bias = parsedFresnelParameters.bias;
  20134. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  20135. return fresnelParameters;
  20136. };
  20137. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  20138. var material;
  20139. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  20140. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  20141. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  20142. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  20143. material.specularPower = parsedMaterial.specularPower;
  20144. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  20145. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  20146. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  20147. material.alpha = parsedMaterial.alpha;
  20148. material.id = parsedMaterial.id;
  20149. if (parsedMaterial.disableDepthWrite) {
  20150. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  20151. }
  20152. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  20153. material.backFaceCulling = parsedMaterial.backFaceCulling;
  20154. material.wireframe = parsedMaterial.wireframe;
  20155. if (parsedMaterial.diffuseTexture) {
  20156. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  20157. }
  20158. if (parsedMaterial.diffuseFresnelParameters) {
  20159. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  20160. }
  20161. if (parsedMaterial.ambientTexture) {
  20162. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  20163. }
  20164. if (parsedMaterial.opacityTexture) {
  20165. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  20166. }
  20167. if (parsedMaterial.opacityFresnelParameters) {
  20168. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  20169. }
  20170. if (parsedMaterial.reflectionTexture) {
  20171. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  20172. }
  20173. if (parsedMaterial.reflectionFresnelParameters) {
  20174. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  20175. }
  20176. if (parsedMaterial.emissiveTexture) {
  20177. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  20178. }
  20179. if (parsedMaterial.lightmapTexture) {
  20180. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  20181. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  20182. }
  20183. if (parsedMaterial.emissiveFresnelParameters) {
  20184. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  20185. }
  20186. if (parsedMaterial.specularTexture) {
  20187. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  20188. }
  20189. if (parsedMaterial.bumpTexture) {
  20190. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  20191. }
  20192. if (parsedMaterial.checkReadyOnlyOnce) {
  20193. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  20194. }
  20195. return material;
  20196. };
  20197. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20198. for (var index = 0; index < parsedData.materials.length; index++) {
  20199. var parsedMaterial = parsedData.materials[index];
  20200. if (parsedMaterial.id === id) {
  20201. return parseMaterial(parsedMaterial, scene, rootUrl);
  20202. }
  20203. }
  20204. return null;
  20205. };
  20206. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  20207. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  20208. multiMaterial.id = parsedMultiMaterial.id;
  20209. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  20210. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20211. var subMatId = parsedMultiMaterial.materials[matIndex];
  20212. if (subMatId) {
  20213. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  20214. }
  20215. else {
  20216. multiMaterial.subMaterials.push(null);
  20217. }
  20218. }
  20219. return multiMaterial;
  20220. };
  20221. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  20222. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  20223. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  20224. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  20225. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  20226. var parsedFlare = parsedLensFlareSystem.flares[index];
  20227. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  20228. }
  20229. return lensFlareSystem;
  20230. };
  20231. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  20232. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  20233. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  20234. if (parsedParticleSystem.textureName) {
  20235. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  20236. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  20237. }
  20238. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  20239. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  20240. particleSystem.minSize = parsedParticleSystem.minSize;
  20241. particleSystem.maxSize = parsedParticleSystem.maxSize;
  20242. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  20243. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  20244. particleSystem.emitter = emitter;
  20245. particleSystem.emitRate = parsedParticleSystem.emitRate;
  20246. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  20247. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  20248. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  20249. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  20250. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  20251. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  20252. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  20253. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  20254. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  20255. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  20256. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  20257. particleSystem.blendMode = parsedParticleSystem.blendMode;
  20258. particleSystem.start();
  20259. return particleSystem;
  20260. };
  20261. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  20262. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  20263. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  20264. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  20265. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  20266. shadowGenerator.getShadowMap().renderList.push(mesh);
  20267. }
  20268. if (parsedShadowGenerator.usePoissonSampling) {
  20269. shadowGenerator.usePoissonSampling = true;
  20270. }
  20271. else if (parsedShadowGenerator.useVarianceShadowMap) {
  20272. shadowGenerator.useVarianceShadowMap = true;
  20273. }
  20274. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  20275. shadowGenerator.useBlurVarianceShadowMap = true;
  20276. if (parsedShadowGenerator.blurScale) {
  20277. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  20278. }
  20279. if (parsedShadowGenerator.blurBoxOffset) {
  20280. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  20281. }
  20282. }
  20283. if (parsedShadowGenerator.bias !== undefined) {
  20284. shadowGenerator.bias = parsedShadowGenerator.bias;
  20285. }
  20286. return shadowGenerator;
  20287. };
  20288. var parseAnimation = function (parsedAnimation) {
  20289. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  20290. var dataType = parsedAnimation.dataType;
  20291. var keys = [];
  20292. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  20293. var key = parsedAnimation.keys[index];
  20294. var data;
  20295. switch (dataType) {
  20296. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  20297. data = key.values[0];
  20298. break;
  20299. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  20300. data = BABYLON.Quaternion.FromArray(key.values);
  20301. break;
  20302. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  20303. data = BABYLON.Matrix.FromArray(key.values);
  20304. break;
  20305. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  20306. default:
  20307. data = BABYLON.Vector3.FromArray(key.values);
  20308. break;
  20309. }
  20310. keys.push({
  20311. frame: key.frame,
  20312. value: data
  20313. });
  20314. }
  20315. animation.setKeys(keys);
  20316. return animation;
  20317. };
  20318. var parseLight = function (parsedLight, scene) {
  20319. var light;
  20320. switch (parsedLight.type) {
  20321. case 0:
  20322. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  20323. break;
  20324. case 1:
  20325. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20326. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  20327. break;
  20328. case 2:
  20329. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  20330. break;
  20331. case 3:
  20332. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  20333. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  20334. break;
  20335. }
  20336. light.id = parsedLight.id;
  20337. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  20338. if (parsedLight.intensity !== undefined) {
  20339. light.intensity = parsedLight.intensity;
  20340. }
  20341. if (parsedLight.range) {
  20342. light.range = parsedLight.range;
  20343. }
  20344. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  20345. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  20346. if (parsedLight.excludedMeshesIds) {
  20347. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  20348. }
  20349. // Parent
  20350. if (parsedLight.parentId) {
  20351. light._waitingParentId = parsedLight.parentId;
  20352. }
  20353. if (parsedLight.includedOnlyMeshesIds) {
  20354. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  20355. }
  20356. // Animations
  20357. if (parsedLight.animations) {
  20358. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  20359. var parsedAnimation = parsedLight.animations[animationIndex];
  20360. light.animations.push(parseAnimation(parsedAnimation));
  20361. }
  20362. }
  20363. if (parsedLight.autoAnimate) {
  20364. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  20365. }
  20366. };
  20367. var parseCamera = function (parsedCamera, scene) {
  20368. var camera;
  20369. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  20370. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  20371. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  20372. var alpha = parsedCamera.alpha;
  20373. var beta = parsedCamera.beta;
  20374. var radius = parsedCamera.radius;
  20375. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  20376. var interaxial_distance = parsedCamera.interaxial_distance;
  20377. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  20378. }
  20379. else {
  20380. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  20381. }
  20382. }
  20383. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20384. interaxial_distance = parsedCamera.interaxial_distance;
  20385. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  20386. }
  20387. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20388. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20389. }
  20390. else if (parsedCamera.type === "FollowCamera") {
  20391. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20392. camera.heightOffset = parsedCamera.heightOffset;
  20393. camera.radius = parsedCamera.radius;
  20394. camera.rotationOffset = parsedCamera.rotationOffset;
  20395. if (lockedTargetMesh)
  20396. camera.target = lockedTargetMesh;
  20397. }
  20398. else if (parsedCamera.type === "GamepadCamera") {
  20399. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20400. }
  20401. else if (parsedCamera.type === "TouchCamera") {
  20402. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20403. }
  20404. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20405. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20406. }
  20407. else if (parsedCamera.type === "WebVRFreeCamera") {
  20408. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  20409. }
  20410. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  20411. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  20412. }
  20413. else {
  20414. // Free Camera is the default value
  20415. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20416. }
  20417. // apply 3d rig, when found
  20418. if (parsedCamera.cameraRigMode) {
  20419. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20420. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20421. }
  20422. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20423. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20424. camera.lockedTarget = lockedTargetMesh;
  20425. }
  20426. camera.id = parsedCamera.id;
  20427. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20428. // Parent
  20429. if (parsedCamera.parentId) {
  20430. camera._waitingParentId = parsedCamera.parentId;
  20431. }
  20432. // Target
  20433. if (parsedCamera.target) {
  20434. if (camera.setTarget) {
  20435. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20436. }
  20437. else {
  20438. //For ArcRotate
  20439. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20440. }
  20441. }
  20442. else {
  20443. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20444. }
  20445. camera.fov = parsedCamera.fov;
  20446. camera.minZ = parsedCamera.minZ;
  20447. camera.maxZ = parsedCamera.maxZ;
  20448. camera.speed = parsedCamera.speed;
  20449. camera.inertia = parsedCamera.inertia;
  20450. camera.checkCollisions = parsedCamera.checkCollisions;
  20451. camera.applyGravity = parsedCamera.applyGravity;
  20452. if (parsedCamera.ellipsoid) {
  20453. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20454. }
  20455. // Animations
  20456. if (parsedCamera.animations) {
  20457. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20458. var parsedAnimation = parsedCamera.animations[animationIndex];
  20459. camera.animations.push(parseAnimation(parsedAnimation));
  20460. }
  20461. }
  20462. if (parsedCamera.autoAnimate) {
  20463. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20464. }
  20465. // Layer Mask
  20466. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20467. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20468. }
  20469. else {
  20470. camera.layerMask = 0x0FFFFFFF;
  20471. }
  20472. return camera;
  20473. };
  20474. var parseGeometry = function (parsedGeometry, scene) {
  20475. var id = parsedGeometry.id;
  20476. return scene.getGeometryByID(id);
  20477. };
  20478. var parseBox = function (parsedBox, scene) {
  20479. if (parseGeometry(parsedBox, scene)) {
  20480. return null; // null since geometry could be something else than a box...
  20481. }
  20482. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20483. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20484. scene.pushGeometry(box, true);
  20485. return box;
  20486. };
  20487. var parseSphere = function (parsedSphere, scene) {
  20488. if (parseGeometry(parsedSphere, scene)) {
  20489. return null; // null since geometry could be something else than a sphere...
  20490. }
  20491. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20492. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20493. scene.pushGeometry(sphere, true);
  20494. return sphere;
  20495. };
  20496. var parseCylinder = function (parsedCylinder, scene) {
  20497. if (parseGeometry(parsedCylinder, scene)) {
  20498. return null; // null since geometry could be something else than a cylinder...
  20499. }
  20500. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20501. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20502. scene.pushGeometry(cylinder, true);
  20503. return cylinder;
  20504. };
  20505. var parseTorus = function (parsedTorus, scene) {
  20506. if (parseGeometry(parsedTorus, scene)) {
  20507. return null; // null since geometry could be something else than a torus...
  20508. }
  20509. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20510. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20511. scene.pushGeometry(torus, true);
  20512. return torus;
  20513. };
  20514. var parseGround = function (parsedGround, scene) {
  20515. if (parseGeometry(parsedGround, scene)) {
  20516. return null; // null since geometry could be something else than a ground...
  20517. }
  20518. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20519. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20520. scene.pushGeometry(ground, true);
  20521. return ground;
  20522. };
  20523. var parsePlane = function (parsedPlane, scene) {
  20524. if (parseGeometry(parsedPlane, scene)) {
  20525. return null; // null since geometry could be something else than a plane...
  20526. }
  20527. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20528. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20529. scene.pushGeometry(plane, true);
  20530. return plane;
  20531. };
  20532. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20533. if (parseGeometry(parsedTorusKnot, scene)) {
  20534. return null; // null since geometry could be something else than a torusKnot...
  20535. }
  20536. 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);
  20537. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20538. scene.pushGeometry(torusKnot, true);
  20539. return torusKnot;
  20540. };
  20541. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20542. if (parseGeometry(parsedVertexData, scene)) {
  20543. return null; // null since geometry could be a primitive
  20544. }
  20545. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20546. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20547. if (parsedVertexData.delayLoadingFile) {
  20548. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20549. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20550. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20551. geometry._delayInfo = [];
  20552. if (parsedVertexData.hasUVs) {
  20553. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20554. }
  20555. if (parsedVertexData.hasUVs2) {
  20556. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20557. }
  20558. if (parsedVertexData.hasUVs3) {
  20559. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20560. }
  20561. if (parsedVertexData.hasUVs4) {
  20562. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20563. }
  20564. if (parsedVertexData.hasUVs5) {
  20565. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20566. }
  20567. if (parsedVertexData.hasUVs6) {
  20568. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20569. }
  20570. if (parsedVertexData.hasColors) {
  20571. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20572. }
  20573. if (parsedVertexData.hasMatricesIndices) {
  20574. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20575. }
  20576. if (parsedVertexData.hasMatricesWeights) {
  20577. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20578. }
  20579. geometry._delayLoadingFunction = importVertexData;
  20580. }
  20581. else {
  20582. importVertexData(parsedVertexData, geometry);
  20583. }
  20584. scene.pushGeometry(geometry, true);
  20585. return geometry;
  20586. };
  20587. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20588. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20589. mesh.id = parsedMesh.id;
  20590. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20591. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20592. if (parsedMesh.rotationQuaternion) {
  20593. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20594. }
  20595. else if (parsedMesh.rotation) {
  20596. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20597. }
  20598. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20599. if (parsedMesh.localMatrix) {
  20600. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20601. }
  20602. else if (parsedMesh.pivotMatrix) {
  20603. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20604. }
  20605. mesh.setEnabled(parsedMesh.isEnabled);
  20606. mesh.isVisible = parsedMesh.isVisible;
  20607. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20608. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20609. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20610. if (parsedMesh.applyFog !== undefined) {
  20611. mesh.applyFog = parsedMesh.applyFog;
  20612. }
  20613. if (parsedMesh.pickable !== undefined) {
  20614. mesh.isPickable = parsedMesh.pickable;
  20615. }
  20616. if (parsedMesh.alphaIndex !== undefined) {
  20617. mesh.alphaIndex = parsedMesh.alphaIndex;
  20618. }
  20619. mesh.receiveShadows = parsedMesh.receiveShadows;
  20620. mesh.billboardMode = parsedMesh.billboardMode;
  20621. if (parsedMesh.visibility !== undefined) {
  20622. mesh.visibility = parsedMesh.visibility;
  20623. }
  20624. mesh.checkCollisions = parsedMesh.checkCollisions;
  20625. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20626. // freezeWorldMatrix
  20627. if (parsedMesh.freezeWorldMatrix) {
  20628. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20629. }
  20630. // Parent
  20631. if (parsedMesh.parentId) {
  20632. mesh._waitingParentId = parsedMesh.parentId;
  20633. }
  20634. // Actions
  20635. if (parsedMesh.actions !== undefined) {
  20636. mesh._waitingActions = parsedMesh.actions;
  20637. }
  20638. // Geometry
  20639. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20640. if (parsedMesh.delayLoadingFile) {
  20641. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20642. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20643. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20644. if (parsedMesh._binaryInfo) {
  20645. mesh._binaryInfo = parsedMesh._binaryInfo;
  20646. }
  20647. mesh._delayInfo = [];
  20648. if (parsedMesh.hasUVs) {
  20649. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20650. }
  20651. if (parsedMesh.hasUVs2) {
  20652. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20653. }
  20654. if (parsedMesh.hasUVs3) {
  20655. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20656. }
  20657. if (parsedMesh.hasUVs4) {
  20658. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20659. }
  20660. if (parsedMesh.hasUVs5) {
  20661. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20662. }
  20663. if (parsedMesh.hasUVs6) {
  20664. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20665. }
  20666. if (parsedMesh.hasColors) {
  20667. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20668. }
  20669. if (parsedMesh.hasMatricesIndices) {
  20670. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20671. }
  20672. if (parsedMesh.hasMatricesWeights) {
  20673. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20674. }
  20675. mesh._delayLoadingFunction = importGeometry;
  20676. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20677. mesh._checkDelayState();
  20678. }
  20679. }
  20680. else {
  20681. importGeometry(parsedMesh, mesh);
  20682. }
  20683. // Material
  20684. if (parsedMesh.materialId) {
  20685. mesh.setMaterialByID(parsedMesh.materialId);
  20686. }
  20687. else {
  20688. mesh.material = null;
  20689. }
  20690. // Skeleton
  20691. if (parsedMesh.skeletonId > -1) {
  20692. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20693. }
  20694. // Physics
  20695. if (parsedMesh.physicsImpostor) {
  20696. if (!scene.isPhysicsEnabled()) {
  20697. scene.enablePhysics();
  20698. }
  20699. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20700. }
  20701. // Animations
  20702. if (parsedMesh.animations) {
  20703. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20704. var parsedAnimation = parsedMesh.animations[animationIndex];
  20705. mesh.animations.push(parseAnimation(parsedAnimation));
  20706. }
  20707. }
  20708. if (parsedMesh.autoAnimate) {
  20709. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20710. }
  20711. // Layer Mask
  20712. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20713. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20714. }
  20715. else {
  20716. mesh.layerMask = 0x0FFFFFFF;
  20717. }
  20718. // Instances
  20719. if (parsedMesh.instances) {
  20720. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20721. var parsedInstance = parsedMesh.instances[index];
  20722. var instance = mesh.createInstance(parsedInstance.name);
  20723. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20724. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20725. if (parsedInstance.rotationQuaternion) {
  20726. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20727. }
  20728. else if (parsedInstance.rotation) {
  20729. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20730. }
  20731. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20732. instance.checkCollisions = mesh.checkCollisions;
  20733. if (parsedMesh.animations) {
  20734. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20735. parsedAnimation = parsedMesh.animations[animationIndex];
  20736. instance.animations.push(parseAnimation(parsedAnimation));
  20737. }
  20738. }
  20739. }
  20740. }
  20741. return mesh;
  20742. };
  20743. var parseActions = function (parsedActions, object, scene) {
  20744. var actionManager = new BABYLON.ActionManager(scene);
  20745. if (object === null)
  20746. scene.actionManager = actionManager;
  20747. else
  20748. object.actionManager = actionManager;
  20749. // instanciate a new object
  20750. var instanciate = function (name, params) {
  20751. var newInstance = Object.create(BABYLON[name].prototype);
  20752. newInstance.constructor.apply(newInstance, params);
  20753. return newInstance;
  20754. };
  20755. var parseParameter = function (name, value, target, propertyPath) {
  20756. if (propertyPath === null) {
  20757. // String, boolean or float
  20758. var floatValue = parseFloat(value);
  20759. if (value === "true" || value === "false")
  20760. return value === "true";
  20761. else
  20762. return isNaN(floatValue) ? value : floatValue;
  20763. }
  20764. var effectiveTarget = propertyPath.split(".");
  20765. var values = value.split(",");
  20766. // Get effective Target
  20767. for (var i = 0; i < effectiveTarget.length; i++) {
  20768. target = target[effectiveTarget[i]];
  20769. }
  20770. // Return appropriate value with its type
  20771. if (typeof (target) === "boolean")
  20772. return values[0] === "true";
  20773. if (typeof (target) === "string")
  20774. return values[0];
  20775. // Parameters with multiple values such as Vector3 etc.
  20776. var split = new Array();
  20777. for (var i = 0; i < values.length; i++)
  20778. split.push(parseFloat(values[i]));
  20779. if (target instanceof BABYLON.Vector3)
  20780. return BABYLON.Vector3.FromArray(split);
  20781. if (target instanceof BABYLON.Vector4)
  20782. return BABYLON.Vector4.FromArray(split);
  20783. if (target instanceof BABYLON.Color3)
  20784. return BABYLON.Color3.FromArray(split);
  20785. if (target instanceof BABYLON.Color4)
  20786. return BABYLON.Color4.FromArray(split);
  20787. return parseFloat(values[0]);
  20788. };
  20789. // traverse graph per trigger
  20790. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20791. if (combineArray === void 0) { combineArray = null; }
  20792. if (parsedAction.detached)
  20793. return;
  20794. var parameters = new Array();
  20795. var target = null;
  20796. var propertyPath = null;
  20797. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20798. // Parameters
  20799. if (parsedAction.type === 2)
  20800. parameters.push(actionManager);
  20801. else
  20802. parameters.push(trigger);
  20803. if (combine) {
  20804. var actions = new Array();
  20805. for (var j = 0; j < parsedAction.combine.length; j++) {
  20806. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20807. }
  20808. parameters.push(actions);
  20809. }
  20810. else {
  20811. for (var i = 0; i < parsedAction.properties.length; i++) {
  20812. var value = parsedAction.properties[i].value;
  20813. var name = parsedAction.properties[i].name;
  20814. var targetType = parsedAction.properties[i].targetType;
  20815. if (name === "target")
  20816. if (targetType !== null && targetType === "SceneProperties")
  20817. value = target = scene;
  20818. else
  20819. value = target = scene.getNodeByName(value);
  20820. else if (name === "parent")
  20821. value = scene.getNodeByName(value);
  20822. else if (name === "sound")
  20823. value = scene.getSoundByName(value);
  20824. else if (name !== "propertyPath") {
  20825. if (parsedAction.type === 2 && name === "operator")
  20826. value = BABYLON.ValueCondition[value];
  20827. else
  20828. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20829. }
  20830. else {
  20831. propertyPath = value;
  20832. }
  20833. parameters.push(value);
  20834. }
  20835. }
  20836. if (combineArray === null) {
  20837. parameters.push(condition);
  20838. }
  20839. else {
  20840. parameters.push(null);
  20841. }
  20842. // If interpolate value action
  20843. if (parsedAction.name === "InterpolateValueAction") {
  20844. var param = parameters[parameters.length - 2];
  20845. parameters[parameters.length - 1] = param;
  20846. parameters[parameters.length - 2] = condition;
  20847. }
  20848. // Action or condition(s) and not CombineAction
  20849. var newAction = instanciate(parsedAction.name, parameters);
  20850. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20851. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20852. if (action)
  20853. action.then(nothing);
  20854. else
  20855. actionManager.registerAction(nothing);
  20856. action = nothing;
  20857. }
  20858. if (combineArray === null) {
  20859. if (newAction instanceof BABYLON.Condition) {
  20860. condition = newAction;
  20861. newAction = action;
  20862. }
  20863. else {
  20864. condition = null;
  20865. if (action)
  20866. action.then(newAction);
  20867. else
  20868. actionManager.registerAction(newAction);
  20869. }
  20870. }
  20871. else {
  20872. combineArray.push(newAction);
  20873. }
  20874. for (var i = 0; i < parsedAction.children.length; i++)
  20875. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20876. };
  20877. // triggers
  20878. for (var i = 0; i < parsedActions.children.length; i++) {
  20879. var triggerParams;
  20880. var trigger = parsedActions.children[i];
  20881. if (trigger.properties.length > 0) {
  20882. var param = trigger.properties[0].value;
  20883. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20884. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20885. }
  20886. else
  20887. triggerParams = BABYLON.ActionManager[trigger.name];
  20888. for (var j = 0; j < trigger.children.length; j++) {
  20889. if (!trigger.detached)
  20890. traverse(trigger.children[j], triggerParams, null, null);
  20891. }
  20892. }
  20893. };
  20894. var parseSound = function (parsedSound, scene, rootUrl) {
  20895. var soundName = parsedSound.name;
  20896. var soundUrl = rootUrl + soundName;
  20897. var options = {
  20898. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20899. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20900. rolloffFactor: parsedSound.rolloffFactor,
  20901. refDistance: parsedSound.refDistance,
  20902. distanceModel: parsedSound.distanceModel,
  20903. playbackRate: parsedSound.playbackRate
  20904. };
  20905. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20906. scene._addPendingData(newSound);
  20907. if (parsedSound.position) {
  20908. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20909. newSound.setPosition(soundPosition);
  20910. }
  20911. if (parsedSound.isDirectional) {
  20912. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20913. if (parsedSound.localDirectionToMesh) {
  20914. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20915. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20916. }
  20917. }
  20918. if (parsedSound.connectedMeshId) {
  20919. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20920. if (connectedMesh) {
  20921. newSound.attachToMesh(connectedMesh);
  20922. }
  20923. }
  20924. };
  20925. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20926. names = (names instanceof Array) ? names : [names];
  20927. for (var i in names) {
  20928. if (mesh.name === names[i]) {
  20929. hierarchyIds.push(mesh.id);
  20930. return true;
  20931. }
  20932. }
  20933. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20934. hierarchyIds.push(mesh.id);
  20935. return true;
  20936. }
  20937. return false;
  20938. };
  20939. var importVertexData = function (parsedVertexData, geometry) {
  20940. var vertexData = new BABYLON.VertexData();
  20941. // positions
  20942. var positions = parsedVertexData.positions;
  20943. if (positions) {
  20944. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20945. }
  20946. // normals
  20947. var normals = parsedVertexData.normals;
  20948. if (normals) {
  20949. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20950. }
  20951. // uvs
  20952. var uvs = parsedVertexData.uvs;
  20953. if (uvs) {
  20954. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20955. }
  20956. // uv2s
  20957. var uv2s = parsedVertexData.uv2s;
  20958. if (uv2s) {
  20959. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20960. }
  20961. // uv3s
  20962. var uv3s = parsedVertexData.uv3s;
  20963. if (uv3s) {
  20964. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20965. }
  20966. // uv4s
  20967. var uv4s = parsedVertexData.uv4s;
  20968. if (uv4s) {
  20969. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20970. }
  20971. // uv5s
  20972. var uv5s = parsedVertexData.uv5s;
  20973. if (uv5s) {
  20974. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20975. }
  20976. // uv6s
  20977. var uv6s = parsedVertexData.uv6s;
  20978. if (uv6s) {
  20979. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20980. }
  20981. // colors
  20982. var colors = parsedVertexData.colors;
  20983. if (colors) {
  20984. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20985. }
  20986. // matricesIndices
  20987. var matricesIndices = parsedVertexData.matricesIndices;
  20988. if (matricesIndices) {
  20989. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20990. }
  20991. // matricesWeights
  20992. var matricesWeights = parsedVertexData.matricesWeights;
  20993. if (matricesWeights) {
  20994. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20995. }
  20996. // indices
  20997. var indices = parsedVertexData.indices;
  20998. if (indices) {
  20999. vertexData.indices = indices;
  21000. }
  21001. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  21002. };
  21003. var importGeometry = function (parsedGeometry, mesh) {
  21004. var scene = mesh.getScene();
  21005. // Geometry
  21006. var geometryId = parsedGeometry.geometryId;
  21007. if (geometryId) {
  21008. var geometry = scene.getGeometryByID(geometryId);
  21009. if (geometry) {
  21010. geometry.applyToMesh(mesh);
  21011. }
  21012. }
  21013. else if (parsedGeometry instanceof ArrayBuffer) {
  21014. var binaryInfo = mesh._binaryInfo;
  21015. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  21016. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  21017. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  21018. }
  21019. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  21020. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  21021. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  21022. }
  21023. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  21024. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  21025. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  21026. }
  21027. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  21028. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  21029. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  21030. }
  21031. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  21032. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  21033. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  21034. }
  21035. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  21036. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  21037. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  21038. }
  21039. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  21040. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  21041. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  21042. }
  21043. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  21044. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  21045. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  21046. }
  21047. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  21048. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  21049. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  21050. }
  21051. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  21052. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  21053. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  21054. }
  21055. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  21056. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  21057. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  21058. }
  21059. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  21060. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  21061. mesh.setIndices(indicesData);
  21062. }
  21063. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  21064. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  21065. mesh.subMeshes = [];
  21066. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  21067. var materialIndex = subMeshesData[(i * 5) + 0];
  21068. var verticesStart = subMeshesData[(i * 5) + 1];
  21069. var verticesCount = subMeshesData[(i * 5) + 2];
  21070. var indexStart = subMeshesData[(i * 5) + 3];
  21071. var indexCount = subMeshesData[(i * 5) + 4];
  21072. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  21073. }
  21074. }
  21075. }
  21076. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  21077. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  21078. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  21079. if (parsedGeometry.uvs) {
  21080. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  21081. }
  21082. if (parsedGeometry.uvs2) {
  21083. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  21084. }
  21085. if (parsedGeometry.uvs3) {
  21086. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  21087. }
  21088. if (parsedGeometry.uvs4) {
  21089. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  21090. }
  21091. if (parsedGeometry.uvs5) {
  21092. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  21093. }
  21094. if (parsedGeometry.uvs6) {
  21095. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  21096. }
  21097. if (parsedGeometry.colors) {
  21098. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  21099. }
  21100. if (parsedGeometry.matricesIndices) {
  21101. if (!parsedGeometry.matricesIndices._isExpanded) {
  21102. var floatIndices = [];
  21103. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  21104. var matricesIndex = parsedGeometry.matricesIndices[i];
  21105. floatIndices.push(matricesIndex & 0x000000FF);
  21106. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  21107. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  21108. floatIndices.push(matricesIndex >> 24);
  21109. }
  21110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  21111. }
  21112. else {
  21113. delete parsedGeometry.matricesIndices._isExpanded;
  21114. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  21115. }
  21116. }
  21117. if (parsedGeometry.matricesWeights) {
  21118. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  21119. }
  21120. mesh.setIndices(parsedGeometry.indices);
  21121. }
  21122. // SubMeshes
  21123. if (parsedGeometry.subMeshes) {
  21124. mesh.subMeshes = [];
  21125. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  21126. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  21127. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  21128. }
  21129. }
  21130. // Flat shading
  21131. if (mesh._shouldGenerateFlatShading) {
  21132. mesh.convertToFlatShadedMesh();
  21133. delete mesh._shouldGenerateFlatShading;
  21134. }
  21135. // Update
  21136. mesh.computeWorldMatrix(true);
  21137. // Octree
  21138. if (scene._selectionOctree) {
  21139. scene._selectionOctree.addMesh(mesh);
  21140. }
  21141. };
  21142. BABYLON.SceneLoader.RegisterPlugin({
  21143. extensions: ".babylon",
  21144. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21145. var parsedData = JSON.parse(data);
  21146. var loadedSkeletonsIds = [];
  21147. var loadedMaterialsIds = [];
  21148. var hierarchyIds = [];
  21149. for (var index = 0; index < parsedData.meshes.length; index++) {
  21150. var parsedMesh = parsedData.meshes[index];
  21151. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21152. if (meshesNames instanceof Array) {
  21153. // Remove found mesh name from list.
  21154. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21155. }
  21156. //Geometry?
  21157. if (parsedMesh.geometryId) {
  21158. //does the file contain geometries?
  21159. if (parsedData.geometries) {
  21160. //find the correct geometry and add it to the scene
  21161. var found = false;
  21162. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21163. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21164. return;
  21165. }
  21166. else {
  21167. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21168. if (parsedGeometryData.id == parsedMesh.geometryId) {
  21169. switch (geometryType) {
  21170. case "boxes":
  21171. parseBox(parsedGeometryData, scene);
  21172. break;
  21173. case "spheres":
  21174. parseSphere(parsedGeometryData, scene);
  21175. break;
  21176. case "cylinders":
  21177. parseCylinder(parsedGeometryData, scene);
  21178. break;
  21179. case "toruses":
  21180. parseTorus(parsedGeometryData, scene);
  21181. break;
  21182. case "grounds":
  21183. parseGround(parsedGeometryData, scene);
  21184. break;
  21185. case "planes":
  21186. parsePlane(parsedGeometryData, scene);
  21187. break;
  21188. case "torusKnots":
  21189. parseTorusKnot(parsedGeometryData, scene);
  21190. break;
  21191. case "vertexData":
  21192. parseVertexData(parsedGeometryData, scene, rootUrl);
  21193. break;
  21194. }
  21195. found = true;
  21196. }
  21197. });
  21198. }
  21199. });
  21200. if (!found) {
  21201. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21202. }
  21203. }
  21204. }
  21205. // Material ?
  21206. if (parsedMesh.materialId) {
  21207. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21208. if (!materialFound && parsedData.multiMaterials) {
  21209. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  21210. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21211. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  21212. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  21213. var subMatId = parsedMultiMaterial.materials[matIndex];
  21214. loadedMaterialsIds.push(subMatId);
  21215. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21216. }
  21217. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21218. parseMultiMaterial(parsedMultiMaterial, scene);
  21219. materialFound = true;
  21220. break;
  21221. }
  21222. }
  21223. }
  21224. if (!materialFound) {
  21225. loadedMaterialsIds.push(parsedMesh.materialId);
  21226. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21227. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21228. }
  21229. }
  21230. }
  21231. // Skeleton ?
  21232. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21233. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21234. if (!skeletonAlreadyLoaded) {
  21235. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  21236. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21237. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21238. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  21239. loadedSkeletonsIds.push(parsedSkeleton.id);
  21240. }
  21241. }
  21242. }
  21243. }
  21244. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  21245. meshes.push(mesh);
  21246. }
  21247. }
  21248. // Connecting parents
  21249. for (index = 0; index < scene.meshes.length; index++) {
  21250. var currentMesh = scene.meshes[index];
  21251. if (currentMesh._waitingParentId) {
  21252. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21253. currentMesh._waitingParentId = undefined;
  21254. }
  21255. }
  21256. // freeze world matrix application
  21257. for (index = 0; index < scene.meshes.length; index++) {
  21258. var currentMesh = scene.meshes[index];
  21259. if (currentMesh._waitingFreezeWorldMatrix) {
  21260. currentMesh.freezeWorldMatrix();
  21261. currentMesh._waitingFreezeWorldMatrix = undefined;
  21262. }
  21263. }
  21264. // Particles
  21265. if (parsedData.particleSystems) {
  21266. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21267. var parsedParticleSystem = parsedData.particleSystems[index];
  21268. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21269. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  21270. }
  21271. }
  21272. }
  21273. return true;
  21274. },
  21275. load: function (scene, data, rootUrl) {
  21276. var parsedData = JSON.parse(data);
  21277. // Scene
  21278. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21279. scene.autoClear = parsedData.autoClear;
  21280. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21281. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21282. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21283. // Fog
  21284. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21285. scene.fogMode = parsedData.fogMode;
  21286. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21287. scene.fogStart = parsedData.fogStart;
  21288. scene.fogEnd = parsedData.fogEnd;
  21289. scene.fogDensity = parsedData.fogDensity;
  21290. }
  21291. // Lights
  21292. for (var index = 0; index < parsedData.lights.length; index++) {
  21293. var parsedLight = parsedData.lights[index];
  21294. parseLight(parsedLight, scene);
  21295. }
  21296. // Materials
  21297. if (parsedData.materials) {
  21298. for (index = 0; index < parsedData.materials.length; index++) {
  21299. var parsedMaterial = parsedData.materials[index];
  21300. parseMaterial(parsedMaterial, scene, rootUrl);
  21301. }
  21302. }
  21303. if (parsedData.multiMaterials) {
  21304. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  21305. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21306. parseMultiMaterial(parsedMultiMaterial, scene);
  21307. }
  21308. }
  21309. // Skeletons
  21310. if (parsedData.skeletons) {
  21311. for (index = 0; index < parsedData.skeletons.length; index++) {
  21312. var parsedSkeleton = parsedData.skeletons[index];
  21313. parseSkeleton(parsedSkeleton, scene);
  21314. }
  21315. }
  21316. // Geometries
  21317. var geometries = parsedData.geometries;
  21318. if (geometries) {
  21319. // Boxes
  21320. var boxes = geometries.boxes;
  21321. if (boxes) {
  21322. for (index = 0; index < boxes.length; index++) {
  21323. var parsedBox = boxes[index];
  21324. parseBox(parsedBox, scene);
  21325. }
  21326. }
  21327. // Spheres
  21328. var spheres = geometries.spheres;
  21329. if (spheres) {
  21330. for (index = 0; index < spheres.length; index++) {
  21331. var parsedSphere = spheres[index];
  21332. parseSphere(parsedSphere, scene);
  21333. }
  21334. }
  21335. // Cylinders
  21336. var cylinders = geometries.cylinders;
  21337. if (cylinders) {
  21338. for (index = 0; index < cylinders.length; index++) {
  21339. var parsedCylinder = cylinders[index];
  21340. parseCylinder(parsedCylinder, scene);
  21341. }
  21342. }
  21343. // Toruses
  21344. var toruses = geometries.toruses;
  21345. if (toruses) {
  21346. for (index = 0; index < toruses.length; index++) {
  21347. var parsedTorus = toruses[index];
  21348. parseTorus(parsedTorus, scene);
  21349. }
  21350. }
  21351. // Grounds
  21352. var grounds = geometries.grounds;
  21353. if (grounds) {
  21354. for (index = 0; index < grounds.length; index++) {
  21355. var parsedGround = grounds[index];
  21356. parseGround(parsedGround, scene);
  21357. }
  21358. }
  21359. // Planes
  21360. var planes = geometries.planes;
  21361. if (planes) {
  21362. for (index = 0; index < planes.length; index++) {
  21363. var parsedPlane = planes[index];
  21364. parsePlane(parsedPlane, scene);
  21365. }
  21366. }
  21367. // TorusKnots
  21368. var torusKnots = geometries.torusKnots;
  21369. if (torusKnots) {
  21370. for (index = 0; index < torusKnots.length; index++) {
  21371. var parsedTorusKnot = torusKnots[index];
  21372. parseTorusKnot(parsedTorusKnot, scene);
  21373. }
  21374. }
  21375. // VertexData
  21376. var vertexData = geometries.vertexData;
  21377. if (vertexData) {
  21378. for (index = 0; index < vertexData.length; index++) {
  21379. var parsedVertexData = vertexData[index];
  21380. parseVertexData(parsedVertexData, scene, rootUrl);
  21381. }
  21382. }
  21383. }
  21384. // Meshes
  21385. for (index = 0; index < parsedData.meshes.length; index++) {
  21386. var parsedMesh = parsedData.meshes[index];
  21387. parseMesh(parsedMesh, scene, rootUrl);
  21388. }
  21389. // Cameras
  21390. for (index = 0; index < parsedData.cameras.length; index++) {
  21391. var parsedCamera = parsedData.cameras[index];
  21392. parseCamera(parsedCamera, scene);
  21393. }
  21394. if (parsedData.activeCameraID) {
  21395. scene.setActiveCameraByID(parsedData.activeCameraID);
  21396. }
  21397. // Browsing all the graph to connect the dots
  21398. for (index = 0; index < scene.cameras.length; index++) {
  21399. var camera = scene.cameras[index];
  21400. if (camera._waitingParentId) {
  21401. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21402. camera._waitingParentId = undefined;
  21403. }
  21404. }
  21405. for (index = 0; index < scene.lights.length; index++) {
  21406. var light = scene.lights[index];
  21407. if (light._waitingParentId) {
  21408. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21409. light._waitingParentId = undefined;
  21410. }
  21411. }
  21412. // Sounds
  21413. if (parsedData.sounds) {
  21414. for (index = 0; index < parsedData.sounds.length; index++) {
  21415. var parsedSound = parsedData.sounds[index];
  21416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21417. parseSound(parsedSound, scene, rootUrl);
  21418. }
  21419. else {
  21420. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21421. }
  21422. }
  21423. }
  21424. // Connect parents & children and parse actions
  21425. for (index = 0; index < scene.meshes.length; index++) {
  21426. var mesh = scene.meshes[index];
  21427. if (mesh._waitingParentId) {
  21428. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21429. mesh._waitingParentId = undefined;
  21430. }
  21431. if (mesh._waitingActions) {
  21432. parseActions(mesh._waitingActions, mesh, scene);
  21433. mesh._waitingActions = undefined;
  21434. }
  21435. }
  21436. // freeze world matrix application
  21437. for (index = 0; index < scene.meshes.length; index++) {
  21438. var currentMesh = scene.meshes[index];
  21439. if (currentMesh._waitingFreezeWorldMatrix) {
  21440. currentMesh.freezeWorldMatrix();
  21441. currentMesh._waitingFreezeWorldMatrix = undefined;
  21442. }
  21443. }
  21444. // Particles Systems
  21445. if (parsedData.particleSystems) {
  21446. for (index = 0; index < parsedData.particleSystems.length; index++) {
  21447. var parsedParticleSystem = parsedData.particleSystems[index];
  21448. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  21449. }
  21450. }
  21451. // Lens flares
  21452. if (parsedData.lensFlareSystems) {
  21453. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  21454. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21455. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  21456. }
  21457. }
  21458. // Shadows
  21459. if (parsedData.shadowGenerators) {
  21460. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  21461. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21462. parseShadowGenerator(parsedShadowGenerator, scene);
  21463. }
  21464. }
  21465. // Actions (scene)
  21466. if (parsedData.actions) {
  21467. parseActions(parsedData.actions, null, scene);
  21468. }
  21469. // Finish
  21470. return true;
  21471. }
  21472. });
  21473. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21474. })(BABYLON || (BABYLON = {}));
  21475. var BABYLON;
  21476. (function (BABYLON) {
  21477. var SpriteManager = (function () {
  21478. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21480. this.name = name;
  21481. this.cellSize = cellSize;
  21482. this.sprites = new Array();
  21483. this.renderingGroupId = 0;
  21484. this.layerMask = 0x0FFFFFFF;
  21485. this.fogEnabled = true;
  21486. this._vertexDeclaration = [4, 4, 4, 4];
  21487. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21488. this._capacity = capacity;
  21489. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21490. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21491. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21492. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21493. this._scene = scene;
  21494. this._scene.spriteManagers.push(this);
  21495. // VBO
  21496. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21497. var indices = [];
  21498. var index = 0;
  21499. for (var count = 0; count < capacity; count++) {
  21500. indices.push(index);
  21501. indices.push(index + 1);
  21502. indices.push(index + 2);
  21503. indices.push(index);
  21504. indices.push(index + 2);
  21505. indices.push(index + 3);
  21506. index += 4;
  21507. }
  21508. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21509. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21510. // Effects
  21511. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21512. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21513. }
  21514. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21515. var arrayOffset = index * 16;
  21516. if (offsetX === 0)
  21517. offsetX = this._epsilon;
  21518. else if (offsetX === 1)
  21519. offsetX = 1 - this._epsilon;
  21520. if (offsetY === 0)
  21521. offsetY = this._epsilon;
  21522. else if (offsetY === 1)
  21523. offsetY = 1 - this._epsilon;
  21524. this._vertices[arrayOffset] = sprite.position.x;
  21525. this._vertices[arrayOffset + 1] = sprite.position.y;
  21526. this._vertices[arrayOffset + 2] = sprite.position.z;
  21527. this._vertices[arrayOffset + 3] = sprite.angle;
  21528. this._vertices[arrayOffset + 4] = sprite.width;
  21529. this._vertices[arrayOffset + 5] = sprite.height;
  21530. this._vertices[arrayOffset + 6] = offsetX;
  21531. this._vertices[arrayOffset + 7] = offsetY;
  21532. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21533. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21534. var offset = (sprite.cellIndex / rowSize) >> 0;
  21535. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21536. this._vertices[arrayOffset + 11] = offset;
  21537. // Color
  21538. this._vertices[arrayOffset + 12] = sprite.color.r;
  21539. this._vertices[arrayOffset + 13] = sprite.color.g;
  21540. this._vertices[arrayOffset + 14] = sprite.color.b;
  21541. this._vertices[arrayOffset + 15] = sprite.color.a;
  21542. };
  21543. SpriteManager.prototype.render = function () {
  21544. // Check
  21545. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21546. return;
  21547. var engine = this._scene.getEngine();
  21548. var baseSize = this._spriteTexture.getBaseSize();
  21549. // Sprites
  21550. var deltaTime = engine.getDeltaTime();
  21551. var max = Math.min(this._capacity, this.sprites.length);
  21552. var rowSize = baseSize.width / this.cellSize;
  21553. var offset = 0;
  21554. for (var index = 0; index < max; index++) {
  21555. var sprite = this.sprites[index];
  21556. if (!sprite) {
  21557. continue;
  21558. }
  21559. sprite._animate(deltaTime);
  21560. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21561. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21562. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21563. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21564. }
  21565. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21566. // Render
  21567. var effect = this._effectBase;
  21568. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21569. effect = this._effectFog;
  21570. }
  21571. engine.enableEffect(effect);
  21572. var viewMatrix = this._scene.getViewMatrix();
  21573. effect.setTexture("diffuseSampler", this._spriteTexture);
  21574. effect.setMatrix("view", viewMatrix);
  21575. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21576. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21577. // Fog
  21578. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21579. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21580. effect.setColor3("vFogColor", this._scene.fogColor);
  21581. }
  21582. // VBOs
  21583. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21584. // Draw order
  21585. engine.setDepthFunctionToLessOrEqual();
  21586. effect.setBool("alphaTest", true);
  21587. engine.setColorWrite(false);
  21588. engine.draw(true, 0, max * 6);
  21589. engine.setColorWrite(true);
  21590. effect.setBool("alphaTest", false);
  21591. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21592. engine.draw(true, 0, max * 6);
  21593. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21594. };
  21595. SpriteManager.prototype.dispose = function () {
  21596. if (this._vertexBuffer) {
  21597. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21598. this._vertexBuffer = null;
  21599. }
  21600. if (this._indexBuffer) {
  21601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21602. this._indexBuffer = null;
  21603. }
  21604. if (this._spriteTexture) {
  21605. this._spriteTexture.dispose();
  21606. this._spriteTexture = null;
  21607. }
  21608. // Remove from scene
  21609. var index = this._scene.spriteManagers.indexOf(this);
  21610. this._scene.spriteManagers.splice(index, 1);
  21611. // Callback
  21612. if (this.onDispose) {
  21613. this.onDispose();
  21614. }
  21615. };
  21616. return SpriteManager;
  21617. })();
  21618. BABYLON.SpriteManager = SpriteManager;
  21619. })(BABYLON || (BABYLON = {}));
  21620. var BABYLON;
  21621. (function (BABYLON) {
  21622. var Sprite = (function () {
  21623. function Sprite(name, manager) {
  21624. this.name = name;
  21625. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21626. this.width = 1.0;
  21627. this.height = 1.0;
  21628. this.angle = 0;
  21629. this.cellIndex = 0;
  21630. this.invertU = 0;
  21631. this.invertV = 0;
  21632. this.animations = new Array();
  21633. this._animationStarted = false;
  21634. this._loopAnimation = false;
  21635. this._fromIndex = 0;
  21636. this._toIndex = 0;
  21637. this._delay = 0;
  21638. this._direction = 1;
  21639. this._frameCount = 0;
  21640. this._time = 0;
  21641. this._manager = manager;
  21642. this._manager.sprites.push(this);
  21643. this.position = BABYLON.Vector3.Zero();
  21644. }
  21645. Object.defineProperty(Sprite.prototype, "size", {
  21646. get: function () {
  21647. return this.width;
  21648. },
  21649. set: function (value) {
  21650. this.width = value;
  21651. this.height = value;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21657. this._fromIndex = from;
  21658. this._toIndex = to;
  21659. this._loopAnimation = loop;
  21660. this._delay = delay;
  21661. this._animationStarted = true;
  21662. this._direction = from < to ? 1 : -1;
  21663. this.cellIndex = from;
  21664. this._time = 0;
  21665. };
  21666. Sprite.prototype.stopAnimation = function () {
  21667. this._animationStarted = false;
  21668. };
  21669. Sprite.prototype._animate = function (deltaTime) {
  21670. if (!this._animationStarted)
  21671. return;
  21672. this._time += deltaTime;
  21673. if (this._time > this._delay) {
  21674. this._time = this._time % this._delay;
  21675. this.cellIndex += this._direction;
  21676. if (this.cellIndex == this._toIndex) {
  21677. if (this._loopAnimation) {
  21678. this.cellIndex = this._fromIndex;
  21679. }
  21680. else {
  21681. this._animationStarted = false;
  21682. if (this.disposeWhenFinishedAnimating) {
  21683. this.dispose();
  21684. }
  21685. }
  21686. }
  21687. }
  21688. };
  21689. Sprite.prototype.dispose = function () {
  21690. for (var i = 0; i < this._manager.sprites.length; i++) {
  21691. if (this._manager.sprites[i] == this) {
  21692. this._manager.sprites.splice(i, 1);
  21693. }
  21694. }
  21695. };
  21696. return Sprite;
  21697. })();
  21698. BABYLON.Sprite = Sprite;
  21699. })(BABYLON || (BABYLON = {}));
  21700. var BABYLON;
  21701. (function (BABYLON) {
  21702. var Layer = (function () {
  21703. function Layer(name, imgUrl, scene, isBackground, color) {
  21704. this.name = name;
  21705. this._vertexDeclaration = [2];
  21706. this._vertexStrideSize = 2 * 4;
  21707. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21708. this.isBackground = isBackground === undefined ? true : isBackground;
  21709. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21710. this._scene = scene;
  21711. this._scene.layers.push(this);
  21712. // VBO
  21713. var vertices = [];
  21714. vertices.push(1, 1);
  21715. vertices.push(-1, 1);
  21716. vertices.push(-1, -1);
  21717. vertices.push(1, -1);
  21718. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21719. // Indices
  21720. var indices = [];
  21721. indices.push(0);
  21722. indices.push(1);
  21723. indices.push(2);
  21724. indices.push(0);
  21725. indices.push(2);
  21726. indices.push(3);
  21727. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21728. // Effects
  21729. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21730. }
  21731. Layer.prototype.render = function () {
  21732. // Check
  21733. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21734. return;
  21735. var engine = this._scene.getEngine();
  21736. // Render
  21737. engine.enableEffect(this._effect);
  21738. engine.setState(false);
  21739. // Texture
  21740. this._effect.setTexture("textureSampler", this.texture);
  21741. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21742. // Color
  21743. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21744. // VBOs
  21745. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21746. // Draw order
  21747. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21748. engine.draw(true, 0, 6);
  21749. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21750. };
  21751. Layer.prototype.dispose = function () {
  21752. if (this._vertexBuffer) {
  21753. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21754. this._vertexBuffer = null;
  21755. }
  21756. if (this._indexBuffer) {
  21757. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21758. this._indexBuffer = null;
  21759. }
  21760. if (this.texture) {
  21761. this.texture.dispose();
  21762. this.texture = null;
  21763. }
  21764. // Remove from scene
  21765. var index = this._scene.layers.indexOf(this);
  21766. this._scene.layers.splice(index, 1);
  21767. // Callback
  21768. if (this.onDispose) {
  21769. this.onDispose();
  21770. }
  21771. };
  21772. return Layer;
  21773. })();
  21774. BABYLON.Layer = Layer;
  21775. })(BABYLON || (BABYLON = {}));
  21776. var BABYLON;
  21777. (function (BABYLON) {
  21778. var Particle = (function () {
  21779. function Particle() {
  21780. this.position = BABYLON.Vector3.Zero();
  21781. this.direction = BABYLON.Vector3.Zero();
  21782. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21783. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21784. this.lifeTime = 1.0;
  21785. this.age = 0;
  21786. this.size = 0;
  21787. this.angle = 0;
  21788. this.angularSpeed = 0;
  21789. }
  21790. Particle.prototype.copyTo = function (other) {
  21791. other.position.copyFrom(this.position);
  21792. other.direction.copyFrom(this.direction);
  21793. other.color.copyFrom(this.color);
  21794. other.colorStep.copyFrom(this.colorStep);
  21795. other.lifeTime = this.lifeTime;
  21796. other.age = this.age;
  21797. other.size = this.size;
  21798. other.angle = this.angle;
  21799. other.angularSpeed = this.angularSpeed;
  21800. };
  21801. return Particle;
  21802. })();
  21803. BABYLON.Particle = Particle;
  21804. })(BABYLON || (BABYLON = {}));
  21805. var BABYLON;
  21806. (function (BABYLON) {
  21807. var randomNumber = function (min, max) {
  21808. if (min === max) {
  21809. return (min);
  21810. }
  21811. var random = Math.random();
  21812. return ((random * (max - min)) + min);
  21813. };
  21814. var ParticleSystem = (function () {
  21815. function ParticleSystem(name, capacity, scene, customEffect) {
  21816. var _this = this;
  21817. this.name = name;
  21818. this.renderingGroupId = 0;
  21819. this.emitter = null;
  21820. this.emitRate = 10;
  21821. this.manualEmitCount = -1;
  21822. this.updateSpeed = 0.01;
  21823. this.targetStopDuration = 0;
  21824. this.disposeOnStop = false;
  21825. this.minEmitPower = 1;
  21826. this.maxEmitPower = 1;
  21827. this.minLifeTime = 1;
  21828. this.maxLifeTime = 1;
  21829. this.minSize = 1;
  21830. this.maxSize = 1;
  21831. this.minAngularSpeed = 0;
  21832. this.maxAngularSpeed = 0;
  21833. this.layerMask = 0x0FFFFFFF;
  21834. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21835. this.forceDepthWrite = false;
  21836. this.gravity = BABYLON.Vector3.Zero();
  21837. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21838. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21839. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21840. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21841. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21842. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21843. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21844. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21845. this.particles = new Array();
  21846. this._vertexDeclaration = [3, 4, 4];
  21847. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21848. this._stockParticles = new Array();
  21849. this._newPartsExcess = 0;
  21850. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21851. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21852. this._scaledDirection = BABYLON.Vector3.Zero();
  21853. this._scaledGravity = BABYLON.Vector3.Zero();
  21854. this._currentRenderId = -1;
  21855. this._started = false;
  21856. this._stopped = false;
  21857. this._actualFrame = 0;
  21858. this.id = name;
  21859. this._capacity = capacity;
  21860. this._scene = scene;
  21861. this._customEffect = customEffect;
  21862. scene.particleSystems.push(this);
  21863. // VBO
  21864. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21865. var indices = [];
  21866. var index = 0;
  21867. for (var count = 0; count < capacity; count++) {
  21868. indices.push(index);
  21869. indices.push(index + 1);
  21870. indices.push(index + 2);
  21871. indices.push(index);
  21872. indices.push(index + 2);
  21873. indices.push(index + 3);
  21874. index += 4;
  21875. }
  21876. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21877. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21878. // Default behaviors
  21879. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21880. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21881. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21882. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21883. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21884. };
  21885. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21886. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21887. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21888. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21890. };
  21891. this.updateFunction = function (particles) {
  21892. for (var index = 0; index < particles.length; index++) {
  21893. var particle = particles[index];
  21894. particle.age += _this._scaledUpdateSpeed;
  21895. if (particle.age >= particle.lifeTime) {
  21896. _this.recycleParticle(particle);
  21897. index--;
  21898. continue;
  21899. }
  21900. else {
  21901. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21902. particle.color.addInPlace(_this._scaledColorStep);
  21903. if (particle.color.a < 0)
  21904. particle.color.a = 0;
  21905. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21906. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21907. particle.position.addInPlace(_this._scaledDirection);
  21908. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21909. particle.direction.addInPlace(_this._scaledGravity);
  21910. }
  21911. }
  21912. };
  21913. }
  21914. ParticleSystem.prototype.recycleParticle = function (particle) {
  21915. var lastParticle = this.particles.pop();
  21916. if (lastParticle !== particle) {
  21917. lastParticle.copyTo(particle);
  21918. this._stockParticles.push(lastParticle);
  21919. }
  21920. };
  21921. ParticleSystem.prototype.getCapacity = function () {
  21922. return this._capacity;
  21923. };
  21924. ParticleSystem.prototype.isAlive = function () {
  21925. return this._alive;
  21926. };
  21927. ParticleSystem.prototype.isStarted = function () {
  21928. return this._started;
  21929. };
  21930. ParticleSystem.prototype.start = function () {
  21931. this._started = true;
  21932. this._stopped = false;
  21933. this._actualFrame = 0;
  21934. };
  21935. ParticleSystem.prototype.stop = function () {
  21936. this._stopped = true;
  21937. };
  21938. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21939. var offset = index * 11;
  21940. this._vertices[offset] = particle.position.x;
  21941. this._vertices[offset + 1] = particle.position.y;
  21942. this._vertices[offset + 2] = particle.position.z;
  21943. this._vertices[offset + 3] = particle.color.r;
  21944. this._vertices[offset + 4] = particle.color.g;
  21945. this._vertices[offset + 5] = particle.color.b;
  21946. this._vertices[offset + 6] = particle.color.a;
  21947. this._vertices[offset + 7] = particle.angle;
  21948. this._vertices[offset + 8] = particle.size;
  21949. this._vertices[offset + 9] = offsetX;
  21950. this._vertices[offset + 10] = offsetY;
  21951. };
  21952. ParticleSystem.prototype._update = function (newParticles) {
  21953. // Update current
  21954. this._alive = this.particles.length > 0;
  21955. this.updateFunction(this.particles);
  21956. // Add new ones
  21957. var worldMatrix;
  21958. if (this.emitter.position) {
  21959. worldMatrix = this.emitter.getWorldMatrix();
  21960. }
  21961. else {
  21962. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21963. }
  21964. for (var index = 0; index < newParticles; index++) {
  21965. if (this.particles.length === this._capacity) {
  21966. break;
  21967. }
  21968. if (this._stockParticles.length !== 0) {
  21969. var particle = this._stockParticles.pop();
  21970. particle.age = 0;
  21971. }
  21972. else {
  21973. particle = new BABYLON.Particle();
  21974. }
  21975. this.particles.push(particle);
  21976. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21977. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21978. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21979. particle.size = randomNumber(this.minSize, this.maxSize);
  21980. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21981. this.startPositionFunction(worldMatrix, particle.position);
  21982. var step = randomNumber(0, 1.0);
  21983. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21984. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21985. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21986. }
  21987. };
  21988. ParticleSystem.prototype._getEffect = function () {
  21989. if (this._customEffect) {
  21990. return this._customEffect;
  21991. }
  21992. ;
  21993. var defines = [];
  21994. if (this._scene.clipPlane) {
  21995. defines.push("#define CLIPPLANE");
  21996. }
  21997. // Effect
  21998. var join = defines.join("\n");
  21999. if (this._cachedDefines !== join) {
  22000. this._cachedDefines = join;
  22001. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22002. }
  22003. return this._effect;
  22004. };
  22005. ParticleSystem.prototype.animate = function () {
  22006. if (!this._started)
  22007. return;
  22008. var effect = this._getEffect();
  22009. // Check
  22010. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22011. return;
  22012. if (this._currentRenderId === this._scene.getRenderId()) {
  22013. return;
  22014. }
  22015. this._currentRenderId = this._scene.getRenderId();
  22016. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22017. // determine the number of particles we need to create
  22018. var emitCout;
  22019. if (this.manualEmitCount > -1) {
  22020. emitCout = this.manualEmitCount;
  22021. this.manualEmitCount = 0;
  22022. }
  22023. else {
  22024. emitCout = this.emitRate;
  22025. }
  22026. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  22027. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  22028. if (this._newPartsExcess > 1.0) {
  22029. newParticles += this._newPartsExcess >> 0;
  22030. this._newPartsExcess -= this._newPartsExcess >> 0;
  22031. }
  22032. this._alive = false;
  22033. if (!this._stopped) {
  22034. this._actualFrame += this._scaledUpdateSpeed;
  22035. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22036. this.stop();
  22037. }
  22038. else {
  22039. newParticles = 0;
  22040. }
  22041. this._update(newParticles);
  22042. // Stopped?
  22043. if (this._stopped) {
  22044. if (!this._alive) {
  22045. this._started = false;
  22046. if (this.disposeOnStop) {
  22047. this._scene._toBeDisposed.push(this);
  22048. }
  22049. }
  22050. }
  22051. // Update VBO
  22052. var offset = 0;
  22053. for (var index = 0; index < this.particles.length; index++) {
  22054. var particle = this.particles[index];
  22055. this._appendParticleVertex(offset++, particle, 0, 0);
  22056. this._appendParticleVertex(offset++, particle, 1, 0);
  22057. this._appendParticleVertex(offset++, particle, 1, 1);
  22058. this._appendParticleVertex(offset++, particle, 0, 1);
  22059. }
  22060. var engine = this._scene.getEngine();
  22061. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22062. };
  22063. ParticleSystem.prototype.render = function () {
  22064. var effect = this._getEffect();
  22065. // Check
  22066. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22067. return 0;
  22068. var engine = this._scene.getEngine();
  22069. // Render
  22070. engine.enableEffect(effect);
  22071. engine.setState(false);
  22072. var viewMatrix = this._scene.getViewMatrix();
  22073. effect.setTexture("diffuseSampler", this.particleTexture);
  22074. effect.setMatrix("view", viewMatrix);
  22075. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22076. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22077. if (this._scene.clipPlane) {
  22078. var clipPlane = this._scene.clipPlane;
  22079. var invView = viewMatrix.clone();
  22080. invView.invert();
  22081. effect.setMatrix("invView", invView);
  22082. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22083. }
  22084. // VBOs
  22085. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22086. // Draw order
  22087. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22088. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22089. }
  22090. else {
  22091. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22092. }
  22093. if (this.forceDepthWrite) {
  22094. engine.setDepthWrite(true);
  22095. }
  22096. engine.draw(true, 0, this.particles.length * 6);
  22097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22098. return this.particles.length;
  22099. };
  22100. ParticleSystem.prototype.dispose = function () {
  22101. if (this._vertexBuffer) {
  22102. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22103. this._vertexBuffer = null;
  22104. }
  22105. if (this._indexBuffer) {
  22106. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22107. this._indexBuffer = null;
  22108. }
  22109. if (this.particleTexture) {
  22110. this.particleTexture.dispose();
  22111. this.particleTexture = null;
  22112. }
  22113. // Remove from scene
  22114. var index = this._scene.particleSystems.indexOf(this);
  22115. this._scene.particleSystems.splice(index, 1);
  22116. // Callback
  22117. if (this.onDispose) {
  22118. this.onDispose();
  22119. }
  22120. };
  22121. // Clone
  22122. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22123. var result = new ParticleSystem(name, this._capacity, this._scene);
  22124. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22125. if (newEmitter === undefined) {
  22126. newEmitter = this.emitter;
  22127. }
  22128. result.emitter = newEmitter;
  22129. if (this.particleTexture) {
  22130. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22131. }
  22132. result.start();
  22133. return result;
  22134. };
  22135. // Statics
  22136. ParticleSystem.BLENDMODE_ONEONE = 0;
  22137. ParticleSystem.BLENDMODE_STANDARD = 1;
  22138. return ParticleSystem;
  22139. })();
  22140. BABYLON.ParticleSystem = ParticleSystem;
  22141. })(BABYLON || (BABYLON = {}));
  22142. var BABYLON;
  22143. (function (BABYLON) {
  22144. var Animation = (function () {
  22145. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22146. this.name = name;
  22147. this.targetProperty = targetProperty;
  22148. this.framePerSecond = framePerSecond;
  22149. this.dataType = dataType;
  22150. this.loopMode = loopMode;
  22151. this._offsetsCache = {};
  22152. this._highLimitsCache = {};
  22153. this._stopped = false;
  22154. this.allowMatricesInterpolation = false;
  22155. this.targetPropertyPath = targetProperty.split(".");
  22156. this.dataType = dataType;
  22157. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22158. }
  22159. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22160. var dataType = undefined;
  22161. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22162. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22163. }
  22164. else if (from instanceof BABYLON.Quaternion) {
  22165. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22166. }
  22167. else if (from instanceof BABYLON.Vector3) {
  22168. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22169. }
  22170. else if (from instanceof BABYLON.Vector2) {
  22171. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22172. }
  22173. else if (from instanceof BABYLON.Color3) {
  22174. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22175. }
  22176. if (dataType == undefined) {
  22177. return null;
  22178. }
  22179. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22180. var keys = [];
  22181. keys.push({ frame: 0, value: from });
  22182. keys.push({ frame: totalFrame, value: to });
  22183. animation.setKeys(keys);
  22184. if (easingFunction !== undefined) {
  22185. animation.setEasingFunction(easingFunction);
  22186. }
  22187. mesh.animations.push(animation);
  22188. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22189. };
  22190. // Methods
  22191. Animation.prototype.reset = function () {
  22192. this._offsetsCache = {};
  22193. this._highLimitsCache = {};
  22194. this.currentFrame = 0;
  22195. };
  22196. Animation.prototype.isStopped = function () {
  22197. return this._stopped;
  22198. };
  22199. Animation.prototype.getKeys = function () {
  22200. return this._keys;
  22201. };
  22202. Animation.prototype.getEasingFunction = function () {
  22203. return this._easingFunction;
  22204. };
  22205. Animation.prototype.setEasingFunction = function (easingFunction) {
  22206. this._easingFunction = easingFunction;
  22207. };
  22208. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22209. return startValue + (endValue - startValue) * gradient;
  22210. };
  22211. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22212. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22213. };
  22214. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22215. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22216. };
  22217. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22218. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22219. };
  22220. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22221. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22222. };
  22223. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22224. var startScale = new BABYLON.Vector3(0, 0, 0);
  22225. var startRotation = new BABYLON.Quaternion();
  22226. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  22227. startValue.decompose(startScale, startRotation, startTranslation);
  22228. var endScale = new BABYLON.Vector3(0, 0, 0);
  22229. var endRotation = new BABYLON.Quaternion();
  22230. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  22231. endValue.decompose(endScale, endRotation, endTranslation);
  22232. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  22233. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  22234. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  22235. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  22236. return result;
  22237. };
  22238. Animation.prototype.clone = function () {
  22239. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22240. clone.setKeys(this._keys);
  22241. return clone;
  22242. };
  22243. Animation.prototype.setKeys = function (values) {
  22244. this._keys = values.slice(0);
  22245. this._offsetsCache = {};
  22246. this._highLimitsCache = {};
  22247. };
  22248. Animation.prototype._getKeyValue = function (value) {
  22249. if (typeof value === "function") {
  22250. return value();
  22251. }
  22252. return value;
  22253. };
  22254. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22255. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22256. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22257. }
  22258. this.currentFrame = currentFrame;
  22259. // Try to get a hash to find the right key
  22260. 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));
  22261. if (this._keys[startKey].frame >= currentFrame) {
  22262. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22263. startKey--;
  22264. }
  22265. }
  22266. for (var key = startKey; key < this._keys.length; key++) {
  22267. if (this._keys[key + 1].frame >= currentFrame) {
  22268. var startValue = this._getKeyValue(this._keys[key].value);
  22269. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22270. // gradient : percent of currentFrame between the frame inf and the frame sup
  22271. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22272. // check for easingFunction and correction of gradient
  22273. if (this._easingFunction != null) {
  22274. gradient = this._easingFunction.ease(gradient);
  22275. }
  22276. switch (this.dataType) {
  22277. // Float
  22278. case Animation.ANIMATIONTYPE_FLOAT:
  22279. switch (loopMode) {
  22280. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22281. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22282. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22283. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22284. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22285. }
  22286. break;
  22287. // Quaternion
  22288. case Animation.ANIMATIONTYPE_QUATERNION:
  22289. var quaternion = null;
  22290. switch (loopMode) {
  22291. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22292. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22293. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22294. break;
  22295. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22296. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22297. break;
  22298. }
  22299. return quaternion;
  22300. // Vector3
  22301. case Animation.ANIMATIONTYPE_VECTOR3:
  22302. switch (loopMode) {
  22303. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22304. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22305. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22306. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22307. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22308. }
  22309. // Vector2
  22310. case Animation.ANIMATIONTYPE_VECTOR2:
  22311. switch (loopMode) {
  22312. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22313. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22314. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22315. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22316. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22317. }
  22318. // Color3
  22319. case Animation.ANIMATIONTYPE_COLOR3:
  22320. switch (loopMode) {
  22321. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22322. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22323. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22324. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22325. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22326. }
  22327. // Matrix
  22328. case Animation.ANIMATIONTYPE_MATRIX:
  22329. switch (loopMode) {
  22330. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22331. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22332. if (this.allowMatricesInterpolation) {
  22333. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22334. }
  22335. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22336. return startValue;
  22337. }
  22338. default:
  22339. break;
  22340. }
  22341. break;
  22342. }
  22343. }
  22344. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22345. };
  22346. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22347. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22348. this._stopped = true;
  22349. return false;
  22350. }
  22351. var returnValue = true;
  22352. // Adding a start key at frame 0 if missing
  22353. if (this._keys[0].frame !== 0) {
  22354. var newKey = { frame: 0, value: this._keys[0].value };
  22355. this._keys.splice(0, 0, newKey);
  22356. }
  22357. // Check limits
  22358. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22359. from = this._keys[0].frame;
  22360. }
  22361. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22362. to = this._keys[this._keys.length - 1].frame;
  22363. }
  22364. // Compute ratio
  22365. var range = to - from;
  22366. var offsetValue;
  22367. // ratio represents the frame delta between from and to
  22368. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22369. var highLimitValue = 0;
  22370. if (ratio > range && !loop) {
  22371. returnValue = false;
  22372. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22373. }
  22374. else {
  22375. // Get max value if required
  22376. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22377. var keyOffset = to.toString() + from.toString();
  22378. if (!this._offsetsCache[keyOffset]) {
  22379. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22380. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22381. switch (this.dataType) {
  22382. // Float
  22383. case Animation.ANIMATIONTYPE_FLOAT:
  22384. this._offsetsCache[keyOffset] = toValue - fromValue;
  22385. break;
  22386. // Quaternion
  22387. case Animation.ANIMATIONTYPE_QUATERNION:
  22388. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22389. break;
  22390. // Vector3
  22391. case Animation.ANIMATIONTYPE_VECTOR3:
  22392. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22393. // Vector2
  22394. case Animation.ANIMATIONTYPE_VECTOR2:
  22395. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22396. // Color3
  22397. case Animation.ANIMATIONTYPE_COLOR3:
  22398. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22399. default:
  22400. break;
  22401. }
  22402. this._highLimitsCache[keyOffset] = toValue;
  22403. }
  22404. highLimitValue = this._highLimitsCache[keyOffset];
  22405. offsetValue = this._offsetsCache[keyOffset];
  22406. }
  22407. }
  22408. if (offsetValue === undefined) {
  22409. switch (this.dataType) {
  22410. // Float
  22411. case Animation.ANIMATIONTYPE_FLOAT:
  22412. offsetValue = 0;
  22413. break;
  22414. // Quaternion
  22415. case Animation.ANIMATIONTYPE_QUATERNION:
  22416. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22417. break;
  22418. // Vector3
  22419. case Animation.ANIMATIONTYPE_VECTOR3:
  22420. offsetValue = BABYLON.Vector3.Zero();
  22421. break;
  22422. // Vector2
  22423. case Animation.ANIMATIONTYPE_VECTOR2:
  22424. offsetValue = BABYLON.Vector2.Zero();
  22425. break;
  22426. // Color3
  22427. case Animation.ANIMATIONTYPE_COLOR3:
  22428. offsetValue = BABYLON.Color3.Black();
  22429. }
  22430. }
  22431. // Compute value
  22432. var repeatCount = (ratio / range) >> 0;
  22433. var currentFrame = returnValue ? from + ratio % range : to;
  22434. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22435. // Set value
  22436. if (this.targetPropertyPath.length > 1) {
  22437. var property = this._target[this.targetPropertyPath[0]];
  22438. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22439. property = property[this.targetPropertyPath[index]];
  22440. }
  22441. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22442. }
  22443. else {
  22444. this._target[this.targetPropertyPath[0]] = currentValue;
  22445. }
  22446. if (this._target.markAsDirty) {
  22447. this._target.markAsDirty(this.targetProperty);
  22448. }
  22449. if (!returnValue) {
  22450. this._stopped = true;
  22451. }
  22452. return returnValue;
  22453. };
  22454. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22455. get: function () {
  22456. return Animation._ANIMATIONTYPE_FLOAT;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22462. get: function () {
  22463. return Animation._ANIMATIONTYPE_VECTOR3;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22469. get: function () {
  22470. return Animation._ANIMATIONTYPE_VECTOR2;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22476. get: function () {
  22477. return Animation._ANIMATIONTYPE_QUATERNION;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22483. get: function () {
  22484. return Animation._ANIMATIONTYPE_MATRIX;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22490. get: function () {
  22491. return Animation._ANIMATIONTYPE_COLOR3;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22497. get: function () {
  22498. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22504. get: function () {
  22505. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22506. },
  22507. enumerable: true,
  22508. configurable: true
  22509. });
  22510. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22511. get: function () {
  22512. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. // Statics
  22518. Animation._ANIMATIONTYPE_FLOAT = 0;
  22519. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22520. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22521. Animation._ANIMATIONTYPE_MATRIX = 3;
  22522. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22523. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22524. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22525. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22526. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22527. return Animation;
  22528. })();
  22529. BABYLON.Animation = Animation;
  22530. })(BABYLON || (BABYLON = {}));
  22531. var BABYLON;
  22532. (function (BABYLON) {
  22533. var Animatable = (function () {
  22534. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22535. if (fromFrame === void 0) { fromFrame = 0; }
  22536. if (toFrame === void 0) { toFrame = 100; }
  22537. if (loopAnimation === void 0) { loopAnimation = false; }
  22538. if (speedRatio === void 0) { speedRatio = 1.0; }
  22539. this.target = target;
  22540. this.fromFrame = fromFrame;
  22541. this.toFrame = toFrame;
  22542. this.loopAnimation = loopAnimation;
  22543. this.speedRatio = speedRatio;
  22544. this.onAnimationEnd = onAnimationEnd;
  22545. this._animations = new Array();
  22546. this._paused = false;
  22547. this.animationStarted = false;
  22548. if (animations) {
  22549. this.appendAnimations(target, animations);
  22550. }
  22551. this._scene = scene;
  22552. scene._activeAnimatables.push(this);
  22553. }
  22554. // Methods
  22555. Animatable.prototype.appendAnimations = function (target, animations) {
  22556. for (var index = 0; index < animations.length; index++) {
  22557. var animation = animations[index];
  22558. animation._target = target;
  22559. this._animations.push(animation);
  22560. }
  22561. };
  22562. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22563. var animations = this._animations;
  22564. for (var index = 0; index < animations.length; index++) {
  22565. if (animations[index].targetProperty === property) {
  22566. return animations[index];
  22567. }
  22568. }
  22569. return null;
  22570. };
  22571. Animatable.prototype.reset = function () {
  22572. var animations = this._animations;
  22573. for (var index = 0; index < animations.length; index++) {
  22574. animations[index].reset();
  22575. }
  22576. this._localDelayOffset = null;
  22577. this._pausedDelay = null;
  22578. };
  22579. Animatable.prototype.pause = function () {
  22580. if (this._paused) {
  22581. return;
  22582. }
  22583. this._paused = true;
  22584. };
  22585. Animatable.prototype.restart = function () {
  22586. this._paused = false;
  22587. };
  22588. Animatable.prototype.stop = function () {
  22589. var index = this._scene._activeAnimatables.indexOf(this);
  22590. if (index > -1) {
  22591. this._scene._activeAnimatables.splice(index, 1);
  22592. }
  22593. if (this.onAnimationEnd) {
  22594. this.onAnimationEnd();
  22595. }
  22596. };
  22597. Animatable.prototype._animate = function (delay) {
  22598. if (this._paused) {
  22599. if (!this._pausedDelay) {
  22600. this._pausedDelay = delay;
  22601. }
  22602. return true;
  22603. }
  22604. if (!this._localDelayOffset) {
  22605. this._localDelayOffset = delay;
  22606. }
  22607. else if (this._pausedDelay) {
  22608. this._localDelayOffset += delay - this._pausedDelay;
  22609. this._pausedDelay = null;
  22610. }
  22611. // Animating
  22612. var running = false;
  22613. var animations = this._animations;
  22614. for (var index = 0; index < animations.length; index++) {
  22615. var animation = animations[index];
  22616. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22617. running = running || isRunning;
  22618. }
  22619. if (!running) {
  22620. // Remove from active animatables
  22621. index = this._scene._activeAnimatables.indexOf(this);
  22622. this._scene._activeAnimatables.splice(index, 1);
  22623. }
  22624. if (!running && this.onAnimationEnd) {
  22625. this.onAnimationEnd();
  22626. }
  22627. return running;
  22628. };
  22629. return Animatable;
  22630. })();
  22631. BABYLON.Animatable = Animatable;
  22632. })(BABYLON || (BABYLON = {}));
  22633. var BABYLON;
  22634. (function (BABYLON) {
  22635. var EasingFunction = (function () {
  22636. function EasingFunction() {
  22637. // Properties
  22638. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22639. }
  22640. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22641. get: function () {
  22642. return EasingFunction._EASINGMODE_EASEIN;
  22643. },
  22644. enumerable: true,
  22645. configurable: true
  22646. });
  22647. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22648. get: function () {
  22649. return EasingFunction._EASINGMODE_EASEOUT;
  22650. },
  22651. enumerable: true,
  22652. configurable: true
  22653. });
  22654. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22655. get: function () {
  22656. return EasingFunction._EASINGMODE_EASEINOUT;
  22657. },
  22658. enumerable: true,
  22659. configurable: true
  22660. });
  22661. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22662. var n = Math.min(Math.max(easingMode, 0), 2);
  22663. this._easingMode = n;
  22664. };
  22665. EasingFunction.prototype.getEasingMode = function () {
  22666. return this._easingMode;
  22667. };
  22668. EasingFunction.prototype.easeInCore = function (gradient) {
  22669. throw new Error('You must implement this method');
  22670. };
  22671. EasingFunction.prototype.ease = function (gradient) {
  22672. switch (this._easingMode) {
  22673. case EasingFunction.EASINGMODE_EASEIN:
  22674. return this.easeInCore(gradient);
  22675. case EasingFunction.EASINGMODE_EASEOUT:
  22676. return (1 - this.easeInCore(1 - gradient));
  22677. }
  22678. if (gradient >= 0.5) {
  22679. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22680. }
  22681. return (this.easeInCore(gradient * 2) * 0.5);
  22682. };
  22683. //Statics
  22684. EasingFunction._EASINGMODE_EASEIN = 0;
  22685. EasingFunction._EASINGMODE_EASEOUT = 1;
  22686. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22687. return EasingFunction;
  22688. })();
  22689. BABYLON.EasingFunction = EasingFunction;
  22690. var CircleEase = (function (_super) {
  22691. __extends(CircleEase, _super);
  22692. function CircleEase() {
  22693. _super.apply(this, arguments);
  22694. }
  22695. CircleEase.prototype.easeInCore = function (gradient) {
  22696. gradient = Math.max(0, Math.min(1, gradient));
  22697. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22698. };
  22699. return CircleEase;
  22700. })(EasingFunction);
  22701. BABYLON.CircleEase = CircleEase;
  22702. var BackEase = (function (_super) {
  22703. __extends(BackEase, _super);
  22704. function BackEase(amplitude) {
  22705. if (amplitude === void 0) { amplitude = 1; }
  22706. _super.call(this);
  22707. this.amplitude = amplitude;
  22708. }
  22709. BackEase.prototype.easeInCore = function (gradient) {
  22710. var num = Math.max(0, this.amplitude);
  22711. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22712. };
  22713. return BackEase;
  22714. })(EasingFunction);
  22715. BABYLON.BackEase = BackEase;
  22716. var BounceEase = (function (_super) {
  22717. __extends(BounceEase, _super);
  22718. function BounceEase(bounces, bounciness) {
  22719. if (bounces === void 0) { bounces = 3; }
  22720. if (bounciness === void 0) { bounciness = 2; }
  22721. _super.call(this);
  22722. this.bounces = bounces;
  22723. this.bounciness = bounciness;
  22724. }
  22725. BounceEase.prototype.easeInCore = function (gradient) {
  22726. var y = Math.max(0.0, this.bounces);
  22727. var bounciness = this.bounciness;
  22728. if (bounciness <= 1.0) {
  22729. bounciness = 1.001;
  22730. }
  22731. var num9 = Math.pow(bounciness, y);
  22732. var num5 = 1.0 - bounciness;
  22733. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22734. var num15 = gradient * num4;
  22735. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22736. var num3 = Math.floor(num65);
  22737. var num13 = num3 + 1.0;
  22738. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22739. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22740. var num7 = (num8 + num12) * 0.5;
  22741. var num6 = gradient - num7;
  22742. var num2 = num7 - num8;
  22743. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22744. };
  22745. return BounceEase;
  22746. })(EasingFunction);
  22747. BABYLON.BounceEase = BounceEase;
  22748. var CubicEase = (function (_super) {
  22749. __extends(CubicEase, _super);
  22750. function CubicEase() {
  22751. _super.apply(this, arguments);
  22752. }
  22753. CubicEase.prototype.easeInCore = function (gradient) {
  22754. return (gradient * gradient * gradient);
  22755. };
  22756. return CubicEase;
  22757. })(EasingFunction);
  22758. BABYLON.CubicEase = CubicEase;
  22759. var ElasticEase = (function (_super) {
  22760. __extends(ElasticEase, _super);
  22761. function ElasticEase(oscillations, springiness) {
  22762. if (oscillations === void 0) { oscillations = 3; }
  22763. if (springiness === void 0) { springiness = 3; }
  22764. _super.call(this);
  22765. this.oscillations = oscillations;
  22766. this.springiness = springiness;
  22767. }
  22768. ElasticEase.prototype.easeInCore = function (gradient) {
  22769. var num2;
  22770. var num3 = Math.max(0.0, this.oscillations);
  22771. var num = Math.max(0.0, this.springiness);
  22772. if (num == 0) {
  22773. num2 = gradient;
  22774. }
  22775. else {
  22776. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22777. }
  22778. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22779. };
  22780. return ElasticEase;
  22781. })(EasingFunction);
  22782. BABYLON.ElasticEase = ElasticEase;
  22783. var ExponentialEase = (function (_super) {
  22784. __extends(ExponentialEase, _super);
  22785. function ExponentialEase(exponent) {
  22786. if (exponent === void 0) { exponent = 2; }
  22787. _super.call(this);
  22788. this.exponent = exponent;
  22789. }
  22790. ExponentialEase.prototype.easeInCore = function (gradient) {
  22791. if (this.exponent <= 0) {
  22792. return gradient;
  22793. }
  22794. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22795. };
  22796. return ExponentialEase;
  22797. })(EasingFunction);
  22798. BABYLON.ExponentialEase = ExponentialEase;
  22799. var PowerEase = (function (_super) {
  22800. __extends(PowerEase, _super);
  22801. function PowerEase(power) {
  22802. if (power === void 0) { power = 2; }
  22803. _super.call(this);
  22804. this.power = power;
  22805. }
  22806. PowerEase.prototype.easeInCore = function (gradient) {
  22807. var y = Math.max(0.0, this.power);
  22808. return Math.pow(gradient, y);
  22809. };
  22810. return PowerEase;
  22811. })(EasingFunction);
  22812. BABYLON.PowerEase = PowerEase;
  22813. var QuadraticEase = (function (_super) {
  22814. __extends(QuadraticEase, _super);
  22815. function QuadraticEase() {
  22816. _super.apply(this, arguments);
  22817. }
  22818. QuadraticEase.prototype.easeInCore = function (gradient) {
  22819. return (gradient * gradient);
  22820. };
  22821. return QuadraticEase;
  22822. })(EasingFunction);
  22823. BABYLON.QuadraticEase = QuadraticEase;
  22824. var QuarticEase = (function (_super) {
  22825. __extends(QuarticEase, _super);
  22826. function QuarticEase() {
  22827. _super.apply(this, arguments);
  22828. }
  22829. QuarticEase.prototype.easeInCore = function (gradient) {
  22830. return (gradient * gradient * gradient * gradient);
  22831. };
  22832. return QuarticEase;
  22833. })(EasingFunction);
  22834. BABYLON.QuarticEase = QuarticEase;
  22835. var QuinticEase = (function (_super) {
  22836. __extends(QuinticEase, _super);
  22837. function QuinticEase() {
  22838. _super.apply(this, arguments);
  22839. }
  22840. QuinticEase.prototype.easeInCore = function (gradient) {
  22841. return (gradient * gradient * gradient * gradient * gradient);
  22842. };
  22843. return QuinticEase;
  22844. })(EasingFunction);
  22845. BABYLON.QuinticEase = QuinticEase;
  22846. var SineEase = (function (_super) {
  22847. __extends(SineEase, _super);
  22848. function SineEase() {
  22849. _super.apply(this, arguments);
  22850. }
  22851. SineEase.prototype.easeInCore = function (gradient) {
  22852. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22853. };
  22854. return SineEase;
  22855. })(EasingFunction);
  22856. BABYLON.SineEase = SineEase;
  22857. var BezierCurveEase = (function (_super) {
  22858. __extends(BezierCurveEase, _super);
  22859. function BezierCurveEase(x1, y1, x2, y2) {
  22860. if (x1 === void 0) { x1 = 0; }
  22861. if (y1 === void 0) { y1 = 0; }
  22862. if (x2 === void 0) { x2 = 1; }
  22863. if (y2 === void 0) { y2 = 1; }
  22864. _super.call(this);
  22865. this.x1 = x1;
  22866. this.y1 = y1;
  22867. this.x2 = x2;
  22868. this.y2 = y2;
  22869. }
  22870. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22871. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22872. };
  22873. return BezierCurveEase;
  22874. })(EasingFunction);
  22875. BABYLON.BezierCurveEase = BezierCurveEase;
  22876. })(BABYLON || (BABYLON = {}));
  22877. var BABYLON;
  22878. (function (BABYLON) {
  22879. var Octree = (function () {
  22880. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22881. if (maxDepth === void 0) { maxDepth = 2; }
  22882. this.maxDepth = maxDepth;
  22883. this.dynamicContent = new Array();
  22884. this._maxBlockCapacity = maxBlockCapacity || 64;
  22885. this._selectionContent = new BABYLON.SmartArray(1024);
  22886. this._creationFunc = creationFunc;
  22887. }
  22888. // Methods
  22889. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22890. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22891. };
  22892. Octree.prototype.addMesh = function (entry) {
  22893. for (var index = 0; index < this.blocks.length; index++) {
  22894. var block = this.blocks[index];
  22895. block.addEntry(entry);
  22896. }
  22897. };
  22898. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22899. this._selectionContent.reset();
  22900. for (var index = 0; index < this.blocks.length; index++) {
  22901. var block = this.blocks[index];
  22902. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22903. }
  22904. if (allowDuplicate) {
  22905. this._selectionContent.concat(this.dynamicContent);
  22906. }
  22907. else {
  22908. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22909. }
  22910. return this._selectionContent;
  22911. };
  22912. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22913. this._selectionContent.reset();
  22914. for (var index = 0; index < this.blocks.length; index++) {
  22915. var block = this.blocks[index];
  22916. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22917. }
  22918. if (allowDuplicate) {
  22919. this._selectionContent.concat(this.dynamicContent);
  22920. }
  22921. else {
  22922. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22923. }
  22924. return this._selectionContent;
  22925. };
  22926. Octree.prototype.intersectsRay = function (ray) {
  22927. this._selectionContent.reset();
  22928. for (var index = 0; index < this.blocks.length; index++) {
  22929. var block = this.blocks[index];
  22930. block.intersectsRay(ray, this._selectionContent);
  22931. }
  22932. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22933. return this._selectionContent;
  22934. };
  22935. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22936. target.blocks = new Array();
  22937. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22938. // Segmenting space
  22939. for (var x = 0; x < 2; x++) {
  22940. for (var y = 0; y < 2; y++) {
  22941. for (var z = 0; z < 2; z++) {
  22942. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22943. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22944. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22945. block.addEntries(entries);
  22946. target.blocks.push(block);
  22947. }
  22948. }
  22949. }
  22950. };
  22951. Octree.CreationFuncForMeshes = function (entry, block) {
  22952. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22953. block.entries.push(entry);
  22954. }
  22955. };
  22956. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22957. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22958. block.entries.push(entry);
  22959. }
  22960. };
  22961. return Octree;
  22962. })();
  22963. BABYLON.Octree = Octree;
  22964. })(BABYLON || (BABYLON = {}));
  22965. var BABYLON;
  22966. (function (BABYLON) {
  22967. var OctreeBlock = (function () {
  22968. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22969. this.entries = new Array();
  22970. this._boundingVectors = new Array();
  22971. this._capacity = capacity;
  22972. this._depth = depth;
  22973. this._maxDepth = maxDepth;
  22974. this._creationFunc = creationFunc;
  22975. this._minPoint = minPoint;
  22976. this._maxPoint = maxPoint;
  22977. this._boundingVectors.push(minPoint.clone());
  22978. this._boundingVectors.push(maxPoint.clone());
  22979. this._boundingVectors.push(minPoint.clone());
  22980. this._boundingVectors[2].x = maxPoint.x;
  22981. this._boundingVectors.push(minPoint.clone());
  22982. this._boundingVectors[3].y = maxPoint.y;
  22983. this._boundingVectors.push(minPoint.clone());
  22984. this._boundingVectors[4].z = maxPoint.z;
  22985. this._boundingVectors.push(maxPoint.clone());
  22986. this._boundingVectors[5].z = minPoint.z;
  22987. this._boundingVectors.push(maxPoint.clone());
  22988. this._boundingVectors[6].x = minPoint.x;
  22989. this._boundingVectors.push(maxPoint.clone());
  22990. this._boundingVectors[7].y = minPoint.y;
  22991. }
  22992. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22993. // Property
  22994. get: function () {
  22995. return this._capacity;
  22996. },
  22997. enumerable: true,
  22998. configurable: true
  22999. });
  23000. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  23001. get: function () {
  23002. return this._minPoint;
  23003. },
  23004. enumerable: true,
  23005. configurable: true
  23006. });
  23007. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  23008. get: function () {
  23009. return this._maxPoint;
  23010. },
  23011. enumerable: true,
  23012. configurable: true
  23013. });
  23014. // Methods
  23015. OctreeBlock.prototype.addEntry = function (entry) {
  23016. if (this.blocks) {
  23017. for (var index = 0; index < this.blocks.length; index++) {
  23018. var block = this.blocks[index];
  23019. block.addEntry(entry);
  23020. }
  23021. return;
  23022. }
  23023. this._creationFunc(entry, this);
  23024. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  23025. this.createInnerBlocks();
  23026. }
  23027. };
  23028. OctreeBlock.prototype.addEntries = function (entries) {
  23029. for (var index = 0; index < entries.length; index++) {
  23030. var mesh = entries[index];
  23031. this.addEntry(mesh);
  23032. }
  23033. };
  23034. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  23035. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  23036. if (this.blocks) {
  23037. for (var index = 0; index < this.blocks.length; index++) {
  23038. var block = this.blocks[index];
  23039. block.select(frustumPlanes, selection, allowDuplicate);
  23040. }
  23041. return;
  23042. }
  23043. if (allowDuplicate) {
  23044. selection.concat(this.entries);
  23045. }
  23046. else {
  23047. selection.concatWithNoDuplicate(this.entries);
  23048. }
  23049. }
  23050. };
  23051. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  23052. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  23053. if (this.blocks) {
  23054. for (var index = 0; index < this.blocks.length; index++) {
  23055. var block = this.blocks[index];
  23056. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  23057. }
  23058. return;
  23059. }
  23060. if (allowDuplicate) {
  23061. selection.concat(this.entries);
  23062. }
  23063. else {
  23064. selection.concatWithNoDuplicate(this.entries);
  23065. }
  23066. }
  23067. };
  23068. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  23069. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  23070. if (this.blocks) {
  23071. for (var index = 0; index < this.blocks.length; index++) {
  23072. var block = this.blocks[index];
  23073. block.intersectsRay(ray, selection);
  23074. }
  23075. return;
  23076. }
  23077. selection.concatWithNoDuplicate(this.entries);
  23078. }
  23079. };
  23080. OctreeBlock.prototype.createInnerBlocks = function () {
  23081. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  23082. };
  23083. return OctreeBlock;
  23084. })();
  23085. BABYLON.OctreeBlock = OctreeBlock;
  23086. })(BABYLON || (BABYLON = {}));
  23087. var BABYLON;
  23088. (function (BABYLON) {
  23089. var Bone = (function (_super) {
  23090. __extends(Bone, _super);
  23091. function Bone(name, skeleton, parentBone, matrix) {
  23092. _super.call(this, name, skeleton.getScene());
  23093. this.name = name;
  23094. this.children = new Array();
  23095. this.animations = new Array();
  23096. this._worldTransform = new BABYLON.Matrix();
  23097. this._absoluteTransform = new BABYLON.Matrix();
  23098. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23099. this._skeleton = skeleton;
  23100. this._matrix = matrix;
  23101. this._baseMatrix = matrix;
  23102. skeleton.bones.push(this);
  23103. if (parentBone) {
  23104. this._parent = parentBone;
  23105. parentBone.children.push(this);
  23106. }
  23107. else {
  23108. this._parent = null;
  23109. }
  23110. this._updateDifferenceMatrix();
  23111. }
  23112. // Members
  23113. Bone.prototype.getParent = function () {
  23114. return this._parent;
  23115. };
  23116. Bone.prototype.getLocalMatrix = function () {
  23117. return this._matrix;
  23118. };
  23119. Bone.prototype.getBaseMatrix = function () {
  23120. return this._baseMatrix;
  23121. };
  23122. Bone.prototype.getWorldMatrix = function () {
  23123. return this._worldTransform;
  23124. };
  23125. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23126. return this._invertedAbsoluteTransform;
  23127. };
  23128. Bone.prototype.getAbsoluteMatrix = function () {
  23129. var matrix = this._matrix.clone();
  23130. var parent = this._parent;
  23131. while (parent) {
  23132. matrix = matrix.multiply(parent.getLocalMatrix());
  23133. parent = parent.getParent();
  23134. }
  23135. return matrix;
  23136. };
  23137. // Methods
  23138. Bone.prototype.updateMatrix = function (matrix) {
  23139. this._matrix = matrix;
  23140. this._skeleton._markAsDirty();
  23141. this._updateDifferenceMatrix();
  23142. };
  23143. Bone.prototype._updateDifferenceMatrix = function () {
  23144. if (this._parent) {
  23145. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23146. }
  23147. else {
  23148. this._absoluteTransform.copyFrom(this._matrix);
  23149. }
  23150. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23151. for (var index = 0; index < this.children.length; index++) {
  23152. this.children[index]._updateDifferenceMatrix();
  23153. }
  23154. };
  23155. Bone.prototype.markAsDirty = function () {
  23156. this._currentRenderId++;
  23157. this._skeleton._markAsDirty();
  23158. };
  23159. return Bone;
  23160. })(BABYLON.Node);
  23161. BABYLON.Bone = Bone;
  23162. })(BABYLON || (BABYLON = {}));
  23163. var BABYLON;
  23164. (function (BABYLON) {
  23165. var Skeleton = (function () {
  23166. function Skeleton(name, id, scene) {
  23167. this.name = name;
  23168. this.id = id;
  23169. this.bones = new Array();
  23170. this._isDirty = true;
  23171. this._identity = BABYLON.Matrix.Identity();
  23172. this.bones = [];
  23173. this._scene = scene;
  23174. scene.skeletons.push(this);
  23175. this.prepare();
  23176. //make sure it will recalculate the matrix next time prepare is called.
  23177. this._isDirty = true;
  23178. }
  23179. // Members
  23180. Skeleton.prototype.getTransformMatrices = function () {
  23181. return this._transformMatrices;
  23182. };
  23183. Skeleton.prototype.getScene = function () {
  23184. return this._scene;
  23185. };
  23186. // Methods
  23187. Skeleton.prototype._markAsDirty = function () {
  23188. this._isDirty = true;
  23189. };
  23190. Skeleton.prototype.prepare = function () {
  23191. if (!this._isDirty) {
  23192. return;
  23193. }
  23194. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23195. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23196. }
  23197. for (var index = 0; index < this.bones.length; index++) {
  23198. var bone = this.bones[index];
  23199. var parentBone = bone.getParent();
  23200. if (parentBone) {
  23201. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23202. }
  23203. else {
  23204. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23205. }
  23206. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  23207. }
  23208. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  23209. this._isDirty = false;
  23210. this._scene._activeBones += this.bones.length;
  23211. };
  23212. Skeleton.prototype.getAnimatables = function () {
  23213. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23214. this._animatables = [];
  23215. for (var index = 0; index < this.bones.length; index++) {
  23216. this._animatables.push(this.bones[index]);
  23217. }
  23218. }
  23219. return this._animatables;
  23220. };
  23221. Skeleton.prototype.clone = function (name, id) {
  23222. var result = new Skeleton(name, id || name, this._scene);
  23223. for (var index = 0; index < this.bones.length; index++) {
  23224. var source = this.bones[index];
  23225. var parentBone = null;
  23226. if (source.getParent()) {
  23227. var parentIndex = this.bones.indexOf(source.getParent());
  23228. parentBone = result.bones[parentIndex];
  23229. }
  23230. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  23231. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23232. }
  23233. return result;
  23234. };
  23235. return Skeleton;
  23236. })();
  23237. BABYLON.Skeleton = Skeleton;
  23238. })(BABYLON || (BABYLON = {}));
  23239. var BABYLON;
  23240. (function (BABYLON) {
  23241. var PostProcess = (function () {
  23242. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23243. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23244. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23245. this.name = name;
  23246. this.width = -1;
  23247. this.height = -1;
  23248. this._reusable = false;
  23249. this._textures = new BABYLON.SmartArray(2);
  23250. this._currentRenderTextureInd = 0;
  23251. if (camera != null) {
  23252. this._camera = camera;
  23253. this._scene = camera.getScene();
  23254. camera.attachPostProcess(this);
  23255. this._engine = this._scene.getEngine();
  23256. }
  23257. else {
  23258. this._engine = engine;
  23259. }
  23260. this._renderRatio = ratio;
  23261. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23262. this._reusable = reusable || false;
  23263. this._textureType = textureType;
  23264. samplers = samplers || [];
  23265. samplers.push("textureSampler");
  23266. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  23267. }
  23268. PostProcess.prototype.isReusable = function () {
  23269. return this._reusable;
  23270. };
  23271. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23272. camera = camera || this._camera;
  23273. var scene = camera.getScene();
  23274. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23275. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23276. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23277. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23278. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23279. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23280. if (this._textures.length > 0) {
  23281. for (var i = 0; i < this._textures.length; i++) {
  23282. this._engine._releaseTexture(this._textures.data[i]);
  23283. }
  23284. this._textures.reset();
  23285. }
  23286. this.width = desiredWidth;
  23287. this.height = desiredHeight;
  23288. 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 }));
  23289. if (this._reusable) {
  23290. 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 }));
  23291. }
  23292. if (this.onSizeChanged) {
  23293. this.onSizeChanged();
  23294. }
  23295. }
  23296. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23297. if (this.onActivate) {
  23298. this.onActivate(camera);
  23299. }
  23300. // Clear
  23301. if (this.clearColor) {
  23302. this._engine.clear(this.clearColor, true, true);
  23303. }
  23304. else {
  23305. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23306. }
  23307. if (this._reusable) {
  23308. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23309. }
  23310. };
  23311. PostProcess.prototype.apply = function () {
  23312. // Check
  23313. if (!this._effect.isReady())
  23314. return null;
  23315. // States
  23316. this._engine.enableEffect(this._effect);
  23317. this._engine.setState(false);
  23318. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23319. this._engine.setDepthBuffer(false);
  23320. this._engine.setDepthWrite(false);
  23321. // Texture
  23322. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23323. // Parameters
  23324. if (this.onApply) {
  23325. this.onApply(this._effect);
  23326. }
  23327. return this._effect;
  23328. };
  23329. PostProcess.prototype.dispose = function (camera) {
  23330. camera = camera || this._camera;
  23331. if (this._textures.length > 0) {
  23332. for (var i = 0; i < this._textures.length; i++) {
  23333. this._engine._releaseTexture(this._textures.data[i]);
  23334. }
  23335. this._textures.reset();
  23336. }
  23337. if (!camera) {
  23338. return;
  23339. }
  23340. camera.detachPostProcess(this);
  23341. var index = camera._postProcesses.indexOf(this);
  23342. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23343. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23344. }
  23345. };
  23346. return PostProcess;
  23347. })();
  23348. BABYLON.PostProcess = PostProcess;
  23349. })(BABYLON || (BABYLON = {}));
  23350. var BABYLON;
  23351. (function (BABYLON) {
  23352. var PostProcessManager = (function () {
  23353. function PostProcessManager(scene) {
  23354. this._vertexDeclaration = [2];
  23355. this._vertexStrideSize = 2 * 4;
  23356. this._scene = scene;
  23357. }
  23358. PostProcessManager.prototype._prepareBuffers = function () {
  23359. if (this._vertexBuffer) {
  23360. return;
  23361. }
  23362. // VBO
  23363. var vertices = [];
  23364. vertices.push(1, 1);
  23365. vertices.push(-1, 1);
  23366. vertices.push(-1, -1);
  23367. vertices.push(1, -1);
  23368. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23369. // Indices
  23370. var indices = [];
  23371. indices.push(0);
  23372. indices.push(1);
  23373. indices.push(2);
  23374. indices.push(0);
  23375. indices.push(2);
  23376. indices.push(3);
  23377. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23378. };
  23379. // Methods
  23380. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23381. var postProcesses = this._scene.activeCamera._postProcesses;
  23382. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23383. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23384. return false;
  23385. }
  23386. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23387. return true;
  23388. };
  23389. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23390. var engine = this._scene.getEngine();
  23391. for (var index = 0; index < postProcesses.length; index++) {
  23392. if (index < postProcesses.length - 1) {
  23393. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23394. }
  23395. else {
  23396. if (targetTexture) {
  23397. engine.bindFramebuffer(targetTexture);
  23398. }
  23399. else {
  23400. engine.restoreDefaultFramebuffer();
  23401. }
  23402. }
  23403. var pp = postProcesses[index];
  23404. var effect = pp.apply();
  23405. if (effect) {
  23406. if (pp.onBeforeRender) {
  23407. pp.onBeforeRender(effect);
  23408. }
  23409. // VBOs
  23410. this._prepareBuffers();
  23411. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23412. // Draw order
  23413. engine.draw(true, 0, 6);
  23414. if (pp.onAfterRender) {
  23415. pp.onAfterRender(effect);
  23416. }
  23417. }
  23418. }
  23419. // Restore depth buffer
  23420. engine.setDepthBuffer(true);
  23421. engine.setDepthWrite(true);
  23422. };
  23423. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23424. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23425. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23426. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23427. return;
  23428. }
  23429. var engine = this._scene.getEngine();
  23430. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23431. if (index < postProcessesTakenIndices.length - 1) {
  23432. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  23433. }
  23434. else {
  23435. if (targetTexture) {
  23436. engine.bindFramebuffer(targetTexture, faceIndex);
  23437. }
  23438. else {
  23439. engine.restoreDefaultFramebuffer();
  23440. }
  23441. }
  23442. if (doNotPresent) {
  23443. break;
  23444. }
  23445. var pp = postProcesses[postProcessesTakenIndices[index]];
  23446. var effect = pp.apply();
  23447. if (effect) {
  23448. if (pp.onBeforeRender) {
  23449. pp.onBeforeRender(effect);
  23450. }
  23451. // VBOs
  23452. this._prepareBuffers();
  23453. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23454. // Draw order
  23455. engine.draw(true, 0, 6);
  23456. if (pp.onAfterRender) {
  23457. pp.onAfterRender(effect);
  23458. }
  23459. }
  23460. }
  23461. // Restore depth buffer
  23462. engine.setDepthBuffer(true);
  23463. engine.setDepthWrite(true);
  23464. };
  23465. PostProcessManager.prototype.dispose = function () {
  23466. if (this._vertexBuffer) {
  23467. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23468. this._vertexBuffer = null;
  23469. }
  23470. if (this._indexBuffer) {
  23471. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23472. this._indexBuffer = null;
  23473. }
  23474. };
  23475. return PostProcessManager;
  23476. })();
  23477. BABYLON.PostProcessManager = PostProcessManager;
  23478. })(BABYLON || (BABYLON = {}));
  23479. var BABYLON;
  23480. (function (BABYLON) {
  23481. var PassPostProcess = (function (_super) {
  23482. __extends(PassPostProcess, _super);
  23483. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23484. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23485. }
  23486. return PassPostProcess;
  23487. })(BABYLON.PostProcess);
  23488. BABYLON.PassPostProcess = PassPostProcess;
  23489. })(BABYLON || (BABYLON = {}));
  23490. var BABYLON;
  23491. (function (BABYLON) {
  23492. var BlurPostProcess = (function (_super) {
  23493. __extends(BlurPostProcess, _super);
  23494. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  23495. var _this = this;
  23496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  23497. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  23498. this.direction = direction;
  23499. this.blurWidth = blurWidth;
  23500. this.onApply = function (effect) {
  23501. effect.setFloat2("screenSize", _this.width, _this.height);
  23502. effect.setVector2("direction", _this.direction);
  23503. effect.setFloat("blurWidth", _this.blurWidth);
  23504. };
  23505. }
  23506. return BlurPostProcess;
  23507. })(BABYLON.PostProcess);
  23508. BABYLON.BlurPostProcess = BlurPostProcess;
  23509. })(BABYLON || (BABYLON = {}));
  23510. var BABYLON;
  23511. (function (BABYLON) {
  23512. var RefractionPostProcess = (function (_super) {
  23513. __extends(RefractionPostProcess, _super);
  23514. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  23515. var _this = this;
  23516. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  23517. this.color = color;
  23518. this.depth = depth;
  23519. this.colorLevel = colorLevel;
  23520. this.onActivate = function (cam) {
  23521. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  23522. };
  23523. this.onApply = function (effect) {
  23524. effect.setColor3("baseColor", _this.color);
  23525. effect.setFloat("depth", _this.depth);
  23526. effect.setFloat("colorLevel", _this.colorLevel);
  23527. effect.setTexture("refractionSampler", _this._refRexture);
  23528. };
  23529. }
  23530. // Methods
  23531. RefractionPostProcess.prototype.dispose = function (camera) {
  23532. if (this._refRexture) {
  23533. this._refRexture.dispose();
  23534. }
  23535. _super.prototype.dispose.call(this, camera);
  23536. };
  23537. return RefractionPostProcess;
  23538. })(BABYLON.PostProcess);
  23539. BABYLON.RefractionPostProcess = RefractionPostProcess;
  23540. })(BABYLON || (BABYLON = {}));
  23541. var BABYLON;
  23542. (function (BABYLON) {
  23543. var BlackAndWhitePostProcess = (function (_super) {
  23544. __extends(BlackAndWhitePostProcess, _super);
  23545. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23546. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  23547. }
  23548. return BlackAndWhitePostProcess;
  23549. })(BABYLON.PostProcess);
  23550. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  23551. })(BABYLON || (BABYLON = {}));
  23552. var BABYLON;
  23553. (function (BABYLON) {
  23554. var ConvolutionPostProcess = (function (_super) {
  23555. __extends(ConvolutionPostProcess, _super);
  23556. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  23557. var _this = this;
  23558. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  23559. this.kernel = kernel;
  23560. this.onApply = function (effect) {
  23561. effect.setFloat2("screenSize", _this.width, _this.height);
  23562. effect.setArray("kernel", _this.kernel);
  23563. };
  23564. }
  23565. // Statics
  23566. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23567. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23568. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23569. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23570. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23571. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23572. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23573. return ConvolutionPostProcess;
  23574. })(BABYLON.PostProcess);
  23575. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23576. })(BABYLON || (BABYLON = {}));
  23577. var BABYLON;
  23578. (function (BABYLON) {
  23579. var FilterPostProcess = (function (_super) {
  23580. __extends(FilterPostProcess, _super);
  23581. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23582. var _this = this;
  23583. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23584. this.kernelMatrix = kernelMatrix;
  23585. this.onApply = function (effect) {
  23586. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23587. };
  23588. }
  23589. return FilterPostProcess;
  23590. })(BABYLON.PostProcess);
  23591. BABYLON.FilterPostProcess = FilterPostProcess;
  23592. })(BABYLON || (BABYLON = {}));
  23593. var BABYLON;
  23594. (function (BABYLON) {
  23595. var FxaaPostProcess = (function (_super) {
  23596. __extends(FxaaPostProcess, _super);
  23597. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23598. var _this = this;
  23599. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23600. this.onSizeChanged = function () {
  23601. _this.texelWidth = 1.0 / _this.width;
  23602. _this.texelHeight = 1.0 / _this.height;
  23603. };
  23604. this.onApply = function (effect) {
  23605. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23606. };
  23607. }
  23608. return FxaaPostProcess;
  23609. })(BABYLON.PostProcess);
  23610. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23611. })(BABYLON || (BABYLON = {}));
  23612. var BABYLON;
  23613. (function (BABYLON) {
  23614. var StereoscopicInterlacePostProcess = (function (_super) {
  23615. __extends(StereoscopicInterlacePostProcess, _super);
  23616. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23617. var _this = this;
  23618. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23619. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23620. this.onSizeChanged = function () {
  23621. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23622. };
  23623. this.onApply = function (effect) {
  23624. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23625. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23626. };
  23627. }
  23628. return StereoscopicInterlacePostProcess;
  23629. })(BABYLON.PostProcess);
  23630. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23631. })(BABYLON || (BABYLON = {}));
  23632. var BABYLON;
  23633. (function (BABYLON) {
  23634. var LensFlare = (function () {
  23635. function LensFlare(size, position, color, imgUrl, system) {
  23636. this.size = size;
  23637. this.position = position;
  23638. this.dispose = function () {
  23639. if (this.texture) {
  23640. this.texture.dispose();
  23641. }
  23642. // Remove from scene
  23643. var index = this._system.lensFlares.indexOf(this);
  23644. this._system.lensFlares.splice(index, 1);
  23645. };
  23646. this.color = color || new BABYLON.Color3(1, 1, 1);
  23647. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23648. this._system = system;
  23649. system.lensFlares.push(this);
  23650. }
  23651. return LensFlare;
  23652. })();
  23653. BABYLON.LensFlare = LensFlare;
  23654. })(BABYLON || (BABYLON = {}));
  23655. var BABYLON;
  23656. (function (BABYLON) {
  23657. var LensFlareSystem = (function () {
  23658. function LensFlareSystem(name, emitter, scene) {
  23659. this.name = name;
  23660. this.lensFlares = new Array();
  23661. this.borderLimit = 300;
  23662. this.layerMask = 0x0FFFFFFF;
  23663. this._vertexDeclaration = [2];
  23664. this._vertexStrideSize = 2 * 4;
  23665. this._isEnabled = true;
  23666. this._scene = scene;
  23667. this._emitter = emitter;
  23668. scene.lensFlareSystems.push(this);
  23669. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23670. // VBO
  23671. var vertices = [];
  23672. vertices.push(1, 1);
  23673. vertices.push(-1, 1);
  23674. vertices.push(-1, -1);
  23675. vertices.push(1, -1);
  23676. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23677. // Indices
  23678. var indices = [];
  23679. indices.push(0);
  23680. indices.push(1);
  23681. indices.push(2);
  23682. indices.push(0);
  23683. indices.push(2);
  23684. indices.push(3);
  23685. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23686. // Effects
  23687. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23688. }
  23689. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23690. get: function () {
  23691. return this._isEnabled;
  23692. },
  23693. set: function (value) {
  23694. this._isEnabled = value;
  23695. },
  23696. enumerable: true,
  23697. configurable: true
  23698. });
  23699. LensFlareSystem.prototype.getScene = function () {
  23700. return this._scene;
  23701. };
  23702. LensFlareSystem.prototype.getEmitter = function () {
  23703. return this._emitter;
  23704. };
  23705. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23706. this._emitter = newEmitter;
  23707. };
  23708. LensFlareSystem.prototype.getEmitterPosition = function () {
  23709. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23710. };
  23711. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23712. var position = this.getEmitterPosition();
  23713. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23714. this._positionX = position.x;
  23715. this._positionY = position.y;
  23716. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23717. if (position.z > 0) {
  23718. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23719. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23720. return true;
  23721. }
  23722. }
  23723. return false;
  23724. };
  23725. LensFlareSystem.prototype._isVisible = function () {
  23726. if (!this._isEnabled) {
  23727. return false;
  23728. }
  23729. var emitterPosition = this.getEmitterPosition();
  23730. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23731. var distance = direction.length();
  23732. direction.normalize();
  23733. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23734. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23735. return !pickInfo.hit || pickInfo.distance > distance;
  23736. };
  23737. LensFlareSystem.prototype.render = function () {
  23738. if (!this._effect.isReady())
  23739. return false;
  23740. var engine = this._scene.getEngine();
  23741. var viewport = this._scene.activeCamera.viewport;
  23742. var globalViewport = viewport.toGlobal(engine);
  23743. // Position
  23744. if (!this.computeEffectivePosition(globalViewport)) {
  23745. return false;
  23746. }
  23747. // Visibility
  23748. if (!this._isVisible()) {
  23749. return false;
  23750. }
  23751. // Intensity
  23752. var awayX;
  23753. var awayY;
  23754. if (this._positionX < this.borderLimit + globalViewport.x) {
  23755. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23756. }
  23757. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23758. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23759. }
  23760. else {
  23761. awayX = 0;
  23762. }
  23763. if (this._positionY < this.borderLimit + globalViewport.y) {
  23764. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23765. }
  23766. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23767. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23768. }
  23769. else {
  23770. awayY = 0;
  23771. }
  23772. var away = (awayX > awayY) ? awayX : awayY;
  23773. if (away > this.borderLimit) {
  23774. away = this.borderLimit;
  23775. }
  23776. var intensity = 1.0 - (away / this.borderLimit);
  23777. if (intensity < 0) {
  23778. return false;
  23779. }
  23780. if (intensity > 1.0) {
  23781. intensity = 1.0;
  23782. }
  23783. // Position
  23784. var centerX = globalViewport.x + globalViewport.width / 2;
  23785. var centerY = globalViewport.y + globalViewport.height / 2;
  23786. var distX = centerX - this._positionX;
  23787. var distY = centerY - this._positionY;
  23788. // Effects
  23789. engine.enableEffect(this._effect);
  23790. engine.setState(false);
  23791. engine.setDepthBuffer(false);
  23792. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23793. // VBOs
  23794. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23795. // Flares
  23796. for (var index = 0; index < this.lensFlares.length; index++) {
  23797. var flare = this.lensFlares[index];
  23798. var x = centerX - (distX * flare.position);
  23799. var y = centerY - (distY * flare.position);
  23800. var cw = flare.size;
  23801. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23802. var cx = 2 * (x / globalViewport.width) - 1.0;
  23803. var cy = 1.0 - 2 * (y / globalViewport.height);
  23804. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23805. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23806. // Texture
  23807. this._effect.setTexture("textureSampler", flare.texture);
  23808. // Color
  23809. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23810. // Draw order
  23811. engine.draw(true, 0, 6);
  23812. }
  23813. engine.setDepthBuffer(true);
  23814. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23815. return true;
  23816. };
  23817. LensFlareSystem.prototype.dispose = function () {
  23818. if (this._vertexBuffer) {
  23819. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23820. this._vertexBuffer = null;
  23821. }
  23822. if (this._indexBuffer) {
  23823. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23824. this._indexBuffer = null;
  23825. }
  23826. while (this.lensFlares.length) {
  23827. this.lensFlares[0].dispose();
  23828. }
  23829. // Remove from scene
  23830. var index = this._scene.lensFlareSystems.indexOf(this);
  23831. this._scene.lensFlareSystems.splice(index, 1);
  23832. };
  23833. return LensFlareSystem;
  23834. })();
  23835. BABYLON.LensFlareSystem = LensFlareSystem;
  23836. })(BABYLON || (BABYLON = {}));
  23837. var BABYLON;
  23838. (function (BABYLON) {
  23839. var CannonJSPlugin = (function () {
  23840. function CannonJSPlugin() {
  23841. this._registeredMeshes = [];
  23842. this._physicsMaterials = [];
  23843. this.updateBodyPosition = function (mesh) {
  23844. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23845. var registeredMesh = this._registeredMeshes[index];
  23846. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23847. var body = registeredMesh.body;
  23848. var center = mesh.getBoundingInfo().boundingBox.center;
  23849. body.position.set(center.x, center.z, center.y);
  23850. body.quaternion.x = mesh.rotationQuaternion.x;
  23851. body.quaternion.z = mesh.rotationQuaternion.y;
  23852. body.quaternion.y = mesh.rotationQuaternion.z;
  23853. body.quaternion.w = -mesh.rotationQuaternion.w;
  23854. return;
  23855. }
  23856. }
  23857. };
  23858. }
  23859. CannonJSPlugin.prototype.initialize = function (iterations) {
  23860. if (iterations === void 0) { iterations = 10; }
  23861. this._world = new CANNON.World();
  23862. this._world.broadphase = new CANNON.NaiveBroadphase();
  23863. this._world.solver.iterations = iterations;
  23864. };
  23865. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23866. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23867. };
  23868. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23869. this._world.step(delta);
  23870. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23871. var registeredMesh = this._registeredMeshes[index];
  23872. if (registeredMesh.isChild) {
  23873. continue;
  23874. }
  23875. // Body position
  23876. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23877. var deltaPos = registeredMesh.delta;
  23878. if (deltaPos) {
  23879. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23880. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23881. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23882. }
  23883. else {
  23884. registeredMesh.mesh.position.x = bodyX;
  23885. registeredMesh.mesh.position.y = bodyZ;
  23886. registeredMesh.mesh.position.z = bodyY;
  23887. }
  23888. if (!registeredMesh.mesh.rotationQuaternion) {
  23889. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23890. }
  23891. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23892. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23893. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23894. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23895. }
  23896. };
  23897. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23898. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23899. };
  23900. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23901. this.unregisterMesh(mesh);
  23902. mesh.computeWorldMatrix(true);
  23903. switch (impostor) {
  23904. case BABYLON.PhysicsEngine.SphereImpostor:
  23905. var bbox = mesh.getBoundingInfo().boundingBox;
  23906. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23907. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23908. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23909. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23910. case BABYLON.PhysicsEngine.BoxImpostor:
  23911. bbox = mesh.getBoundingInfo().boundingBox;
  23912. var min = bbox.minimumWorld;
  23913. var max = bbox.maximumWorld;
  23914. var box = max.subtract(min).scale(0.5);
  23915. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23916. case BABYLON.PhysicsEngine.PlaneImpostor:
  23917. return this._createPlane(mesh, options);
  23918. case BABYLON.PhysicsEngine.MeshImpostor:
  23919. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23920. var rawFaces = mesh.getIndices();
  23921. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23922. }
  23923. return null;
  23924. };
  23925. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23926. var shape = new CANNON.Sphere(radius);
  23927. if (!options) {
  23928. return shape;
  23929. }
  23930. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23931. };
  23932. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23933. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23934. if (!options) {
  23935. return shape;
  23936. }
  23937. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23938. };
  23939. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23940. var shape = new CANNON.Plane();
  23941. if (!options) {
  23942. return shape;
  23943. }
  23944. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23945. };
  23946. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23947. var verts = [], faces = [];
  23948. mesh.computeWorldMatrix(true);
  23949. // Get vertices
  23950. for (var i = 0; i < rawVerts.length; i += 3) {
  23951. var transformed = BABYLON.Vector3.Zero();
  23952. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23953. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23954. }
  23955. // Get faces
  23956. for (var j = 0; j < rawFaces.length; j += 3) {
  23957. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23958. }
  23959. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23960. if (!options) {
  23961. return shape;
  23962. }
  23963. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23964. };
  23965. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23966. var index;
  23967. var mat;
  23968. for (index = 0; index < this._physicsMaterials.length; index++) {
  23969. mat = this._physicsMaterials[index];
  23970. if (mat.friction === friction && mat.restitution === restitution) {
  23971. return mat;
  23972. }
  23973. }
  23974. var currentMat = new CANNON.Material();
  23975. currentMat.friction = friction;
  23976. currentMat.restitution = restitution;
  23977. this._physicsMaterials.push(currentMat);
  23978. for (index = 0; index < this._physicsMaterials.length; index++) {
  23979. mat = this._physicsMaterials[index];
  23980. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23981. contactMaterial.contactEquationStiffness = 1e10;
  23982. contactMaterial.contactEquationRegularizationTime = 10;
  23983. this._world.addContactMaterial(contactMaterial);
  23984. }
  23985. return currentMat;
  23986. };
  23987. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23988. var initialRotation = null;
  23989. if (mesh.rotationQuaternion) {
  23990. initialRotation = mesh.rotationQuaternion.clone();
  23991. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23992. }
  23993. // The delta between the mesh position and the mesh bounding box center
  23994. var bbox = mesh.getBoundingInfo().boundingBox;
  23995. var deltaPosition = mesh.position.subtract(bbox.center);
  23996. var material = this._addMaterial(friction, restitution);
  23997. var body = new CANNON.RigidBody(mass, shape, material);
  23998. if (initialRotation) {
  23999. body.quaternion.x = initialRotation.x;
  24000. body.quaternion.z = initialRotation.y;
  24001. body.quaternion.y = initialRotation.z;
  24002. body.quaternion.w = -initialRotation.w;
  24003. }
  24004. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24005. this._world.add(body);
  24006. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24007. return body;
  24008. };
  24009. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24010. var compoundShape = new CANNON.Compound();
  24011. for (var index = 0; index < parts.length; index++) {
  24012. var mesh = parts[index].mesh;
  24013. var shape = this.registerMesh(mesh, parts[index].impostor);
  24014. if (index == 0) {
  24015. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24016. }
  24017. else {
  24018. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24019. }
  24020. }
  24021. var initialMesh = parts[0].mesh;
  24022. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24023. body.parts = parts;
  24024. return body;
  24025. };
  24026. CannonJSPlugin.prototype._unbindBody = function (body) {
  24027. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24028. var registeredMesh = this._registeredMeshes[index];
  24029. if (registeredMesh.body === body) {
  24030. registeredMesh.body = null;
  24031. registeredMesh.delta = 0;
  24032. }
  24033. }
  24034. };
  24035. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24036. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24037. var registeredMesh = this._registeredMeshes[index];
  24038. if (registeredMesh.mesh === mesh) {
  24039. // Remove body
  24040. if (registeredMesh.body) {
  24041. this._world.remove(registeredMesh.body);
  24042. this._unbindBody(registeredMesh.body);
  24043. }
  24044. this._registeredMeshes.splice(index, 1);
  24045. return;
  24046. }
  24047. }
  24048. };
  24049. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24050. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24051. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24052. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24053. var registeredMesh = this._registeredMeshes[index];
  24054. if (registeredMesh.mesh === mesh) {
  24055. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24056. return;
  24057. }
  24058. }
  24059. };
  24060. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24061. var body1 = null, body2 = null;
  24062. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24063. var registeredMesh = this._registeredMeshes[index];
  24064. if (registeredMesh.mesh === mesh1) {
  24065. body1 = registeredMesh.body;
  24066. }
  24067. else if (registeredMesh.mesh === mesh2) {
  24068. body2 = registeredMesh.body;
  24069. }
  24070. }
  24071. if (!body1 || !body2) {
  24072. return false;
  24073. }
  24074. 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));
  24075. this._world.addConstraint(constraint);
  24076. return true;
  24077. };
  24078. CannonJSPlugin.prototype.dispose = function () {
  24079. while (this._registeredMeshes.length) {
  24080. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24081. }
  24082. };
  24083. CannonJSPlugin.prototype.isSupported = function () {
  24084. return window.CANNON !== undefined;
  24085. };
  24086. return CannonJSPlugin;
  24087. })();
  24088. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24089. })(BABYLON || (BABYLON = {}));
  24090. var BABYLON;
  24091. (function (BABYLON) {
  24092. var OimoJSPlugin = (function () {
  24093. function OimoJSPlugin() {
  24094. this._registeredMeshes = [];
  24095. /**
  24096. * Update the body position according to the mesh position
  24097. * @param mesh
  24098. */
  24099. this.updateBodyPosition = function (mesh) {
  24100. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24101. var registeredMesh = this._registeredMeshes[index];
  24102. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24103. var body = registeredMesh.body.body;
  24104. mesh.computeWorldMatrix(true);
  24105. var center = mesh.getBoundingInfo().boundingBox.center;
  24106. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  24107. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  24108. body.sleeping = false;
  24109. return;
  24110. }
  24111. // Case where the parent has been updated
  24112. if (registeredMesh.mesh.parent === mesh) {
  24113. mesh.computeWorldMatrix(true);
  24114. registeredMesh.mesh.computeWorldMatrix(true);
  24115. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  24116. var absoluteRotation = mesh.rotation;
  24117. body = registeredMesh.body.body;
  24118. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  24119. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  24120. body.sleeping = false;
  24121. return;
  24122. }
  24123. }
  24124. };
  24125. }
  24126. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  24127. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24128. };
  24129. OimoJSPlugin.prototype.initialize = function (iterations) {
  24130. this._world = new OIMO.World();
  24131. this._world.clear();
  24132. };
  24133. OimoJSPlugin.prototype.setGravity = function (gravity) {
  24134. this._world.gravity = gravity;
  24135. };
  24136. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24137. var body = null;
  24138. this.unregisterMesh(mesh);
  24139. mesh.computeWorldMatrix(true);
  24140. var initialRotation = null;
  24141. if (mesh.rotationQuaternion) {
  24142. initialRotation = mesh.rotationQuaternion.clone();
  24143. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24144. mesh.computeWorldMatrix(true);
  24145. }
  24146. var bbox = mesh.getBoundingInfo().boundingBox;
  24147. // The delta between the mesh position and the mesh bounding box center
  24148. var deltaPosition = mesh.position.subtract(bbox.center);
  24149. // Transform delta position with the rotation
  24150. if (initialRotation) {
  24151. var m = new BABYLON.Matrix();
  24152. initialRotation.toRotationMatrix(m);
  24153. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  24154. }
  24155. // register mesh
  24156. switch (impostor) {
  24157. case BABYLON.PhysicsEngine.SphereImpostor:
  24158. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24159. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24160. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24161. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24162. body = new OIMO.Body({
  24163. type: 'sphere',
  24164. size: [size],
  24165. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24166. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24167. move: options.mass != 0,
  24168. config: [options.mass, options.friction, options.restitution],
  24169. world: this._world
  24170. });
  24171. break;
  24172. case BABYLON.PhysicsEngine.PlaneImpostor:
  24173. //Oimo "fakes" a cylinder as a box, so why don't we!
  24174. case BABYLON.PhysicsEngine.CylinderImpostor:
  24175. case BABYLON.PhysicsEngine.BoxImpostor:
  24176. var min = bbox.minimumWorld;
  24177. var max = bbox.maximumWorld;
  24178. var box = max.subtract(min);
  24179. var sizeX = this._checkWithEpsilon(box.x);
  24180. var sizeY = this._checkWithEpsilon(box.y);
  24181. var sizeZ = this._checkWithEpsilon(box.z);
  24182. body = new OIMO.Body({
  24183. type: 'box',
  24184. size: [sizeX, sizeY, sizeZ],
  24185. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  24186. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  24187. move: options.mass != 0,
  24188. config: [options.mass, options.friction, options.restitution],
  24189. world: this._world
  24190. });
  24191. break;
  24192. }
  24193. //If quaternion was set as the rotation of the object
  24194. if (initialRotation) {
  24195. //We have to access the rigid body's properties to set the quaternion.
  24196. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  24197. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  24198. //update the internal rotation matrix
  24199. body.body.syncShapes();
  24200. }
  24201. this._registeredMeshes.push({
  24202. mesh: mesh,
  24203. body: body,
  24204. delta: deltaPosition
  24205. });
  24206. return body;
  24207. };
  24208. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24209. var types = [], sizes = [], positions = [], rotations = [];
  24210. var initialMesh = parts[0].mesh;
  24211. for (var index = 0; index < parts.length; index++) {
  24212. var part = parts[index];
  24213. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  24214. types.push(bodyParameters.type);
  24215. sizes.push.apply(sizes, bodyParameters.size);
  24216. positions.push.apply(positions, bodyParameters.pos);
  24217. rotations.push.apply(rotations, bodyParameters.rot);
  24218. }
  24219. var body = new OIMO.Body({
  24220. type: types,
  24221. size: sizes,
  24222. pos: positions,
  24223. rot: rotations,
  24224. move: options.mass != 0,
  24225. config: [options.mass, options.friction, options.restitution],
  24226. world: this._world
  24227. });
  24228. this._registeredMeshes.push({
  24229. mesh: initialMesh,
  24230. body: body
  24231. });
  24232. return body;
  24233. };
  24234. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  24235. var bodyParameters = null;
  24236. var mesh = part.mesh;
  24237. // We need the bounding box/sphere info to compute the physics body
  24238. mesh.computeWorldMatrix();
  24239. switch (part.impostor) {
  24240. case BABYLON.PhysicsEngine.SphereImpostor:
  24241. var bbox = mesh.getBoundingInfo().boundingBox;
  24242. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24243. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24244. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24245. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  24246. bodyParameters = {
  24247. type: 'sphere',
  24248. /* bug with oimo : sphere needs 3 sizes in this case */
  24249. size: [size, -1, -1],
  24250. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  24251. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24252. };
  24253. break;
  24254. case BABYLON.PhysicsEngine.PlaneImpostor:
  24255. case BABYLON.PhysicsEngine.BoxImpostor:
  24256. bbox = mesh.getBoundingInfo().boundingBox;
  24257. var min = bbox.minimumWorld;
  24258. var max = bbox.maximumWorld;
  24259. var box = max.subtract(min);
  24260. var sizeX = this._checkWithEpsilon(box.x);
  24261. var sizeY = this._checkWithEpsilon(box.y);
  24262. var sizeZ = this._checkWithEpsilon(box.z);
  24263. var relativePosition = mesh.position;
  24264. bodyParameters = {
  24265. type: 'box',
  24266. size: [sizeX, sizeY, sizeZ],
  24267. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  24268. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  24269. };
  24270. break;
  24271. }
  24272. return bodyParameters;
  24273. };
  24274. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  24275. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24276. var registeredMesh = this._registeredMeshes[index];
  24277. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24278. if (registeredMesh.body) {
  24279. this._world.removeRigidBody(registeredMesh.body.body);
  24280. this._unbindBody(registeredMesh.body);
  24281. }
  24282. this._registeredMeshes.splice(index, 1);
  24283. return;
  24284. }
  24285. }
  24286. };
  24287. OimoJSPlugin.prototype._unbindBody = function (body) {
  24288. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24289. var registeredMesh = this._registeredMeshes[index];
  24290. if (registeredMesh.body === body) {
  24291. registeredMesh.body = null;
  24292. }
  24293. }
  24294. };
  24295. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24296. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24297. var registeredMesh = this._registeredMeshes[index];
  24298. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24299. // Get object mass to have a behaviour similar to cannon.js
  24300. var mass = registeredMesh.body.body.massInfo.mass;
  24301. // The force is scaled with the mass of object
  24302. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  24303. return;
  24304. }
  24305. }
  24306. };
  24307. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24308. var body1 = null, body2 = null;
  24309. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24310. var registeredMesh = this._registeredMeshes[index];
  24311. if (registeredMesh.mesh === mesh1) {
  24312. body1 = registeredMesh.body.body;
  24313. }
  24314. else if (registeredMesh.mesh === mesh2) {
  24315. body2 = registeredMesh.body.body;
  24316. }
  24317. }
  24318. if (!body1 || !body2) {
  24319. return false;
  24320. }
  24321. if (!options) {
  24322. options = {};
  24323. }
  24324. new OIMO.Link({
  24325. type: options.type,
  24326. body1: body1,
  24327. body2: body2,
  24328. min: options.min,
  24329. max: options.max,
  24330. axe1: options.axe1,
  24331. axe2: options.axe2,
  24332. pos1: [pivot1.x, pivot1.y, pivot1.z],
  24333. pos2: [pivot2.x, pivot2.y, pivot2.z],
  24334. collision: options.collision,
  24335. spring: options.spring,
  24336. world: this._world
  24337. });
  24338. return true;
  24339. };
  24340. OimoJSPlugin.prototype.dispose = function () {
  24341. this._world.clear();
  24342. while (this._registeredMeshes.length) {
  24343. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24344. }
  24345. };
  24346. OimoJSPlugin.prototype.isSupported = function () {
  24347. return OIMO !== undefined;
  24348. };
  24349. OimoJSPlugin.prototype._getLastShape = function (body) {
  24350. var lastShape = body.shapes;
  24351. while (lastShape.next) {
  24352. lastShape = lastShape.next;
  24353. }
  24354. return lastShape;
  24355. };
  24356. OimoJSPlugin.prototype.runOneStep = function (time) {
  24357. this._world.step();
  24358. // Update the position of all registered meshes
  24359. var i = this._registeredMeshes.length;
  24360. var m;
  24361. while (i--) {
  24362. var body = this._registeredMeshes[i].body.body;
  24363. var mesh = this._registeredMeshes[i].mesh;
  24364. var delta = this._registeredMeshes[i].delta;
  24365. if (!body.sleeping) {
  24366. if (body.shapes.next) {
  24367. var parentShape = this._getLastShape(body);
  24368. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  24369. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  24370. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  24371. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  24372. if (!mesh.rotationQuaternion) {
  24373. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24374. }
  24375. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  24376. mesh.computeWorldMatrix();
  24377. }
  24378. else {
  24379. m = body.getMatrix();
  24380. mtx = BABYLON.Matrix.FromArray(m);
  24381. // Body position
  24382. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  24383. if (!delta) {
  24384. mesh.position.x = bodyX;
  24385. mesh.position.y = bodyY;
  24386. mesh.position.z = bodyZ;
  24387. }
  24388. else {
  24389. mesh.position.x = bodyX + delta.x;
  24390. mesh.position.y = bodyY + delta.y;
  24391. mesh.position.z = bodyZ + delta.z;
  24392. }
  24393. if (!mesh.rotationQuaternion) {
  24394. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24395. }
  24396. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  24397. mesh.computeWorldMatrix();
  24398. }
  24399. }
  24400. }
  24401. };
  24402. return OimoJSPlugin;
  24403. })();
  24404. BABYLON.OimoJSPlugin = OimoJSPlugin;
  24405. })(BABYLON || (BABYLON = {}));
  24406. var BABYLON;
  24407. (function (BABYLON) {
  24408. var PhysicsEngine = (function () {
  24409. function PhysicsEngine(plugin) {
  24410. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  24411. }
  24412. PhysicsEngine.prototype._initialize = function (gravity) {
  24413. this._currentPlugin.initialize();
  24414. this._setGravity(gravity);
  24415. };
  24416. PhysicsEngine.prototype._runOneStep = function (delta) {
  24417. if (delta > 0.1) {
  24418. delta = 0.1;
  24419. }
  24420. else if (delta <= 0) {
  24421. delta = 1.0 / 60.0;
  24422. }
  24423. this._currentPlugin.runOneStep(delta);
  24424. };
  24425. PhysicsEngine.prototype._setGravity = function (gravity) {
  24426. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24427. this._currentPlugin.setGravity(this.gravity);
  24428. };
  24429. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  24430. return this._currentPlugin.registerMesh(mesh, impostor, options);
  24431. };
  24432. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  24433. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  24434. };
  24435. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  24436. this._currentPlugin.unregisterMesh(mesh);
  24437. };
  24438. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  24439. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  24440. };
  24441. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  24442. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  24443. };
  24444. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  24445. this._currentPlugin.updateBodyPosition(mesh);
  24446. };
  24447. PhysicsEngine.prototype.dispose = function () {
  24448. this._currentPlugin.dispose();
  24449. };
  24450. PhysicsEngine.prototype.isSupported = function () {
  24451. return this._currentPlugin.isSupported();
  24452. };
  24453. // Statics
  24454. PhysicsEngine.NoImpostor = 0;
  24455. PhysicsEngine.SphereImpostor = 1;
  24456. PhysicsEngine.BoxImpostor = 2;
  24457. PhysicsEngine.PlaneImpostor = 3;
  24458. PhysicsEngine.MeshImpostor = 4;
  24459. PhysicsEngine.CapsuleImpostor = 5;
  24460. PhysicsEngine.ConeImpostor = 6;
  24461. PhysicsEngine.CylinderImpostor = 7;
  24462. PhysicsEngine.ConvexHullImpostor = 8;
  24463. PhysicsEngine.Epsilon = 0.001;
  24464. return PhysicsEngine;
  24465. })();
  24466. BABYLON.PhysicsEngine = PhysicsEngine;
  24467. })(BABYLON || (BABYLON = {}));
  24468. var BABYLON;
  24469. (function (BABYLON) {
  24470. var serializeLight = function (light) {
  24471. var serializationObject = {};
  24472. serializationObject.name = light.name;
  24473. serializationObject.id = light.id;
  24474. serializationObject.tags = BABYLON.Tags.GetTags(light);
  24475. if (light instanceof BABYLON.PointLight) {
  24476. serializationObject.type = 0;
  24477. serializationObject.position = (light).position.asArray();
  24478. }
  24479. else if (light instanceof BABYLON.DirectionalLight) {
  24480. serializationObject.type = 1;
  24481. var directionalLight = light;
  24482. serializationObject.position = directionalLight.position.asArray();
  24483. serializationObject.direction = directionalLight.direction.asArray();
  24484. }
  24485. else if (light instanceof BABYLON.SpotLight) {
  24486. serializationObject.type = 2;
  24487. var spotLight = light;
  24488. serializationObject.position = spotLight.position.asArray();
  24489. serializationObject.direction = spotLight.position.asArray();
  24490. serializationObject.angle = spotLight.angle;
  24491. serializationObject.exponent = spotLight.exponent;
  24492. }
  24493. else if (light instanceof BABYLON.HemisphericLight) {
  24494. serializationObject.type = 3;
  24495. var hemisphericLight = light;
  24496. serializationObject.direction = hemisphericLight.direction.asArray();
  24497. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  24498. }
  24499. if (light.intensity) {
  24500. serializationObject.intensity = light.intensity;
  24501. }
  24502. serializationObject.range = light.range;
  24503. serializationObject.diffuse = light.diffuse.asArray();
  24504. serializationObject.specular = light.specular.asArray();
  24505. return serializationObject;
  24506. };
  24507. var serializeFresnelParameter = function (fresnelParameter) {
  24508. var serializationObject = {};
  24509. serializationObject.isEnabled = fresnelParameter.isEnabled;
  24510. serializationObject.leftColor = fresnelParameter.leftColor;
  24511. serializationObject.rightColor = fresnelParameter.rightColor;
  24512. serializationObject.bias = fresnelParameter.bias;
  24513. serializationObject.power = fresnelParameter.power;
  24514. return serializationObject;
  24515. };
  24516. var serializeAnimation;
  24517. var appendAnimations = function (source, destination) {
  24518. if (source.animations) {
  24519. destination.animations = [];
  24520. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  24521. var animation = source.animations[animationIndex];
  24522. destination.animations.push(serializeAnimation(animation));
  24523. }
  24524. }
  24525. };
  24526. var serializeCamera = function (camera) {
  24527. var serializationObject = {};
  24528. serializationObject.name = camera.name;
  24529. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  24530. serializationObject.id = camera.id;
  24531. serializationObject.position = camera.position.asArray();
  24532. // Parent
  24533. if (camera.parent) {
  24534. serializationObject.parentId = camera.parent.id;
  24535. }
  24536. serializationObject.fov = camera.fov;
  24537. serializationObject.minZ = camera.minZ;
  24538. serializationObject.maxZ = camera.maxZ;
  24539. serializationObject.inertia = camera.inertia;
  24540. //setting the type
  24541. if (camera instanceof BABYLON.FreeCamera) {
  24542. serializationObject.type = "FreeCamera";
  24543. }
  24544. else if (camera instanceof BABYLON.ArcRotateCamera) {
  24545. serializationObject.type = "ArcRotateCamera";
  24546. }
  24547. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24548. serializationObject.type = "AnaglyphArcRotateCamera";
  24549. }
  24550. else if (camera instanceof BABYLON.GamepadCamera) {
  24551. serializationObject.type = "GamepadCamera";
  24552. }
  24553. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  24554. serializationObject.type = "AnaglyphFreeCamera";
  24555. }
  24556. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  24557. serializationObject.type = "DeviceOrientationCamera";
  24558. }
  24559. else if (camera instanceof BABYLON.FollowCamera) {
  24560. serializationObject.type = "FollowCamera";
  24561. }
  24562. else if (camera instanceof BABYLON.TouchCamera) {
  24563. serializationObject.type = "TouchCamera";
  24564. }
  24565. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  24566. serializationObject.type = "VirtualJoysticksCamera";
  24567. }
  24568. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24569. serializationObject.type = "WebVRFreeCamera";
  24570. }
  24571. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24572. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24573. }
  24574. //special properties of specific cameras
  24575. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24576. var arcCamera = camera;
  24577. serializationObject.alpha = arcCamera.alpha;
  24578. serializationObject.beta = arcCamera.beta;
  24579. serializationObject.radius = arcCamera.radius;
  24580. if (arcCamera.target && arcCamera.target.id) {
  24581. serializationObject.lockedTargetId = arcCamera.target.id;
  24582. }
  24583. }
  24584. else if (camera instanceof BABYLON.FollowCamera) {
  24585. var followCam = camera;
  24586. serializationObject.radius = followCam.radius;
  24587. serializationObject.heightOffset = followCam.heightOffset;
  24588. serializationObject.rotationOffset = followCam.rotationOffset;
  24589. }
  24590. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24591. //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.
  24592. if (camera['_interaxialDistance'] !== undefined) {
  24593. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24594. }
  24595. }
  24596. //general properties that not all cameras have. The [] is due to typescript's type safety
  24597. if (camera['speed'] !== undefined) {
  24598. serializationObject.speed = camera['speed'];
  24599. }
  24600. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24601. serializationObject.target = camera['target'].asArray();
  24602. }
  24603. // Target
  24604. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24605. serializationObject.rotation = camera['rotation'].asArray();
  24606. }
  24607. // Locked target
  24608. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24609. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24610. }
  24611. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24612. serializationObject.applyGravity = camera['applyGravity'] || false;
  24613. if (camera['ellipsoid']) {
  24614. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24615. }
  24616. // Animations
  24617. appendAnimations(camera, serializationObject);
  24618. // Layer mask
  24619. serializationObject.layerMask = camera.layerMask;
  24620. return serializationObject;
  24621. };
  24622. serializeAnimation = function (animation) {
  24623. var serializationObject = {};
  24624. serializationObject.name = animation.name;
  24625. serializationObject.property = animation.targetProperty;
  24626. serializationObject.framePerSecond = animation.framePerSecond;
  24627. serializationObject.dataType = animation.dataType;
  24628. serializationObject.loopBehavior = animation.loopMode;
  24629. var dataType = animation.dataType;
  24630. serializationObject.keys = [];
  24631. var keys = animation.getKeys();
  24632. for (var index = 0; index < keys.length; index++) {
  24633. var animationKey = keys[index];
  24634. var key = {};
  24635. key.frame = animationKey.frame;
  24636. switch (dataType) {
  24637. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24638. key.values = [animationKey.value];
  24639. break;
  24640. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24641. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24642. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24643. key.values = animationKey.value.asArray();
  24644. break;
  24645. }
  24646. serializationObject.keys.push(key);
  24647. }
  24648. return serializationObject;
  24649. };
  24650. var serializeMultiMaterial = function (material) {
  24651. var serializationObject = {};
  24652. serializationObject.name = material.name;
  24653. serializationObject.id = material.id;
  24654. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24655. serializationObject.materials = [];
  24656. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24657. var subMat = material.subMaterials[matIndex];
  24658. if (subMat) {
  24659. serializationObject.materials.push(subMat.id);
  24660. }
  24661. else {
  24662. serializationObject.materials.push(null);
  24663. }
  24664. }
  24665. return serializationObject;
  24666. };
  24667. var serializeTexture;
  24668. var serializeMaterial = function (material) {
  24669. var serializationObject = {};
  24670. serializationObject.name = material.name;
  24671. serializationObject.ambient = material.ambientColor.asArray();
  24672. serializationObject.diffuse = material.diffuseColor.asArray();
  24673. serializationObject.specular = material.specularColor.asArray();
  24674. serializationObject.specularPower = material.specularPower;
  24675. serializationObject.emissive = material.emissiveColor.asArray();
  24676. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  24677. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  24678. serializationObject.alpha = material.alpha;
  24679. serializationObject.id = material.id;
  24680. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24681. serializationObject.backFaceCulling = material.backFaceCulling;
  24682. if (material.diffuseTexture) {
  24683. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24684. }
  24685. if (material.diffuseFresnelParameters) {
  24686. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24687. }
  24688. if (material.ambientTexture) {
  24689. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24690. }
  24691. if (material.opacityTexture) {
  24692. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24693. }
  24694. if (material.opacityFresnelParameters) {
  24695. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24696. }
  24697. if (material.reflectionTexture) {
  24698. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24699. }
  24700. if (material.reflectionFresnelParameters) {
  24701. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24702. }
  24703. if (material.emissiveTexture) {
  24704. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24705. }
  24706. if (material.lightmapTexture) {
  24707. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  24708. serializationObject.lightmapThreshold = material.lightmapThreshold;
  24709. }
  24710. if (material.emissiveFresnelParameters) {
  24711. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24712. }
  24713. if (material.specularTexture) {
  24714. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24715. }
  24716. if (material.bumpTexture) {
  24717. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24718. }
  24719. return serializationObject;
  24720. };
  24721. serializeTexture = function (texture) {
  24722. var serializationObject = {};
  24723. if (!texture.name) {
  24724. return null;
  24725. }
  24726. if (texture instanceof BABYLON.CubeTexture) {
  24727. serializationObject.name = texture.name;
  24728. serializationObject.hasAlpha = texture.hasAlpha;
  24729. serializationObject.isCube = true;
  24730. serializationObject.level = texture.level;
  24731. serializationObject.coordinatesMode = texture.coordinatesMode;
  24732. return serializationObject;
  24733. }
  24734. var index;
  24735. if (texture instanceof BABYLON.MirrorTexture) {
  24736. var mirrorTexture = texture;
  24737. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24738. serializationObject.renderList = [];
  24739. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  24740. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24741. }
  24742. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24743. }
  24744. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24745. var renderTargetTexture = texture;
  24746. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24747. serializationObject.renderList = [];
  24748. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24749. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24750. }
  24751. }
  24752. var regularTexture = texture;
  24753. serializationObject.name = texture.name;
  24754. serializationObject.hasAlpha = texture.hasAlpha;
  24755. serializationObject.level = texture.level;
  24756. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24757. serializationObject.coordinatesMode = texture.coordinatesMode;
  24758. serializationObject.uOffset = regularTexture.uOffset;
  24759. serializationObject.vOffset = regularTexture.vOffset;
  24760. serializationObject.uScale = regularTexture.uScale;
  24761. serializationObject.vScale = regularTexture.vScale;
  24762. serializationObject.uAng = regularTexture.uAng;
  24763. serializationObject.vAng = regularTexture.vAng;
  24764. serializationObject.wAng = regularTexture.wAng;
  24765. serializationObject.wrapU = texture.wrapU;
  24766. serializationObject.wrapV = texture.wrapV;
  24767. // Animations
  24768. appendAnimations(texture, serializationObject);
  24769. return serializationObject;
  24770. };
  24771. var serializeSkeleton = function (skeleton) {
  24772. var serializationObject = {};
  24773. serializationObject.name = skeleton.name;
  24774. serializationObject.id = skeleton.id;
  24775. serializationObject.bones = [];
  24776. for (var index = 0; index < skeleton.bones.length; index++) {
  24777. var bone = skeleton.bones[index];
  24778. var serializedBone = {
  24779. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24780. name: bone.name,
  24781. matrix: bone.getLocalMatrix().toArray()
  24782. };
  24783. serializationObject.bones.push(serializedBone);
  24784. if (bone.animations && bone.animations.length > 0) {
  24785. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24786. }
  24787. }
  24788. return serializationObject;
  24789. };
  24790. var serializeParticleSystem = function (particleSystem) {
  24791. var serializationObject = {};
  24792. serializationObject.emitterId = particleSystem.emitter.id;
  24793. serializationObject.capacity = particleSystem.getCapacity();
  24794. if (particleSystem.particleTexture) {
  24795. serializationObject.textureName = particleSystem.particleTexture.name;
  24796. }
  24797. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24798. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24799. serializationObject.minSize = particleSystem.minSize;
  24800. serializationObject.maxSize = particleSystem.maxSize;
  24801. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24802. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24803. serializationObject.emitRate = particleSystem.emitRate;
  24804. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24805. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24806. serializationObject.gravity = particleSystem.gravity.asArray();
  24807. serializationObject.direction1 = particleSystem.direction1.asArray();
  24808. serializationObject.direction2 = particleSystem.direction2.asArray();
  24809. serializationObject.color1 = particleSystem.color1.asArray();
  24810. serializationObject.color2 = particleSystem.color2.asArray();
  24811. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24812. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24813. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24814. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24815. serializationObject.blendMode = particleSystem.blendMode;
  24816. return serializationObject;
  24817. };
  24818. var serializeLensFlareSystem = function (lensFlareSystem) {
  24819. var serializationObject = {};
  24820. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24821. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24822. serializationObject.flares = [];
  24823. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24824. var flare = lensFlareSystem.lensFlares[index];
  24825. serializationObject.flares.push({
  24826. size: flare.size,
  24827. position: flare.position,
  24828. color: flare.color.asArray(),
  24829. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24830. });
  24831. }
  24832. return serializationObject;
  24833. };
  24834. var serializeShadowGenerator = function (light) {
  24835. var serializationObject = {};
  24836. var shadowGenerator = light.getShadowGenerator();
  24837. serializationObject.lightId = light.id;
  24838. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24839. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24840. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24841. serializationObject.renderList = [];
  24842. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24843. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24844. serializationObject.renderList.push(mesh.id);
  24845. }
  24846. return serializationObject;
  24847. };
  24848. var serializedGeometries = [];
  24849. var serializeVertexData;
  24850. var serializeTorusKnot;
  24851. var serializePlane;
  24852. var serializeGround;
  24853. var serializeTorus;
  24854. var serializeCylinder;
  24855. var serializeSphere;
  24856. var serializeBox;
  24857. var serializeGeometry = function (geometry, serializationGeometries) {
  24858. if (serializedGeometries[geometry.id]) {
  24859. return;
  24860. }
  24861. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24862. serializationGeometries.boxes.push(serializeBox(geometry));
  24863. }
  24864. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24865. serializationGeometries.spheres.push(serializeSphere(geometry));
  24866. }
  24867. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24868. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24869. }
  24870. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24871. serializationGeometries.toruses.push(serializeTorus(geometry));
  24872. }
  24873. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24874. serializationGeometries.grounds.push(serializeGround(geometry));
  24875. }
  24876. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24877. serializationGeometries.planes.push(serializePlane(geometry));
  24878. }
  24879. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24880. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24881. }
  24882. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24883. throw new Error("Unknown primitive type");
  24884. }
  24885. else {
  24886. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24887. }
  24888. serializedGeometries[geometry.id] = true;
  24889. };
  24890. var serializeGeometryBase = function (geometry) {
  24891. var serializationObject = {};
  24892. serializationObject.id = geometry.id;
  24893. if (BABYLON.Tags.HasTags(geometry)) {
  24894. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24895. }
  24896. return serializationObject;
  24897. };
  24898. serializeVertexData = function (vertexData) {
  24899. var serializationObject = serializeGeometryBase(vertexData);
  24900. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24901. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24902. }
  24903. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24904. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24905. }
  24906. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24907. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24908. }
  24909. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24910. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24911. }
  24912. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24913. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24914. }
  24915. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24916. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24917. }
  24918. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24919. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24920. }
  24921. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24922. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24923. }
  24924. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24925. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24926. }
  24927. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24928. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24929. serializationObject.matricesIndices._isExpanded = true;
  24930. }
  24931. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24932. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24933. }
  24934. serializationObject.indices = vertexData.getIndices();
  24935. return serializationObject;
  24936. };
  24937. var serializePrimitive = function (primitive) {
  24938. var serializationObject = serializeGeometryBase(primitive);
  24939. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24940. return serializationObject;
  24941. };
  24942. serializeBox = function (box) {
  24943. var serializationObject = serializePrimitive(box);
  24944. serializationObject.size = box.size;
  24945. return serializationObject;
  24946. };
  24947. serializeSphere = function (sphere) {
  24948. var serializationObject = serializePrimitive(sphere);
  24949. serializationObject.segments = sphere.segments;
  24950. serializationObject.diameter = sphere.diameter;
  24951. return serializationObject;
  24952. };
  24953. serializeCylinder = function (cylinder) {
  24954. var serializationObject = serializePrimitive(cylinder);
  24955. serializationObject.height = cylinder.height;
  24956. serializationObject.diameterTop = cylinder.diameterTop;
  24957. serializationObject.diameterBottom = cylinder.diameterBottom;
  24958. serializationObject.tessellation = cylinder.tessellation;
  24959. return serializationObject;
  24960. };
  24961. serializeTorus = function (torus) {
  24962. var serializationObject = serializePrimitive(torus);
  24963. serializationObject.diameter = torus.diameter;
  24964. serializationObject.thickness = torus.thickness;
  24965. serializationObject.tessellation = torus.tessellation;
  24966. return serializationObject;
  24967. };
  24968. serializeGround = function (ground) {
  24969. var serializationObject = serializePrimitive(ground);
  24970. serializationObject.width = ground.width;
  24971. serializationObject.height = ground.height;
  24972. serializationObject.subdivisions = ground.subdivisions;
  24973. return serializationObject;
  24974. };
  24975. serializePlane = function (plane) {
  24976. var serializationObject = serializePrimitive(plane);
  24977. serializationObject.size = plane.size;
  24978. return serializationObject;
  24979. };
  24980. serializeTorusKnot = function (torusKnot) {
  24981. var serializationObject = serializePrimitive(torusKnot);
  24982. serializationObject.radius = torusKnot.radius;
  24983. serializationObject.tube = torusKnot.tube;
  24984. serializationObject.radialSegments = torusKnot.radialSegments;
  24985. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24986. serializationObject.p = torusKnot.p;
  24987. serializationObject.q = torusKnot.q;
  24988. return serializationObject;
  24989. };
  24990. var serializeMesh = function (mesh, serializationScene) {
  24991. var serializationObject = {};
  24992. serializationObject.name = mesh.name;
  24993. serializationObject.id = mesh.id;
  24994. if (BABYLON.Tags.HasTags(mesh)) {
  24995. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24996. }
  24997. serializationObject.position = mesh.position.asArray();
  24998. if (mesh.rotationQuaternion) {
  24999. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  25000. }
  25001. else if (mesh.rotation) {
  25002. serializationObject.rotation = mesh.rotation.asArray();
  25003. }
  25004. serializationObject.scaling = mesh.scaling.asArray();
  25005. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  25006. serializationObject.isEnabled = mesh.isEnabled();
  25007. serializationObject.isVisible = mesh.isVisible;
  25008. serializationObject.infiniteDistance = mesh.infiniteDistance;
  25009. serializationObject.pickable = mesh.isPickable;
  25010. serializationObject.receiveShadows = mesh.receiveShadows;
  25011. serializationObject.billboardMode = mesh.billboardMode;
  25012. serializationObject.visibility = mesh.visibility;
  25013. serializationObject.checkCollisions = mesh.checkCollisions;
  25014. // Parent
  25015. if (mesh.parent) {
  25016. serializationObject.parentId = mesh.parent.id;
  25017. }
  25018. // Geometry
  25019. var geometry = mesh._geometry;
  25020. if (geometry) {
  25021. var geometryId = geometry.id;
  25022. serializationObject.geometryId = geometryId;
  25023. if (!mesh.getScene().getGeometryByID(geometryId)) {
  25024. // 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
  25025. serializeGeometry(geometry, serializationScene.geometries);
  25026. }
  25027. // SubMeshes
  25028. serializationObject.subMeshes = [];
  25029. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25030. var subMesh = mesh.subMeshes[subIndex];
  25031. serializationObject.subMeshes.push({
  25032. materialIndex: subMesh.materialIndex,
  25033. verticesStart: subMesh.verticesStart,
  25034. verticesCount: subMesh.verticesCount,
  25035. indexStart: subMesh.indexStart,
  25036. indexCount: subMesh.indexCount
  25037. });
  25038. }
  25039. }
  25040. // Material
  25041. if (mesh.material) {
  25042. serializationObject.materialId = mesh.material.id;
  25043. }
  25044. else {
  25045. mesh.material = null;
  25046. }
  25047. // Skeleton
  25048. if (mesh.skeleton) {
  25049. serializationObject.skeletonId = mesh.skeleton.id;
  25050. }
  25051. // Physics
  25052. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  25053. serializationObject.physicsMass = mesh.getPhysicsMass();
  25054. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  25055. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  25056. switch (mesh.getPhysicsImpostor()) {
  25057. case BABYLON.PhysicsEngine.BoxImpostor:
  25058. serializationObject.physicsImpostor = 1;
  25059. break;
  25060. case BABYLON.PhysicsEngine.SphereImpostor:
  25061. serializationObject.physicsImpostor = 2;
  25062. break;
  25063. }
  25064. }
  25065. // Instances
  25066. serializationObject.instances = [];
  25067. for (var index = 0; index < mesh.instances.length; index++) {
  25068. var instance = mesh.instances[index];
  25069. var serializationInstance = {
  25070. name: instance.name,
  25071. position: instance.position.asArray(),
  25072. rotation: instance.rotation.asArray(),
  25073. rotationQuaternion: instance.rotationQuaternion.asArray(),
  25074. scaling: instance.scaling.asArray()
  25075. };
  25076. serializationObject.instances.push(serializationInstance);
  25077. // Animations
  25078. appendAnimations(instance, serializationInstance);
  25079. }
  25080. // Animations
  25081. appendAnimations(mesh, serializationObject);
  25082. // Layer mask
  25083. serializationObject.layerMask = mesh.layerMask;
  25084. return serializationObject;
  25085. };
  25086. var finalizeSingleMesh = function (mesh, serializationObject) {
  25087. //only works if the mesh is already loaded
  25088. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25089. //serialize material
  25090. if (mesh.material) {
  25091. if (mesh.material instanceof BABYLON.StandardMaterial) {
  25092. serializationObject.materials = serializationObject.materials || [];
  25093. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25094. serializationObject.materials.push(serializeMaterial(mesh.material));
  25095. }
  25096. }
  25097. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  25098. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  25099. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  25100. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  25101. }
  25102. }
  25103. }
  25104. //serialize geometry
  25105. var geometry = mesh._geometry;
  25106. if (geometry) {
  25107. if (!serializationObject.geometries) {
  25108. serializationObject.geometries = {};
  25109. serializationObject.geometries.boxes = [];
  25110. serializationObject.geometries.spheres = [];
  25111. serializationObject.geometries.cylinders = [];
  25112. serializationObject.geometries.toruses = [];
  25113. serializationObject.geometries.grounds = [];
  25114. serializationObject.geometries.planes = [];
  25115. serializationObject.geometries.torusKnots = [];
  25116. serializationObject.geometries.vertexData = [];
  25117. }
  25118. serializeGeometry(geometry, serializationObject.geometries);
  25119. }
  25120. // Skeletons
  25121. if (mesh.skeleton) {
  25122. serializationObject.skeletons = serializationObject.skeletons || [];
  25123. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  25124. }
  25125. //serialize the actual mesh
  25126. serializationObject.meshes = serializationObject.meshes || [];
  25127. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25128. }
  25129. };
  25130. var SceneSerializer = (function () {
  25131. function SceneSerializer() {
  25132. }
  25133. SceneSerializer.Serialize = function (scene) {
  25134. var serializationObject = {};
  25135. // Scene
  25136. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  25137. serializationObject.autoClear = scene.autoClear;
  25138. serializationObject.clearColor = scene.clearColor.asArray();
  25139. serializationObject.ambientColor = scene.ambientColor.asArray();
  25140. serializationObject.gravity = scene.gravity.asArray();
  25141. // Fog
  25142. if (scene.fogMode && scene.fogMode !== 0) {
  25143. serializationObject.fogMode = scene.fogMode;
  25144. serializationObject.fogColor = scene.fogColor.asArray();
  25145. serializationObject.fogStart = scene.fogStart;
  25146. serializationObject.fogEnd = scene.fogEnd;
  25147. serializationObject.fogDensity = scene.fogDensity;
  25148. }
  25149. // Lights
  25150. serializationObject.lights = [];
  25151. var index;
  25152. var light;
  25153. for (index = 0; index < scene.lights.length; index++) {
  25154. light = scene.lights[index];
  25155. serializationObject.lights.push(serializeLight(light));
  25156. }
  25157. // Cameras
  25158. serializationObject.cameras = [];
  25159. for (index = 0; index < scene.cameras.length; index++) {
  25160. var camera = scene.cameras[index];
  25161. serializationObject.cameras.push(serializeCamera(camera));
  25162. }
  25163. if (scene.activeCamera) {
  25164. serializationObject.activeCameraID = scene.activeCamera.id;
  25165. }
  25166. // Materials
  25167. serializationObject.materials = [];
  25168. serializationObject.multiMaterials = [];
  25169. var material;
  25170. for (index = 0; index < scene.materials.length; index++) {
  25171. material = scene.materials[index];
  25172. serializationObject.materials.push(serializeMaterial(material));
  25173. }
  25174. // MultiMaterials
  25175. serializationObject.multiMaterials = [];
  25176. for (index = 0; index < scene.multiMaterials.length; index++) {
  25177. var multiMaterial = scene.multiMaterials[index];
  25178. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  25179. }
  25180. for (index = 0; index < scene.materials.length; index++) {
  25181. material = scene.materials[index];
  25182. if (material instanceof BABYLON.StandardMaterial) {
  25183. serializationObject.materials.push(serializeMaterial(material));
  25184. }
  25185. else if (material instanceof BABYLON.MultiMaterial) {
  25186. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  25187. }
  25188. }
  25189. // Skeletons
  25190. serializationObject.skeletons = [];
  25191. for (index = 0; index < scene.skeletons.length; index++) {
  25192. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  25193. }
  25194. // Geometries
  25195. serializationObject.geometries = {};
  25196. serializationObject.geometries.boxes = [];
  25197. serializationObject.geometries.spheres = [];
  25198. serializationObject.geometries.cylinders = [];
  25199. serializationObject.geometries.toruses = [];
  25200. serializationObject.geometries.grounds = [];
  25201. serializationObject.geometries.planes = [];
  25202. serializationObject.geometries.torusKnots = [];
  25203. serializationObject.geometries.vertexData = [];
  25204. serializedGeometries = [];
  25205. var geometries = scene.getGeometries();
  25206. for (index = 0; index < geometries.length; index++) {
  25207. var geometry = geometries[index];
  25208. if (geometry.isReady()) {
  25209. serializeGeometry(geometry, serializationObject.geometries);
  25210. }
  25211. }
  25212. // Meshes
  25213. serializationObject.meshes = [];
  25214. for (index = 0; index < scene.meshes.length; index++) {
  25215. var abstractMesh = scene.meshes[index];
  25216. if (abstractMesh instanceof BABYLON.Mesh) {
  25217. var mesh = abstractMesh;
  25218. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  25219. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  25220. }
  25221. }
  25222. }
  25223. // Particles Systems
  25224. serializationObject.particleSystems = [];
  25225. for (index = 0; index < scene.particleSystems.length; index++) {
  25226. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  25227. }
  25228. // Lens flares
  25229. serializationObject.lensFlareSystems = [];
  25230. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  25231. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  25232. }
  25233. // Shadows
  25234. serializationObject.shadowGenerators = [];
  25235. for (index = 0; index < scene.lights.length; index++) {
  25236. light = scene.lights[index];
  25237. if (light.getShadowGenerator()) {
  25238. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  25239. }
  25240. }
  25241. return serializationObject;
  25242. };
  25243. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  25244. if (withParents === void 0) { withParents = false; }
  25245. if (withChildren === void 0) { withChildren = false; }
  25246. var serializationObject = {};
  25247. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  25248. if (withParents || withChildren) {
  25249. //deliberate for loop! not for each, appended should be processed as well.
  25250. for (var i = 0; i < toSerialize.length; ++i) {
  25251. if (withChildren) {
  25252. toSerialize[i].getDescendants().forEach(function (node) {
  25253. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  25254. toSerialize.push(node);
  25255. }
  25256. });
  25257. }
  25258. //make sure the array doesn't contain the object already
  25259. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  25260. toSerialize.push(toSerialize[i].parent);
  25261. }
  25262. }
  25263. }
  25264. toSerialize.forEach(function (mesh) {
  25265. finalizeSingleMesh(mesh, serializationObject);
  25266. });
  25267. return serializationObject;
  25268. };
  25269. return SceneSerializer;
  25270. })();
  25271. BABYLON.SceneSerializer = SceneSerializer;
  25272. })(BABYLON || (BABYLON = {}));
  25273. var BABYLON;
  25274. (function (BABYLON) {
  25275. // Unique ID when we import meshes from Babylon to CSG
  25276. var currentCSGMeshId = 0;
  25277. // # class Vertex
  25278. // Represents a vertex of a polygon. Use your own vertex class instead of this
  25279. // one to provide additional features like texture coordinates and vertex
  25280. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  25281. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  25282. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  25283. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  25284. // is not used anywhere else.
  25285. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  25286. var Vertex = (function () {
  25287. function Vertex(pos, normal, uv) {
  25288. this.pos = pos;
  25289. this.normal = normal;
  25290. this.uv = uv;
  25291. }
  25292. Vertex.prototype.clone = function () {
  25293. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  25294. };
  25295. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  25296. // orientation of a polygon is flipped.
  25297. Vertex.prototype.flip = function () {
  25298. this.normal = this.normal.scale(-1);
  25299. };
  25300. // Create a new vertex between this vertex and `other` by linearly
  25301. // interpolating all properties using a parameter of `t`. Subclasses should
  25302. // override this to interpolate additional properties.
  25303. Vertex.prototype.interpolate = function (other, t) {
  25304. 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));
  25305. };
  25306. return Vertex;
  25307. })();
  25308. // # class Plane
  25309. // Represents a plane in 3D space.
  25310. var Plane = (function () {
  25311. function Plane(normal, w) {
  25312. this.normal = normal;
  25313. this.w = w;
  25314. }
  25315. Plane.FromPoints = function (a, b, c) {
  25316. var v0 = c.subtract(a);
  25317. var v1 = b.subtract(a);
  25318. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  25319. return null;
  25320. }
  25321. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  25322. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  25323. };
  25324. Plane.prototype.clone = function () {
  25325. return new Plane(this.normal.clone(), this.w);
  25326. };
  25327. Plane.prototype.flip = function () {
  25328. this.normal.scaleInPlace(-1);
  25329. this.w = -this.w;
  25330. };
  25331. // Split `polygon` by this plane if needed, then put the polygon or polygon
  25332. // fragments in the appropriate lists. Coplanar polygons go into either
  25333. // `coplanarFront` or `coplanarBack` depending on their orientation with
  25334. // respect to this plane. Polygons in front or in back of this plane go into
  25335. // either `front` or `back`.
  25336. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  25337. var COPLANAR = 0;
  25338. var FRONT = 1;
  25339. var BACK = 2;
  25340. var SPANNING = 3;
  25341. // Classify each point as well as the entire polygon into one of the above
  25342. // four classes.
  25343. var polygonType = 0;
  25344. var types = [];
  25345. for (var i = 0; i < polygon.vertices.length; i++) {
  25346. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  25347. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  25348. polygonType |= type;
  25349. types.push(type);
  25350. }
  25351. // Put the polygon in the correct list, splitting it when necessary.
  25352. switch (polygonType) {
  25353. case COPLANAR:
  25354. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  25355. break;
  25356. case FRONT:
  25357. front.push(polygon);
  25358. break;
  25359. case BACK:
  25360. back.push(polygon);
  25361. break;
  25362. case SPANNING:
  25363. var f = [], b = [];
  25364. for (i = 0; i < polygon.vertices.length; i++) {
  25365. var j = (i + 1) % polygon.vertices.length;
  25366. var ti = types[i], tj = types[j];
  25367. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  25368. if (ti != BACK)
  25369. f.push(vi);
  25370. if (ti != FRONT)
  25371. b.push(ti != BACK ? vi.clone() : vi);
  25372. if ((ti | tj) == SPANNING) {
  25373. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  25374. var v = vi.interpolate(vj, t);
  25375. f.push(v);
  25376. b.push(v.clone());
  25377. }
  25378. }
  25379. if (f.length >= 3) {
  25380. var poly = new Polygon(f, polygon.shared);
  25381. if (poly.plane)
  25382. front.push(poly);
  25383. }
  25384. if (b.length >= 3) {
  25385. poly = new Polygon(b, polygon.shared);
  25386. if (poly.plane)
  25387. back.push(poly);
  25388. }
  25389. break;
  25390. }
  25391. };
  25392. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  25393. // point is on the plane.
  25394. Plane.EPSILON = 1e-5;
  25395. return Plane;
  25396. })();
  25397. // # class Polygon
  25398. // Represents a convex polygon. The vertices used to initialize a polygon must
  25399. // be coplanar and form a convex loop.
  25400. //
  25401. // Each convex polygon has a `shared` property, which is shared between all
  25402. // polygons that are clones of each other or were split from the same polygon.
  25403. // This can be used to define per-polygon properties (such as surface color).
  25404. var Polygon = (function () {
  25405. function Polygon(vertices, shared) {
  25406. this.vertices = vertices;
  25407. this.shared = shared;
  25408. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  25409. }
  25410. Polygon.prototype.clone = function () {
  25411. var vertices = this.vertices.map(function (v) { return v.clone(); });
  25412. return new Polygon(vertices, this.shared);
  25413. };
  25414. Polygon.prototype.flip = function () {
  25415. this.vertices.reverse().map(function (v) { v.flip(); });
  25416. this.plane.flip();
  25417. };
  25418. return Polygon;
  25419. })();
  25420. // # class Node
  25421. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  25422. // by picking a polygon to split along. That polygon (and all other coplanar
  25423. // polygons) are added directly to that node and the other polygons are added to
  25424. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  25425. // no distinction between internal and leaf nodes.
  25426. var Node = (function () {
  25427. function Node(polygons) {
  25428. this.plane = null;
  25429. this.front = null;
  25430. this.back = null;
  25431. this.polygons = [];
  25432. if (polygons) {
  25433. this.build(polygons);
  25434. }
  25435. }
  25436. Node.prototype.clone = function () {
  25437. var node = new Node();
  25438. node.plane = this.plane && this.plane.clone();
  25439. node.front = this.front && this.front.clone();
  25440. node.back = this.back && this.back.clone();
  25441. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  25442. return node;
  25443. };
  25444. // Convert solid space to empty space and empty space to solid space.
  25445. Node.prototype.invert = function () {
  25446. for (var i = 0; i < this.polygons.length; i++) {
  25447. this.polygons[i].flip();
  25448. }
  25449. if (this.plane) {
  25450. this.plane.flip();
  25451. }
  25452. if (this.front) {
  25453. this.front.invert();
  25454. }
  25455. if (this.back) {
  25456. this.back.invert();
  25457. }
  25458. var temp = this.front;
  25459. this.front = this.back;
  25460. this.back = temp;
  25461. };
  25462. // Recursively remove all polygons in `polygons` that are inside this BSP
  25463. // tree.
  25464. Node.prototype.clipPolygons = function (polygons) {
  25465. if (!this.plane)
  25466. return polygons.slice();
  25467. var front = [], back = [];
  25468. for (var i = 0; i < polygons.length; i++) {
  25469. this.plane.splitPolygon(polygons[i], front, back, front, back);
  25470. }
  25471. if (this.front) {
  25472. front = this.front.clipPolygons(front);
  25473. }
  25474. if (this.back) {
  25475. back = this.back.clipPolygons(back);
  25476. }
  25477. else {
  25478. back = [];
  25479. }
  25480. return front.concat(back);
  25481. };
  25482. // Remove all polygons in this BSP tree that are inside the other BSP tree
  25483. // `bsp`.
  25484. Node.prototype.clipTo = function (bsp) {
  25485. this.polygons = bsp.clipPolygons(this.polygons);
  25486. if (this.front)
  25487. this.front.clipTo(bsp);
  25488. if (this.back)
  25489. this.back.clipTo(bsp);
  25490. };
  25491. // Return a list of all polygons in this BSP tree.
  25492. Node.prototype.allPolygons = function () {
  25493. var polygons = this.polygons.slice();
  25494. if (this.front)
  25495. polygons = polygons.concat(this.front.allPolygons());
  25496. if (this.back)
  25497. polygons = polygons.concat(this.back.allPolygons());
  25498. return polygons;
  25499. };
  25500. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  25501. // new polygons are filtered down to the bottom of the tree and become new
  25502. // nodes there. Each set of polygons is partitioned using the first polygon
  25503. // (no heuristic is used to pick a good split).
  25504. Node.prototype.build = function (polygons) {
  25505. if (!polygons.length)
  25506. return;
  25507. if (!this.plane)
  25508. this.plane = polygons[0].plane.clone();
  25509. var front = [], back = [];
  25510. for (var i = 0; i < polygons.length; i++) {
  25511. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  25512. }
  25513. if (front.length) {
  25514. if (!this.front)
  25515. this.front = new Node();
  25516. this.front.build(front);
  25517. }
  25518. if (back.length) {
  25519. if (!this.back)
  25520. this.back = new Node();
  25521. this.back.build(back);
  25522. }
  25523. };
  25524. return Node;
  25525. })();
  25526. var CSG = (function () {
  25527. function CSG() {
  25528. this.polygons = new Array();
  25529. }
  25530. // Convert BABYLON.Mesh to BABYLON.CSG
  25531. CSG.FromMesh = function (mesh) {
  25532. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  25533. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  25534. if (mesh instanceof BABYLON.Mesh) {
  25535. mesh.computeWorldMatrix(true);
  25536. matrix = mesh.getWorldMatrix();
  25537. meshPosition = mesh.position.clone();
  25538. meshRotation = mesh.rotation.clone();
  25539. if (mesh.rotationQuaternion) {
  25540. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  25541. }
  25542. meshScaling = mesh.scaling.clone();
  25543. }
  25544. else {
  25545. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  25546. }
  25547. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25548. var subMeshes = mesh.subMeshes;
  25549. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  25550. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  25551. vertices = [];
  25552. for (var j = 0; j < 3; j++) {
  25553. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  25554. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  25555. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  25556. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  25557. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  25558. vertex = new Vertex(position, normal, uv);
  25559. vertices.push(vertex);
  25560. }
  25561. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  25562. // To handle the case of degenerated triangle
  25563. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  25564. if (polygon.plane)
  25565. polygons.push(polygon);
  25566. }
  25567. }
  25568. var csg = CSG.FromPolygons(polygons);
  25569. csg.matrix = matrix;
  25570. csg.position = meshPosition;
  25571. csg.rotation = meshRotation;
  25572. csg.scaling = meshScaling;
  25573. csg.rotationQuaternion = meshRotationQuaternion;
  25574. currentCSGMeshId++;
  25575. return csg;
  25576. };
  25577. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  25578. CSG.FromPolygons = function (polygons) {
  25579. var csg = new CSG();
  25580. csg.polygons = polygons;
  25581. return csg;
  25582. };
  25583. CSG.prototype.clone = function () {
  25584. var csg = new CSG();
  25585. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  25586. csg.copyTransformAttributes(this);
  25587. return csg;
  25588. };
  25589. CSG.prototype.toPolygons = function () {
  25590. return this.polygons;
  25591. };
  25592. CSG.prototype.union = function (csg) {
  25593. var a = new Node(this.clone().polygons);
  25594. var b = new Node(csg.clone().polygons);
  25595. a.clipTo(b);
  25596. b.clipTo(a);
  25597. b.invert();
  25598. b.clipTo(a);
  25599. b.invert();
  25600. a.build(b.allPolygons());
  25601. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25602. };
  25603. CSG.prototype.unionInPlace = function (csg) {
  25604. var a = new Node(this.polygons);
  25605. var b = new Node(csg.polygons);
  25606. a.clipTo(b);
  25607. b.clipTo(a);
  25608. b.invert();
  25609. b.clipTo(a);
  25610. b.invert();
  25611. a.build(b.allPolygons());
  25612. this.polygons = a.allPolygons();
  25613. };
  25614. CSG.prototype.subtract = function (csg) {
  25615. var a = new Node(this.clone().polygons);
  25616. var b = new Node(csg.clone().polygons);
  25617. a.invert();
  25618. a.clipTo(b);
  25619. b.clipTo(a);
  25620. b.invert();
  25621. b.clipTo(a);
  25622. b.invert();
  25623. a.build(b.allPolygons());
  25624. a.invert();
  25625. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25626. };
  25627. CSG.prototype.subtractInPlace = function (csg) {
  25628. var a = new Node(this.polygons);
  25629. var b = new Node(csg.polygons);
  25630. a.invert();
  25631. a.clipTo(b);
  25632. b.clipTo(a);
  25633. b.invert();
  25634. b.clipTo(a);
  25635. b.invert();
  25636. a.build(b.allPolygons());
  25637. a.invert();
  25638. this.polygons = a.allPolygons();
  25639. };
  25640. CSG.prototype.intersect = function (csg) {
  25641. var a = new Node(this.clone().polygons);
  25642. var b = new Node(csg.clone().polygons);
  25643. a.invert();
  25644. b.clipTo(a);
  25645. b.invert();
  25646. a.clipTo(b);
  25647. b.clipTo(a);
  25648. a.build(b.allPolygons());
  25649. a.invert();
  25650. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25651. };
  25652. CSG.prototype.intersectInPlace = function (csg) {
  25653. var a = new Node(this.polygons);
  25654. var b = new Node(csg.polygons);
  25655. a.invert();
  25656. b.clipTo(a);
  25657. b.invert();
  25658. a.clipTo(b);
  25659. b.clipTo(a);
  25660. a.build(b.allPolygons());
  25661. a.invert();
  25662. this.polygons = a.allPolygons();
  25663. };
  25664. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25665. // not modified.
  25666. CSG.prototype.inverse = function () {
  25667. var csg = this.clone();
  25668. csg.inverseInPlace();
  25669. return csg;
  25670. };
  25671. CSG.prototype.inverseInPlace = function () {
  25672. this.polygons.map(function (p) { p.flip(); });
  25673. };
  25674. // This is used to keep meshes transformations so they can be restored
  25675. // when we build back a Babylon Mesh
  25676. // NB : All CSG operations are performed in world coordinates
  25677. CSG.prototype.copyTransformAttributes = function (csg) {
  25678. this.matrix = csg.matrix;
  25679. this.position = csg.position;
  25680. this.rotation = csg.rotation;
  25681. this.scaling = csg.scaling;
  25682. this.rotationQuaternion = csg.rotationQuaternion;
  25683. return this;
  25684. };
  25685. // Build Raw mesh from CSG
  25686. // Coordinates here are in world space
  25687. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25688. var matrix = this.matrix.clone();
  25689. matrix.invert();
  25690. 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;
  25691. if (keepSubMeshes) {
  25692. // Sort Polygons, since subMeshes are indices range
  25693. polygons.sort(function (a, b) {
  25694. if (a.shared.meshId === b.shared.meshId) {
  25695. return a.shared.subMeshId - b.shared.subMeshId;
  25696. }
  25697. else {
  25698. return a.shared.meshId - b.shared.meshId;
  25699. }
  25700. });
  25701. }
  25702. for (var i = 0, il = polygons.length; i < il; i++) {
  25703. polygon = polygons[i];
  25704. // Building SubMeshes
  25705. if (!subMesh_dict[polygon.shared.meshId]) {
  25706. subMesh_dict[polygon.shared.meshId] = {};
  25707. }
  25708. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25709. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25710. indexStart: +Infinity,
  25711. indexEnd: -Infinity,
  25712. materialIndex: polygon.shared.materialIndex
  25713. };
  25714. }
  25715. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25716. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25717. polygonIndices[0] = 0;
  25718. polygonIndices[1] = j - 1;
  25719. polygonIndices[2] = j;
  25720. for (var k = 0; k < 3; k++) {
  25721. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25722. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25723. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25724. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25725. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25726. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25727. // Check if 2 points can be merged
  25728. if (!(typeof vertex_idx !== 'undefined' &&
  25729. normals[vertex_idx * 3] === localNormal.x &&
  25730. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25731. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25732. uvs[vertex_idx * 2] === uv.x &&
  25733. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25734. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25735. uvs.push(uv.x, uv.y);
  25736. normals.push(normal.x, normal.y, normal.z);
  25737. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25738. }
  25739. indices.push(vertex_idx);
  25740. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25741. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25742. currentIndex++;
  25743. }
  25744. }
  25745. }
  25746. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25747. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25748. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25749. mesh.setIndices(indices);
  25750. if (keepSubMeshes) {
  25751. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25752. var materialIndexOffset = 0, materialMaxIndex;
  25753. mesh.subMeshes.length = 0;
  25754. for (var m in subMesh_dict) {
  25755. materialMaxIndex = -1;
  25756. for (var sm in subMesh_dict[m]) {
  25757. subMesh_obj = subMesh_dict[m][sm];
  25758. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25759. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25760. }
  25761. materialIndexOffset += ++materialMaxIndex;
  25762. }
  25763. }
  25764. return mesh;
  25765. };
  25766. // Build Mesh from CSG taking material and transforms into account
  25767. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25768. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25769. mesh.material = material;
  25770. mesh.position.copyFrom(this.position);
  25771. mesh.rotation.copyFrom(this.rotation);
  25772. if (this.rotationQuaternion) {
  25773. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25774. }
  25775. mesh.scaling.copyFrom(this.scaling);
  25776. mesh.computeWorldMatrix(true);
  25777. return mesh;
  25778. };
  25779. return CSG;
  25780. })();
  25781. BABYLON.CSG = CSG;
  25782. })(BABYLON || (BABYLON = {}));
  25783. var BABYLON;
  25784. (function (BABYLON) {
  25785. var VRDistortionCorrectionPostProcess = (function (_super) {
  25786. __extends(VRDistortionCorrectionPostProcess, _super);
  25787. //ANY
  25788. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25789. var _this = this;
  25790. _super.call(this, name, "vrDistortionCorrection", [
  25791. 'LensCenter',
  25792. 'Scale',
  25793. 'ScaleIn',
  25794. 'HmdWarpParam'
  25795. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25796. this._isRightEye = isRightEye;
  25797. this._distortionFactors = vrMetrics.distortionK;
  25798. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25799. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25800. this.onSizeChanged = function () {
  25801. _this.aspectRatio = _this.width * .5 / _this.height;
  25802. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25803. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25804. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25805. };
  25806. this.onApply = function (effect) {
  25807. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25808. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25809. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25810. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25811. };
  25812. }
  25813. return VRDistortionCorrectionPostProcess;
  25814. })(BABYLON.PostProcess);
  25815. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25816. })(BABYLON || (BABYLON = {}));
  25817. // Mainly based on these 2 articles :
  25818. // 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
  25819. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25820. var BABYLON;
  25821. (function (BABYLON) {
  25822. (function (JoystickAxis) {
  25823. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25824. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25825. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25826. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25827. var JoystickAxis = BABYLON.JoystickAxis;
  25828. var VirtualJoystick = (function () {
  25829. function VirtualJoystick(leftJoystick) {
  25830. var _this = this;
  25831. if (leftJoystick) {
  25832. this._leftJoystick = true;
  25833. }
  25834. else {
  25835. this._leftJoystick = false;
  25836. }
  25837. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25838. VirtualJoystick._globalJoystickIndex++;
  25839. // By default left & right arrow keys are moving the X
  25840. // and up & down keys are moving the Y
  25841. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25842. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25843. this.reverseLeftRight = false;
  25844. this.reverseUpDown = false;
  25845. // collections of pointers
  25846. this._touches = new BABYLON.SmartCollection();
  25847. this.deltaPosition = BABYLON.Vector3.Zero();
  25848. this._joystickSensibility = 25;
  25849. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25850. this._rotationSpeed = 25;
  25851. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25852. this._rotateOnAxisRelativeToMesh = false;
  25853. this._onResize = function (evt) {
  25854. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25855. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25856. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25857. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25858. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25859. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25860. };
  25861. // injecting a canvas element on top of the canvas 3D game
  25862. if (!VirtualJoystick.vjCanvas) {
  25863. window.addEventListener("resize", this._onResize, false);
  25864. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25865. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25866. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25867. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25868. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25869. VirtualJoystick.vjCanvas.style.width = "100%";
  25870. VirtualJoystick.vjCanvas.style.height = "100%";
  25871. VirtualJoystick.vjCanvas.style.position = "absolute";
  25872. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25873. VirtualJoystick.vjCanvas.style.top = "0px";
  25874. VirtualJoystick.vjCanvas.style.left = "0px";
  25875. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25876. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25877. // Support for jQuery PEP polyfill
  25878. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  25879. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25880. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25881. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25882. document.body.appendChild(VirtualJoystick.vjCanvas);
  25883. }
  25884. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25885. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25886. this.pressed = false;
  25887. // default joystick color
  25888. this._joystickColor = "cyan";
  25889. this._joystickPointerID = -1;
  25890. // current joystick position
  25891. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25892. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25893. // origin joystick position
  25894. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25895. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25896. this._onPointerDownHandlerRef = function (evt) {
  25897. _this._onPointerDown(evt);
  25898. };
  25899. this._onPointerMoveHandlerRef = function (evt) {
  25900. _this._onPointerMove(evt);
  25901. };
  25902. this._onPointerOutHandlerRef = function (evt) {
  25903. _this._onPointerUp(evt);
  25904. };
  25905. this._onPointerUpHandlerRef = function (evt) {
  25906. _this._onPointerUp(evt);
  25907. };
  25908. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25909. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25910. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25911. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25912. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25913. evt.preventDefault(); // Disables system menu
  25914. }, false);
  25915. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25916. }
  25917. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25918. this._joystickSensibility = newJoystickSensibility;
  25919. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25920. };
  25921. VirtualJoystick.prototype._onPointerDown = function (e) {
  25922. var positionOnScreenCondition;
  25923. e.preventDefault();
  25924. if (this._leftJoystick === true) {
  25925. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25926. }
  25927. else {
  25928. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25929. }
  25930. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25931. // First contact will be dedicated to the virtual joystick
  25932. this._joystickPointerID = e.pointerId;
  25933. this._joystickPointerStartPos.x = e.clientX;
  25934. this._joystickPointerStartPos.y = e.clientY;
  25935. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25936. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25937. this._deltaJoystickVector.x = 0;
  25938. this._deltaJoystickVector.y = 0;
  25939. this.pressed = true;
  25940. this._touches.add(e.pointerId.toString(), e);
  25941. }
  25942. else {
  25943. // You can only trigger the action buttons with a joystick declared
  25944. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25945. this._action();
  25946. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25947. }
  25948. }
  25949. };
  25950. VirtualJoystick.prototype._onPointerMove = function (e) {
  25951. // If the current pointer is the one associated to the joystick (first touch contact)
  25952. if (this._joystickPointerID == e.pointerId) {
  25953. this._joystickPointerPos.x = e.clientX;
  25954. this._joystickPointerPos.y = e.clientY;
  25955. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25956. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25957. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25958. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25959. switch (this._axisTargetedByLeftAndRight) {
  25960. case JoystickAxis.X:
  25961. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25962. break;
  25963. case JoystickAxis.Y:
  25964. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25965. break;
  25966. case JoystickAxis.Z:
  25967. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25968. break;
  25969. }
  25970. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25971. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25972. switch (this._axisTargetedByUpAndDown) {
  25973. case JoystickAxis.X:
  25974. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25975. break;
  25976. case JoystickAxis.Y:
  25977. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25978. break;
  25979. case JoystickAxis.Z:
  25980. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25981. break;
  25982. }
  25983. }
  25984. else {
  25985. if (this._touches.item(e.pointerId.toString())) {
  25986. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25987. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25988. }
  25989. }
  25990. };
  25991. VirtualJoystick.prototype._onPointerUp = function (e) {
  25992. if (this._joystickPointerID == e.pointerId) {
  25993. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25994. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25995. this._joystickPointerID = -1;
  25996. this.pressed = false;
  25997. }
  25998. else {
  25999. var touch = this._touches.item(e.pointerId.toString());
  26000. if (touch) {
  26001. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  26002. }
  26003. }
  26004. this._deltaJoystickVector.x = 0;
  26005. this._deltaJoystickVector.y = 0;
  26006. this._touches.remove(e.pointerId.toString());
  26007. };
  26008. /**
  26009. * Change the color of the virtual joystick
  26010. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  26011. */
  26012. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  26013. this._joystickColor = newColor;
  26014. };
  26015. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  26016. this._action = action;
  26017. };
  26018. // Define which axis you'd like to control for left & right
  26019. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  26020. switch (axis) {
  26021. case JoystickAxis.X:
  26022. case JoystickAxis.Y:
  26023. case JoystickAxis.Z:
  26024. this._axisTargetedByLeftAndRight = axis;
  26025. break;
  26026. default:
  26027. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  26028. break;
  26029. }
  26030. };
  26031. // Define which axis you'd like to control for up & down
  26032. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  26033. switch (axis) {
  26034. case JoystickAxis.X:
  26035. case JoystickAxis.Y:
  26036. case JoystickAxis.Z:
  26037. this._axisTargetedByUpAndDown = axis;
  26038. break;
  26039. default:
  26040. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  26041. break;
  26042. }
  26043. };
  26044. VirtualJoystick.prototype._clearCanvas = function () {
  26045. if (this._leftJoystick) {
  26046. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  26047. }
  26048. else {
  26049. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  26050. }
  26051. };
  26052. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  26053. var _this = this;
  26054. if (this.pressed) {
  26055. this._touches.forEach(function (touch) {
  26056. if (touch.pointerId === _this._joystickPointerID) {
  26057. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  26058. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  26059. VirtualJoystick.vjCanvasContext.beginPath();
  26060. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26061. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26062. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  26063. VirtualJoystick.vjCanvasContext.stroke();
  26064. VirtualJoystick.vjCanvasContext.closePath();
  26065. VirtualJoystick.vjCanvasContext.beginPath();
  26066. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26067. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  26068. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  26069. VirtualJoystick.vjCanvasContext.stroke();
  26070. VirtualJoystick.vjCanvasContext.closePath();
  26071. VirtualJoystick.vjCanvasContext.beginPath();
  26072. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  26073. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  26074. VirtualJoystick.vjCanvasContext.stroke();
  26075. VirtualJoystick.vjCanvasContext.closePath();
  26076. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  26077. }
  26078. else {
  26079. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  26080. VirtualJoystick.vjCanvasContext.beginPath();
  26081. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  26082. VirtualJoystick.vjCanvasContext.beginPath();
  26083. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  26084. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  26085. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  26086. VirtualJoystick.vjCanvasContext.stroke();
  26087. VirtualJoystick.vjCanvasContext.closePath();
  26088. touch.prevX = touch.x;
  26089. touch.prevY = touch.y;
  26090. }
  26091. ;
  26092. });
  26093. }
  26094. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  26095. };
  26096. VirtualJoystick.prototype.releaseCanvas = function () {
  26097. if (VirtualJoystick.vjCanvas) {
  26098. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  26099. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  26100. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  26101. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  26102. window.removeEventListener("resize", this._onResize);
  26103. document.body.removeChild(VirtualJoystick.vjCanvas);
  26104. VirtualJoystick.vjCanvas = null;
  26105. }
  26106. };
  26107. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  26108. VirtualJoystick._globalJoystickIndex = 0;
  26109. return VirtualJoystick;
  26110. })();
  26111. BABYLON.VirtualJoystick = VirtualJoystick;
  26112. })(BABYLON || (BABYLON = {}));
  26113. var BABYLON;
  26114. (function (BABYLON) {
  26115. // We're mainly based on the logic defined into the FreeCamera code
  26116. var VirtualJoysticksCamera = (function (_super) {
  26117. __extends(VirtualJoysticksCamera, _super);
  26118. function VirtualJoysticksCamera(name, position, scene) {
  26119. _super.call(this, name, position, scene);
  26120. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  26121. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  26122. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  26123. this._leftjoystick.setJoystickSensibility(0.15);
  26124. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  26125. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  26126. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  26127. this._rightjoystick.reverseUpDown = true;
  26128. this._rightjoystick.setJoystickSensibility(0.05);
  26129. this._rightjoystick.setJoystickColor("yellow");
  26130. }
  26131. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  26132. return this._leftjoystick;
  26133. };
  26134. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  26135. return this._rightjoystick;
  26136. };
  26137. VirtualJoysticksCamera.prototype._checkInputs = function () {
  26138. var speed = this._computeLocalCameraSpeed() * 50;
  26139. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26140. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  26141. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26142. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  26143. if (!this._leftjoystick.pressed) {
  26144. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  26145. }
  26146. if (!this._rightjoystick.pressed) {
  26147. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  26148. }
  26149. _super.prototype._checkInputs.call(this);
  26150. };
  26151. VirtualJoysticksCamera.prototype.dispose = function () {
  26152. this._leftjoystick.releaseCanvas();
  26153. _super.prototype.dispose.call(this);
  26154. };
  26155. return VirtualJoysticksCamera;
  26156. })(BABYLON.FreeCamera);
  26157. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  26158. })(BABYLON || (BABYLON = {}));
  26159. var BABYLON;
  26160. (function (BABYLON) {
  26161. var ShaderMaterial = (function (_super) {
  26162. __extends(ShaderMaterial, _super);
  26163. function ShaderMaterial(name, scene, shaderPath, options) {
  26164. _super.call(this, name, scene);
  26165. this._textures = new Array();
  26166. this._floats = new Array();
  26167. this._floatsArrays = {};
  26168. this._colors3 = new Array();
  26169. this._colors4 = new Array();
  26170. this._vectors2 = new Array();
  26171. this._vectors3 = new Array();
  26172. this._vectors4 = new Array();
  26173. this._matrices = new Array();
  26174. this._matrices3x3 = new Array();
  26175. this._matrices2x2 = new Array();
  26176. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  26177. this._shaderPath = shaderPath;
  26178. options.needAlphaBlending = options.needAlphaBlending || false;
  26179. options.needAlphaTesting = options.needAlphaTesting || false;
  26180. options.attributes = options.attributes || ["position", "normal", "uv"];
  26181. options.uniforms = options.uniforms || ["worldViewProjection"];
  26182. options.samplers = options.samplers || [];
  26183. options.defines = options.defines || [];
  26184. this._options = options;
  26185. }
  26186. ShaderMaterial.prototype.needAlphaBlending = function () {
  26187. return this._options.needAlphaBlending;
  26188. };
  26189. ShaderMaterial.prototype.needAlphaTesting = function () {
  26190. return this._options.needAlphaTesting;
  26191. };
  26192. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  26193. if (this._options.uniforms.indexOf(uniformName) === -1) {
  26194. this._options.uniforms.push(uniformName);
  26195. }
  26196. };
  26197. ShaderMaterial.prototype.setTexture = function (name, texture) {
  26198. if (this._options.samplers.indexOf(name) === -1) {
  26199. this._options.samplers.push(name);
  26200. }
  26201. this._textures[name] = texture;
  26202. return this;
  26203. };
  26204. ShaderMaterial.prototype.setFloat = function (name, value) {
  26205. this._checkUniform(name);
  26206. this._floats[name] = value;
  26207. return this;
  26208. };
  26209. ShaderMaterial.prototype.setFloats = function (name, value) {
  26210. this._checkUniform(name);
  26211. this._floatsArrays[name] = value;
  26212. return this;
  26213. };
  26214. ShaderMaterial.prototype.setColor3 = function (name, value) {
  26215. this._checkUniform(name);
  26216. this._colors3[name] = value;
  26217. return this;
  26218. };
  26219. ShaderMaterial.prototype.setColor4 = function (name, value) {
  26220. this._checkUniform(name);
  26221. this._colors4[name] = value;
  26222. return this;
  26223. };
  26224. ShaderMaterial.prototype.setVector2 = function (name, value) {
  26225. this._checkUniform(name);
  26226. this._vectors2[name] = value;
  26227. return this;
  26228. };
  26229. ShaderMaterial.prototype.setVector3 = function (name, value) {
  26230. this._checkUniform(name);
  26231. this._vectors3[name] = value;
  26232. return this;
  26233. };
  26234. ShaderMaterial.prototype.setVector4 = function (name, value) {
  26235. this._checkUniform(name);
  26236. this._vectors4[name] = value;
  26237. return this;
  26238. };
  26239. ShaderMaterial.prototype.setMatrix = function (name, value) {
  26240. this._checkUniform(name);
  26241. this._matrices[name] = value;
  26242. return this;
  26243. };
  26244. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  26245. this._checkUniform(name);
  26246. this._matrices3x3[name] = value;
  26247. return this;
  26248. };
  26249. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  26250. this._checkUniform(name);
  26251. this._matrices2x2[name] = value;
  26252. return this;
  26253. };
  26254. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  26255. var scene = this.getScene();
  26256. var engine = scene.getEngine();
  26257. if (!this.checkReadyOnEveryCall) {
  26258. if (this._renderId === scene.getRenderId()) {
  26259. return true;
  26260. }
  26261. }
  26262. // Instances
  26263. var defines = [];
  26264. var fallbacks = new BABYLON.EffectFallbacks();
  26265. if (useInstances) {
  26266. defines.push("#define INSTANCES");
  26267. }
  26268. for (var index = 0; index < this._options.defines.length; index++) {
  26269. defines.push(this._options.defines[index]);
  26270. }
  26271. // Bones
  26272. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26273. defines.push("#define BONES");
  26274. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26275. defines.push("#define BONES4");
  26276. fallbacks.addFallback(0, "BONES4");
  26277. }
  26278. // Alpha test
  26279. if (engine.getAlphaTesting()) {
  26280. defines.push("#define ALPHATEST");
  26281. }
  26282. var previousEffect = this._effect;
  26283. var join = defines.join("\n");
  26284. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  26285. if (!this._effect.isReady()) {
  26286. return false;
  26287. }
  26288. if (previousEffect !== this._effect) {
  26289. scene.resetCachedMaterial();
  26290. }
  26291. this._renderId = scene.getRenderId();
  26292. return true;
  26293. };
  26294. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26295. var scene = this.getScene();
  26296. if (this._options.uniforms.indexOf("world") !== -1) {
  26297. this._effect.setMatrix("world", world);
  26298. }
  26299. if (this._options.uniforms.indexOf("worldView") !== -1) {
  26300. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  26301. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  26302. }
  26303. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  26304. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  26305. }
  26306. };
  26307. ShaderMaterial.prototype.bind = function (world, mesh) {
  26308. // Std values
  26309. this.bindOnlyWorldMatrix(world);
  26310. if (this.getScene().getCachedMaterial() !== this) {
  26311. if (this._options.uniforms.indexOf("view") !== -1) {
  26312. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  26313. }
  26314. if (this._options.uniforms.indexOf("projection") !== -1) {
  26315. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  26316. }
  26317. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  26318. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26319. }
  26320. // Bones
  26321. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26322. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26323. }
  26324. // Texture
  26325. for (var name in this._textures) {
  26326. this._effect.setTexture(name, this._textures[name]);
  26327. }
  26328. // Float
  26329. for (name in this._floats) {
  26330. this._effect.setFloat(name, this._floats[name]);
  26331. }
  26332. // Float s
  26333. for (name in this._floatsArrays) {
  26334. this._effect.setArray(name, this._floatsArrays[name]);
  26335. }
  26336. // Color3
  26337. for (name in this._colors3) {
  26338. this._effect.setColor3(name, this._colors3[name]);
  26339. }
  26340. // Color4
  26341. for (name in this._colors4) {
  26342. var color = this._colors4[name];
  26343. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  26344. }
  26345. // Vector2
  26346. for (name in this._vectors2) {
  26347. this._effect.setVector2(name, this._vectors2[name]);
  26348. }
  26349. // Vector3
  26350. for (name in this._vectors3) {
  26351. this._effect.setVector3(name, this._vectors3[name]);
  26352. }
  26353. // Vector4
  26354. for (name in this._vectors4) {
  26355. this._effect.setVector4(name, this._vectors4[name]);
  26356. }
  26357. // Matrix
  26358. for (name in this._matrices) {
  26359. this._effect.setMatrix(name, this._matrices[name]);
  26360. }
  26361. // Matrix 3x3
  26362. for (name in this._matrices3x3) {
  26363. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  26364. }
  26365. // Matrix 2x2
  26366. for (name in this._matrices2x2) {
  26367. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  26368. }
  26369. }
  26370. _super.prototype.bind.call(this, world, mesh);
  26371. };
  26372. ShaderMaterial.prototype.clone = function (name) {
  26373. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  26374. return newShaderMaterial;
  26375. };
  26376. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  26377. for (var name in this._textures) {
  26378. this._textures[name].dispose();
  26379. }
  26380. this._textures = [];
  26381. _super.prototype.dispose.call(this, forceDisposeEffect);
  26382. };
  26383. return ShaderMaterial;
  26384. })(BABYLON.Material);
  26385. BABYLON.ShaderMaterial = ShaderMaterial;
  26386. })(BABYLON || (BABYLON = {}));
  26387. var BABYLON;
  26388. (function (BABYLON) {
  26389. var VertexData = (function () {
  26390. function VertexData() {
  26391. }
  26392. VertexData.prototype.set = function (data, kind) {
  26393. switch (kind) {
  26394. case BABYLON.VertexBuffer.PositionKind:
  26395. this.positions = data;
  26396. break;
  26397. case BABYLON.VertexBuffer.NormalKind:
  26398. this.normals = data;
  26399. break;
  26400. case BABYLON.VertexBuffer.UVKind:
  26401. this.uvs = data;
  26402. break;
  26403. case BABYLON.VertexBuffer.UV2Kind:
  26404. this.uvs2 = data;
  26405. break;
  26406. case BABYLON.VertexBuffer.UV3Kind:
  26407. this.uvs3 = data;
  26408. break;
  26409. case BABYLON.VertexBuffer.UV4Kind:
  26410. this.uvs4 = data;
  26411. break;
  26412. case BABYLON.VertexBuffer.UV5Kind:
  26413. this.uvs5 = data;
  26414. break;
  26415. case BABYLON.VertexBuffer.UV6Kind:
  26416. this.uvs6 = data;
  26417. break;
  26418. case BABYLON.VertexBuffer.ColorKind:
  26419. this.colors = data;
  26420. break;
  26421. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26422. this.matricesIndices = data;
  26423. break;
  26424. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26425. this.matricesWeights = data;
  26426. break;
  26427. }
  26428. };
  26429. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26430. this._applyTo(mesh, updatable);
  26431. };
  26432. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26433. this._applyTo(geometry, updatable);
  26434. };
  26435. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26436. this._update(mesh);
  26437. };
  26438. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26439. this._update(geometry);
  26440. };
  26441. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26442. if (this.positions) {
  26443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26444. }
  26445. if (this.normals) {
  26446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26447. }
  26448. if (this.uvs) {
  26449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26450. }
  26451. if (this.uvs2) {
  26452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26453. }
  26454. if (this.uvs3) {
  26455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26456. }
  26457. if (this.uvs4) {
  26458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26459. }
  26460. if (this.uvs5) {
  26461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26462. }
  26463. if (this.uvs6) {
  26464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26465. }
  26466. if (this.colors) {
  26467. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26468. }
  26469. if (this.matricesIndices) {
  26470. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26471. }
  26472. if (this.matricesWeights) {
  26473. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26474. }
  26475. if (this.indices) {
  26476. meshOrGeometry.setIndices(this.indices);
  26477. }
  26478. };
  26479. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26480. if (this.positions) {
  26481. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26482. }
  26483. if (this.normals) {
  26484. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26485. }
  26486. if (this.uvs) {
  26487. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26488. }
  26489. if (this.uvs2) {
  26490. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26491. }
  26492. if (this.uvs3) {
  26493. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26494. }
  26495. if (this.uvs4) {
  26496. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26497. }
  26498. if (this.uvs5) {
  26499. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26500. }
  26501. if (this.uvs6) {
  26502. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26503. }
  26504. if (this.colors) {
  26505. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26506. }
  26507. if (this.matricesIndices) {
  26508. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26509. }
  26510. if (this.matricesWeights) {
  26511. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26512. }
  26513. if (this.indices) {
  26514. meshOrGeometry.setIndices(this.indices);
  26515. }
  26516. };
  26517. VertexData.prototype.transform = function (matrix) {
  26518. var transformed = BABYLON.Vector3.Zero();
  26519. var index;
  26520. if (this.positions) {
  26521. var position = BABYLON.Vector3.Zero();
  26522. for (index = 0; index < this.positions.length; index += 3) {
  26523. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26524. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26525. this.positions[index] = transformed.x;
  26526. this.positions[index + 1] = transformed.y;
  26527. this.positions[index + 2] = transformed.z;
  26528. }
  26529. }
  26530. if (this.normals) {
  26531. var normal = BABYLON.Vector3.Zero();
  26532. for (index = 0; index < this.normals.length; index += 3) {
  26533. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26534. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26535. this.normals[index] = transformed.x;
  26536. this.normals[index + 1] = transformed.y;
  26537. this.normals[index + 2] = transformed.z;
  26538. }
  26539. }
  26540. };
  26541. VertexData.prototype.merge = function (other) {
  26542. var index;
  26543. if (other.indices) {
  26544. if (!this.indices) {
  26545. this.indices = [];
  26546. }
  26547. var offset = this.positions ? this.positions.length / 3 : 0;
  26548. for (index = 0; index < other.indices.length; index++) {
  26549. this.indices.push(other.indices[index] + offset);
  26550. }
  26551. }
  26552. if (other.positions) {
  26553. if (!this.positions) {
  26554. this.positions = [];
  26555. }
  26556. for (index = 0; index < other.positions.length; index++) {
  26557. this.positions.push(other.positions[index]);
  26558. }
  26559. }
  26560. if (other.normals) {
  26561. if (!this.normals) {
  26562. this.normals = [];
  26563. }
  26564. for (index = 0; index < other.normals.length; index++) {
  26565. this.normals.push(other.normals[index]);
  26566. }
  26567. }
  26568. if (other.uvs) {
  26569. if (!this.uvs) {
  26570. this.uvs = [];
  26571. }
  26572. for (index = 0; index < other.uvs.length; index++) {
  26573. this.uvs.push(other.uvs[index]);
  26574. }
  26575. }
  26576. if (other.uvs2) {
  26577. if (!this.uvs2) {
  26578. this.uvs2 = [];
  26579. }
  26580. for (index = 0; index < other.uvs2.length; index++) {
  26581. this.uvs2.push(other.uvs2[index]);
  26582. }
  26583. }
  26584. if (other.uvs3) {
  26585. if (!this.uvs3) {
  26586. this.uvs3 = [];
  26587. }
  26588. for (index = 0; index < other.uvs3.length; index++) {
  26589. this.uvs3.push(other.uvs3[index]);
  26590. }
  26591. }
  26592. if (other.uvs4) {
  26593. if (!this.uvs4) {
  26594. this.uvs4 = [];
  26595. }
  26596. for (index = 0; index < other.uvs4.length; index++) {
  26597. this.uvs4.push(other.uvs4[index]);
  26598. }
  26599. }
  26600. if (other.uvs5) {
  26601. if (!this.uvs5) {
  26602. this.uvs5 = [];
  26603. }
  26604. for (index = 0; index < other.uvs5.length; index++) {
  26605. this.uvs5.push(other.uvs5[index]);
  26606. }
  26607. }
  26608. if (other.uvs6) {
  26609. if (!this.uvs6) {
  26610. this.uvs6 = [];
  26611. }
  26612. for (index = 0; index < other.uvs6.length; index++) {
  26613. this.uvs6.push(other.uvs6[index]);
  26614. }
  26615. }
  26616. if (other.matricesIndices) {
  26617. if (!this.matricesIndices) {
  26618. this.matricesIndices = [];
  26619. }
  26620. for (index = 0; index < other.matricesIndices.length; index++) {
  26621. this.matricesIndices.push(other.matricesIndices[index]);
  26622. }
  26623. }
  26624. if (other.matricesWeights) {
  26625. if (!this.matricesWeights) {
  26626. this.matricesWeights = [];
  26627. }
  26628. for (index = 0; index < other.matricesWeights.length; index++) {
  26629. this.matricesWeights.push(other.matricesWeights[index]);
  26630. }
  26631. }
  26632. if (other.colors) {
  26633. if (!this.colors) {
  26634. this.colors = [];
  26635. }
  26636. for (index = 0; index < other.colors.length; index++) {
  26637. this.colors.push(other.colors[index]);
  26638. }
  26639. }
  26640. };
  26641. // Statics
  26642. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26643. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26644. };
  26645. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26646. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26647. };
  26648. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26649. var result = new VertexData();
  26650. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26651. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26652. }
  26653. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26654. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26655. }
  26656. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26657. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26658. }
  26659. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26660. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26661. }
  26662. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26663. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26664. }
  26665. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26666. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26667. }
  26668. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26669. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26670. }
  26671. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26672. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26673. }
  26674. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26675. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26676. }
  26677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26678. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26679. }
  26680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26681. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26682. }
  26683. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26684. return result;
  26685. };
  26686. VertexData.CreateRibbon = function (options) {
  26687. var pathArray = options.pathArray;
  26688. var closeArray = options.closeArray || false;
  26689. var closePath = options.closePath || false;
  26690. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26691. var offset = options.offset || defaultOffset;
  26692. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26693. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26694. var positions = [];
  26695. var indices = [];
  26696. var normals = [];
  26697. var uvs = [];
  26698. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26699. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26700. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26701. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26702. var minlg; // minimal length among all paths from pathArray
  26703. var lg = []; // array of path lengths : nb of vertex per path
  26704. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26705. var p; // path iterator
  26706. var i; // point iterator
  26707. var j; // point iterator
  26708. // if single path in pathArray
  26709. if (pathArray.length < 2) {
  26710. var ar1 = [];
  26711. var ar2 = [];
  26712. for (i = 0; i < pathArray[0].length - offset; i++) {
  26713. ar1.push(pathArray[0][i]);
  26714. ar2.push(pathArray[0][i + offset]);
  26715. }
  26716. pathArray = [ar1, ar2];
  26717. }
  26718. // positions and horizontal distances (u)
  26719. var idc = 0;
  26720. var closePathCorr = (closePath) ? 1 : 0;
  26721. var path;
  26722. var l;
  26723. minlg = pathArray[0].length;
  26724. var vectlg;
  26725. var dist;
  26726. for (p = 0; p < pathArray.length; p++) {
  26727. uTotalDistance[p] = 0;
  26728. us[p] = [0];
  26729. path = pathArray[p];
  26730. l = path.length;
  26731. minlg = (minlg < l) ? minlg : l;
  26732. j = 0;
  26733. while (j < l) {
  26734. positions.push(path[j].x, path[j].y, path[j].z);
  26735. if (j > 0) {
  26736. vectlg = path[j].subtract(path[j - 1]).length();
  26737. dist = vectlg + uTotalDistance[p];
  26738. us[p].push(dist);
  26739. uTotalDistance[p] = dist;
  26740. }
  26741. j++;
  26742. }
  26743. if (closePath) {
  26744. j--;
  26745. positions.push(path[0].x, path[0].y, path[0].z);
  26746. vectlg = path[j].subtract(path[0]).length();
  26747. dist = vectlg + uTotalDistance[p];
  26748. us[p].push(dist);
  26749. uTotalDistance[p] = dist;
  26750. }
  26751. lg[p] = l + closePathCorr;
  26752. idx[p] = idc;
  26753. idc += (l + closePathCorr);
  26754. }
  26755. // vertical distances (v)
  26756. var path1;
  26757. var path2;
  26758. var vertex1;
  26759. var vertex2;
  26760. for (i = 0; i < minlg + closePathCorr; i++) {
  26761. vTotalDistance[i] = 0;
  26762. vs[i] = [0];
  26763. for (p = 0; p < pathArray.length - 1; p++) {
  26764. path1 = pathArray[p];
  26765. path2 = pathArray[p + 1];
  26766. if (i === minlg) {
  26767. vertex1 = path1[0];
  26768. vertex2 = path2[0];
  26769. }
  26770. else {
  26771. vertex1 = path1[i];
  26772. vertex2 = path2[i];
  26773. }
  26774. vectlg = vertex2.subtract(vertex1).length();
  26775. dist = vectlg + vTotalDistance[i];
  26776. vs[i].push(dist);
  26777. vTotalDistance[i] = dist;
  26778. }
  26779. if (closeArray) {
  26780. path1 = pathArray[p];
  26781. path2 = pathArray[0];
  26782. if (i === minlg) {
  26783. vertex2 = path2[0];
  26784. }
  26785. vectlg = vertex2.subtract(vertex1).length();
  26786. dist = vectlg + vTotalDistance[i];
  26787. vTotalDistance[i] = dist;
  26788. }
  26789. }
  26790. // uvs
  26791. var u;
  26792. var v;
  26793. for (p = 0; p < pathArray.length; p++) {
  26794. for (i = 0; i < minlg + closePathCorr; i++) {
  26795. u = us[p][i] / uTotalDistance[p];
  26796. v = vs[i][p] / vTotalDistance[i];
  26797. uvs.push(u, v);
  26798. }
  26799. }
  26800. // indices
  26801. p = 0; // path index
  26802. var pi = 0; // positions array index
  26803. var l1 = lg[p] - 1; // path1 length
  26804. var l2 = lg[p + 1] - 1; // path2 length
  26805. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26806. var shft = idx[1] - idx[0]; // shift
  26807. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26808. while (pi <= min && p < path1nb) {
  26809. // 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
  26810. indices.push(pi, pi + shft, pi + 1);
  26811. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26812. pi += 1;
  26813. if (pi === min) {
  26814. p++;
  26815. if (p === lg.length - 1) {
  26816. shft = idx[0] - idx[p];
  26817. l1 = lg[p] - 1;
  26818. l2 = lg[0] - 1;
  26819. }
  26820. else {
  26821. shft = idx[p + 1] - idx[p];
  26822. l1 = lg[p] - 1;
  26823. l2 = lg[p + 1] - 1;
  26824. }
  26825. pi = idx[p];
  26826. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26827. }
  26828. }
  26829. // normals
  26830. VertexData.ComputeNormals(positions, indices, normals);
  26831. if (closePath) {
  26832. var indexFirst = 0;
  26833. var indexLast = 0;
  26834. for (p = 0; p < pathArray.length; p++) {
  26835. indexFirst = idx[p] * 3;
  26836. if (p + 1 < pathArray.length) {
  26837. indexLast = (idx[p + 1] - 1) * 3;
  26838. }
  26839. else {
  26840. indexLast = normals.length - 3;
  26841. }
  26842. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26843. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26844. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26845. normals[indexLast] = normals[indexFirst];
  26846. normals[indexLast + 1] = normals[indexFirst + 1];
  26847. normals[indexLast + 2] = normals[indexFirst + 2];
  26848. }
  26849. }
  26850. // sides
  26851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26852. // Result
  26853. var vertexData = new VertexData();
  26854. vertexData.indices = indices;
  26855. vertexData.positions = positions;
  26856. vertexData.normals = normals;
  26857. vertexData.uvs = uvs;
  26858. if (closePath) {
  26859. vertexData._idx = idx;
  26860. }
  26861. return vertexData;
  26862. };
  26863. VertexData.CreateBox = function (options) {
  26864. var normalsSource = [
  26865. new BABYLON.Vector3(0, 0, 1),
  26866. new BABYLON.Vector3(0, 0, -1),
  26867. new BABYLON.Vector3(1, 0, 0),
  26868. new BABYLON.Vector3(-1, 0, 0),
  26869. new BABYLON.Vector3(0, 1, 0),
  26870. new BABYLON.Vector3(0, -1, 0)
  26871. ];
  26872. var indices = [];
  26873. var positions = [];
  26874. var normals = [];
  26875. var uvs = [];
  26876. var width = options.width || options.size || 1;
  26877. var height = options.height || options.size || 1;
  26878. var depth = options.depth || options.size || 1;
  26879. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26880. var faceUV = options.faceUV || new Array(6);
  26881. var faceColors = options.faceColors;
  26882. var colors = [];
  26883. // default face colors and UV if undefined
  26884. for (var f = 0; f < 6; f++) {
  26885. if (faceUV[f] === undefined) {
  26886. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26887. }
  26888. if (faceColors && faceColors[f] === undefined) {
  26889. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26890. }
  26891. }
  26892. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26893. // Create each face in turn.
  26894. for (var index = 0; index < normalsSource.length; index++) {
  26895. var normal = normalsSource[index];
  26896. // Get two vectors perpendicular to the face normal and to each other.
  26897. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26898. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26899. // Six indices (two triangles) per face.
  26900. var verticesLength = positions.length / 3;
  26901. indices.push(verticesLength);
  26902. indices.push(verticesLength + 1);
  26903. indices.push(verticesLength + 2);
  26904. indices.push(verticesLength);
  26905. indices.push(verticesLength + 2);
  26906. indices.push(verticesLength + 3);
  26907. // Four vertices per face.
  26908. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26909. positions.push(vertex.x, vertex.y, vertex.z);
  26910. normals.push(normal.x, normal.y, normal.z);
  26911. uvs.push(faceUV[index].z, faceUV[index].w);
  26912. if (faceColors) {
  26913. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26914. }
  26915. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26916. positions.push(vertex.x, vertex.y, vertex.z);
  26917. normals.push(normal.x, normal.y, normal.z);
  26918. uvs.push(faceUV[index].x, faceUV[index].w);
  26919. if (faceColors) {
  26920. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26921. }
  26922. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26923. positions.push(vertex.x, vertex.y, vertex.z);
  26924. normals.push(normal.x, normal.y, normal.z);
  26925. uvs.push(faceUV[index].x, faceUV[index].y);
  26926. if (faceColors) {
  26927. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26928. }
  26929. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26930. positions.push(vertex.x, vertex.y, vertex.z);
  26931. normals.push(normal.x, normal.y, normal.z);
  26932. uvs.push(faceUV[index].z, faceUV[index].y);
  26933. if (faceColors) {
  26934. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26935. }
  26936. }
  26937. // sides
  26938. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26939. // Result
  26940. var vertexData = new VertexData();
  26941. vertexData.indices = indices;
  26942. vertexData.positions = positions;
  26943. vertexData.normals = normals;
  26944. vertexData.uvs = uvs;
  26945. if (faceColors) {
  26946. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26947. vertexData.colors = totalColors;
  26948. }
  26949. return vertexData;
  26950. };
  26951. VertexData.CreateSphere = function (options) {
  26952. var segments = options.segments || 32;
  26953. var diameterX = options.diameterX || options.diameter || 1;
  26954. var diameterY = options.diameterY || options.diameter || 1;
  26955. var diameterZ = options.diameterZ || options.diameter || 1;
  26956. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  26957. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26958. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26959. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26960. var totalZRotationSteps = 2 + segments;
  26961. var totalYRotationSteps = 2 * totalZRotationSteps;
  26962. var indices = [];
  26963. var positions = [];
  26964. var normals = [];
  26965. var uvs = [];
  26966. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26967. var normalizedZ = zRotationStep / totalZRotationSteps;
  26968. var angleZ = normalizedZ * Math.PI * slice;
  26969. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26970. var normalizedY = yRotationStep / totalYRotationSteps;
  26971. var angleY = normalizedY * Math.PI * 2 * arc;
  26972. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26973. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26974. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26975. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26976. var vertex = complete.multiply(radius);
  26977. var normal = BABYLON.Vector3.Normalize(vertex);
  26978. positions.push(vertex.x, vertex.y, vertex.z);
  26979. normals.push(normal.x, normal.y, normal.z);
  26980. uvs.push(normalizedY, normalizedZ);
  26981. }
  26982. if (zRotationStep > 0) {
  26983. var verticesCount = positions.length / 3;
  26984. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26985. indices.push((firstIndex));
  26986. indices.push((firstIndex + 1));
  26987. indices.push(firstIndex + totalYRotationSteps + 1);
  26988. indices.push((firstIndex + totalYRotationSteps + 1));
  26989. indices.push((firstIndex + 1));
  26990. indices.push((firstIndex + totalYRotationSteps + 2));
  26991. }
  26992. }
  26993. }
  26994. // Sides
  26995. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26996. // Result
  26997. var vertexData = new VertexData();
  26998. vertexData.indices = indices;
  26999. vertexData.positions = positions;
  27000. vertexData.normals = normals;
  27001. vertexData.uvs = uvs;
  27002. return vertexData;
  27003. };
  27004. // Cylinder and cone
  27005. VertexData.CreateCylinder = function (options) {
  27006. var height = options.height || 2;
  27007. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || 1;
  27008. var diameterBottom = options.diameterBottom || 1;
  27009. var tessellation = options.tessellation || 24;
  27010. var subdivisions = options.subdivisions || 1;
  27011. var arc = (options.arc <= 0) ? 1.0 : options.arc || 1.0;
  27012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27013. var faceUV = options.faceUV || new Array(3);
  27014. var faceColors = options.faceColors;
  27015. // default face colors and UV if undefined
  27016. for (var f = 0; f < 3; f++) {
  27017. if (faceColors && faceColors[f] === undefined) {
  27018. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27019. }
  27020. if (faceUV && faceUV[f] === undefined) {
  27021. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27022. }
  27023. }
  27024. var indices = [];
  27025. var positions = [];
  27026. var normals = [];
  27027. var uvs = [];
  27028. var colors = [];
  27029. var angle_step = Math.PI * 2 * arc / tessellation;
  27030. var angle;
  27031. var h;
  27032. var radius;
  27033. var tan = (diameterBottom - diameterTop) / 2 / height;
  27034. var ringVertex = BABYLON.Vector3.Zero();
  27035. var ringNormal = BABYLON.Vector3.Zero();
  27036. // positions, normals, uvs
  27037. var i;
  27038. var j;
  27039. for (i = 0; i <= subdivisions; i++) {
  27040. h = i / subdivisions;
  27041. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27042. for (j = 0; j <= tessellation; j++) {
  27043. angle = j * angle_step;
  27044. ringVertex.x = Math.cos(-angle) * radius;
  27045. ringVertex.y = -height / 2 + h * height;
  27046. ringVertex.z = Math.sin(-angle) * radius;
  27047. if (diameterTop === 0 && i === subdivisions) {
  27048. // if no top cap, reuse former normals
  27049. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27050. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27051. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27052. }
  27053. else {
  27054. ringNormal.x = ringVertex.x;
  27055. ringNormal.z = ringVertex.z;
  27056. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27057. ringNormal.normalize();
  27058. }
  27059. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27060. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27061. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  27062. if (faceColors) {
  27063. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  27064. }
  27065. }
  27066. }
  27067. // indices
  27068. for (i = 0; i < subdivisions; i++) {
  27069. for (j = 0; j < tessellation; j++) {
  27070. var i0 = i * (tessellation + 1) + j;
  27071. var i1 = (i + 1) * (tessellation + 1) + j;
  27072. var i2 = i * (tessellation + 1) + (j + 1);
  27073. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  27074. indices.push(i0, i1, i2);
  27075. indices.push(i3, i2, i1);
  27076. }
  27077. }
  27078. // Caps
  27079. var createCylinderCap = function (isTop) {
  27080. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27081. if (radius === 0) {
  27082. return;
  27083. }
  27084. // Cap positions, normals & uvs
  27085. var angle;
  27086. var circleVector;
  27087. var i;
  27088. var u = (isTop) ? faceUV[2] : faceUV[0];
  27089. var c;
  27090. if (faceColors) {
  27091. c = (isTop) ? faceColors[2] : faceColors[0];
  27092. }
  27093. // cap center
  27094. var vbase = positions.length / 3;
  27095. var offset = isTop ? height / 2 : -height / 2;
  27096. var center = new BABYLON.Vector3(0, offset, 0);
  27097. positions.push(center.x, center.y, center.z);
  27098. normals.push(0, isTop ? 1 : -1, 0);
  27099. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27100. if (faceColors) {
  27101. colors.push(c.r, c.g, c.b, c.a);
  27102. }
  27103. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27104. for (i = 0; i <= tessellation; i++) {
  27105. angle = Math.PI * 2 * i * arc / tessellation;
  27106. var cos = Math.cos(-angle);
  27107. var sin = Math.sin(-angle);
  27108. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27109. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27110. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27111. normals.push(0, isTop ? 1 : -1, 0);
  27112. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27113. if (faceColors) {
  27114. colors.push(c.r, c.g, c.b, c.a);
  27115. }
  27116. }
  27117. // Cap indices
  27118. for (i = 0; i < tessellation; i++) {
  27119. if (!isTop) {
  27120. indices.push(vbase);
  27121. indices.push(vbase + (i + 1));
  27122. indices.push(vbase + (i + 2));
  27123. }
  27124. else {
  27125. indices.push(vbase);
  27126. indices.push(vbase + (i + 2));
  27127. indices.push(vbase + (i + 1));
  27128. }
  27129. }
  27130. };
  27131. // add caps to geometry
  27132. createCylinderCap(false);
  27133. createCylinderCap(true);
  27134. // Sides
  27135. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27136. var vertexData = new VertexData();
  27137. vertexData.indices = indices;
  27138. vertexData.positions = positions;
  27139. vertexData.normals = normals;
  27140. vertexData.uvs = uvs;
  27141. if (faceColors) {
  27142. vertexData.colors = colors;
  27143. }
  27144. return vertexData;
  27145. };
  27146. VertexData.CreateTorus = function (options) {
  27147. var indices = [];
  27148. var positions = [];
  27149. var normals = [];
  27150. var uvs = [];
  27151. var diameter = options.diameter || 1;
  27152. var thickness = options.thickness || 0.5;
  27153. var tessellation = options.tessellation || 16;
  27154. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27155. var stride = tessellation + 1;
  27156. for (var i = 0; i <= tessellation; i++) {
  27157. var u = i / tessellation;
  27158. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27159. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27160. for (var j = 0; j <= tessellation; j++) {
  27161. var v = 1 - j / tessellation;
  27162. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27163. var dx = Math.cos(innerAngle);
  27164. var dy = Math.sin(innerAngle);
  27165. // Create a vertex.
  27166. var normal = new BABYLON.Vector3(dx, dy, 0);
  27167. var position = normal.scale(thickness / 2);
  27168. var textureCoordinate = new BABYLON.Vector2(u, v);
  27169. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27170. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27171. positions.push(position.x, position.y, position.z);
  27172. normals.push(normal.x, normal.y, normal.z);
  27173. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27174. // And create indices for two triangles.
  27175. var nextI = (i + 1) % stride;
  27176. var nextJ = (j + 1) % stride;
  27177. indices.push(i * stride + j);
  27178. indices.push(i * stride + nextJ);
  27179. indices.push(nextI * stride + j);
  27180. indices.push(i * stride + nextJ);
  27181. indices.push(nextI * stride + nextJ);
  27182. indices.push(nextI * stride + j);
  27183. }
  27184. }
  27185. // Sides
  27186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27187. // Result
  27188. var vertexData = new VertexData();
  27189. vertexData.indices = indices;
  27190. vertexData.positions = positions;
  27191. vertexData.normals = normals;
  27192. vertexData.uvs = uvs;
  27193. return vertexData;
  27194. };
  27195. VertexData.CreateLines = function (options) {
  27196. var indices = [];
  27197. var positions = [];
  27198. var points = options.points;
  27199. for (var index = 0; index < points.length; index++) {
  27200. positions.push(points[index].x, points[index].y, points[index].z);
  27201. if (index > 0) {
  27202. indices.push(index - 1);
  27203. indices.push(index);
  27204. }
  27205. }
  27206. // Result
  27207. var vertexData = new VertexData();
  27208. vertexData.indices = indices;
  27209. vertexData.positions = positions;
  27210. return vertexData;
  27211. };
  27212. VertexData.CreateDashedLines = function (options) {
  27213. var dashSize = options.dashSize || 3;
  27214. var gapSize = options.gapSize || 1;
  27215. var dashNb = options.dashNb || 200;
  27216. var points = options.points;
  27217. var positions = new Array();
  27218. var indices = new Array();
  27219. var curvect = BABYLON.Vector3.Zero();
  27220. var lg = 0;
  27221. var nb = 0;
  27222. var shft = 0;
  27223. var dashshft = 0;
  27224. var curshft = 0;
  27225. var idx = 0;
  27226. var i = 0;
  27227. for (i = 0; i < points.length - 1; i++) {
  27228. points[i + 1].subtractToRef(points[i], curvect);
  27229. lg += curvect.length();
  27230. }
  27231. shft = lg / dashNb;
  27232. dashshft = dashSize * shft / (dashSize + gapSize);
  27233. for (i = 0; i < points.length - 1; i++) {
  27234. points[i + 1].subtractToRef(points[i], curvect);
  27235. nb = Math.floor(curvect.length() / shft);
  27236. curvect.normalize();
  27237. for (var j = 0; j < nb; j++) {
  27238. curshft = shft * j;
  27239. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27240. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27241. indices.push(idx, idx + 1);
  27242. idx += 2;
  27243. }
  27244. }
  27245. // Result
  27246. var vertexData = new VertexData();
  27247. vertexData.positions = positions;
  27248. vertexData.indices = indices;
  27249. return vertexData;
  27250. };
  27251. VertexData.CreateGround = function (options) {
  27252. var indices = [];
  27253. var positions = [];
  27254. var normals = [];
  27255. var uvs = [];
  27256. var row, col;
  27257. var width = options.width || 1;
  27258. var height = options.height || 1;
  27259. var subdivisions = options.subdivisions || 1;
  27260. for (row = 0; row <= subdivisions; row++) {
  27261. for (col = 0; col <= subdivisions; col++) {
  27262. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  27263. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27264. positions.push(position.x, position.y, position.z);
  27265. normals.push(normal.x, normal.y, normal.z);
  27266. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  27267. }
  27268. }
  27269. for (row = 0; row < subdivisions; row++) {
  27270. for (col = 0; col < subdivisions; col++) {
  27271. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27272. indices.push(col + 1 + row * (subdivisions + 1));
  27273. indices.push(col + row * (subdivisions + 1));
  27274. indices.push(col + (row + 1) * (subdivisions + 1));
  27275. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  27276. indices.push(col + row * (subdivisions + 1));
  27277. }
  27278. }
  27279. // Result
  27280. var vertexData = new VertexData();
  27281. vertexData.indices = indices;
  27282. vertexData.positions = positions;
  27283. vertexData.normals = normals;
  27284. vertexData.uvs = uvs;
  27285. return vertexData;
  27286. };
  27287. VertexData.CreateTiledGround = function (options) {
  27288. var xmin = options.xmin;
  27289. var zmin = options.zmin;
  27290. var xmax = options.xmax;
  27291. var zmax = options.zmax;
  27292. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27293. var precision = options.precision || { w: 1, h: 1 };
  27294. var indices = [];
  27295. var positions = [];
  27296. var normals = [];
  27297. var uvs = [];
  27298. var row, col, tileRow, tileCol;
  27299. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  27300. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27301. precision.w = (precision.w < 1) ? 1 : precision.w;
  27302. precision.h = (precision.h < 1) ? 1 : precision.h;
  27303. var tileSize = {
  27304. 'w': (xmax - xmin) / subdivisions.w,
  27305. 'h': (zmax - zmin) / subdivisions.h
  27306. };
  27307. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27308. // Indices
  27309. var base = positions.length / 3;
  27310. var rowLength = precision.w + 1;
  27311. for (row = 0; row < precision.h; row++) {
  27312. for (col = 0; col < precision.w; col++) {
  27313. var square = [
  27314. base + col + row * rowLength,
  27315. base + (col + 1) + row * rowLength,
  27316. base + (col + 1) + (row + 1) * rowLength,
  27317. base + col + (row + 1) * rowLength
  27318. ];
  27319. indices.push(square[1]);
  27320. indices.push(square[2]);
  27321. indices.push(square[3]);
  27322. indices.push(square[0]);
  27323. indices.push(square[1]);
  27324. indices.push(square[3]);
  27325. }
  27326. }
  27327. // Position, normals and uvs
  27328. var position = BABYLON.Vector3.Zero();
  27329. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27330. for (row = 0; row <= precision.h; row++) {
  27331. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27332. for (col = 0; col <= precision.w; col++) {
  27333. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27334. position.y = 0;
  27335. positions.push(position.x, position.y, position.z);
  27336. normals.push(normal.x, normal.y, normal.z);
  27337. uvs.push(col / precision.w, row / precision.h);
  27338. }
  27339. }
  27340. }
  27341. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27342. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27343. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27344. }
  27345. }
  27346. // Result
  27347. var vertexData = new VertexData();
  27348. vertexData.indices = indices;
  27349. vertexData.positions = positions;
  27350. vertexData.normals = normals;
  27351. vertexData.uvs = uvs;
  27352. return vertexData;
  27353. };
  27354. VertexData.CreateGroundFromHeightMap = function (options) {
  27355. var indices = [];
  27356. var positions = [];
  27357. var normals = [];
  27358. var uvs = [];
  27359. var row, col;
  27360. // Vertices
  27361. for (row = 0; row <= options.subdivisions; row++) {
  27362. for (col = 0; col <= options.subdivisions; col++) {
  27363. var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
  27364. // Compute height
  27365. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27366. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27367. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27368. var r = options.buffer[pos] / 255.0;
  27369. var g = options.buffer[pos + 1] / 255.0;
  27370. var b = options.buffer[pos + 2] / 255.0;
  27371. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  27372. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27373. // Add vertex
  27374. positions.push(position.x, position.y, position.z);
  27375. normals.push(0, 0, 0);
  27376. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27377. }
  27378. }
  27379. // Indices
  27380. for (row = 0; row < options.subdivisions; row++) {
  27381. for (col = 0; col < options.subdivisions; col++) {
  27382. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27383. indices.push(col + 1 + row * (options.subdivisions + 1));
  27384. indices.push(col + row * (options.subdivisions + 1));
  27385. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27386. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27387. indices.push(col + row * (options.subdivisions + 1));
  27388. }
  27389. }
  27390. // Normals
  27391. VertexData.ComputeNormals(positions, indices, normals);
  27392. // Result
  27393. var vertexData = new VertexData();
  27394. vertexData.indices = indices;
  27395. vertexData.positions = positions;
  27396. vertexData.normals = normals;
  27397. vertexData.uvs = uvs;
  27398. return vertexData;
  27399. };
  27400. VertexData.CreatePlane = function (options) {
  27401. var indices = [];
  27402. var positions = [];
  27403. var normals = [];
  27404. var uvs = [];
  27405. var width = options.width || options.size || 1;
  27406. var height = options.height || options.size || 1;
  27407. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27408. // Vertices
  27409. var halfWidth = width / 2.0;
  27410. var halfHeight = height / 2.0;
  27411. positions.push(-halfWidth, -halfHeight, 0);
  27412. normals.push(0, 0, -1.0);
  27413. uvs.push(0.0, 0.0);
  27414. positions.push(halfWidth, -halfHeight, 0);
  27415. normals.push(0, 0, -1.0);
  27416. uvs.push(1.0, 0.0);
  27417. positions.push(halfWidth, halfHeight, 0);
  27418. normals.push(0, 0, -1.0);
  27419. uvs.push(1.0, 1.0);
  27420. positions.push(-halfWidth, halfHeight, 0);
  27421. normals.push(0, 0, -1.0);
  27422. uvs.push(0.0, 1.0);
  27423. // Indices
  27424. indices.push(0);
  27425. indices.push(1);
  27426. indices.push(2);
  27427. indices.push(0);
  27428. indices.push(2);
  27429. indices.push(3);
  27430. // Sides
  27431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27432. // Result
  27433. var vertexData = new VertexData();
  27434. vertexData.indices = indices;
  27435. vertexData.positions = positions;
  27436. vertexData.normals = normals;
  27437. vertexData.uvs = uvs;
  27438. return vertexData;
  27439. };
  27440. VertexData.CreateDisc = function (options) {
  27441. var positions = [];
  27442. var indices = [];
  27443. var normals = [];
  27444. var uvs = [];
  27445. var radius = options.radius || 0.5;
  27446. var tessellation = options.tessellation || 64;
  27447. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27448. // positions and uvs
  27449. positions.push(0, 0, 0); // disc center first
  27450. uvs.push(0.5, 0.5);
  27451. var step = Math.PI * 2 / tessellation;
  27452. for (var a = 0; a < Math.PI * 2; a += step) {
  27453. var x = Math.cos(a);
  27454. var y = Math.sin(a);
  27455. var u = (x + 1) / 2;
  27456. var v = (1 - y) / 2;
  27457. positions.push(radius * x, radius * y, 0);
  27458. uvs.push(u, v);
  27459. }
  27460. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27461. uvs.push(uvs[2], uvs[3]);
  27462. //indices
  27463. var vertexNb = positions.length / 3;
  27464. for (var i = 1; i < vertexNb - 1; i++) {
  27465. indices.push(i + 1, 0, i);
  27466. }
  27467. // result
  27468. VertexData.ComputeNormals(positions, indices, normals);
  27469. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27470. var vertexData = new VertexData();
  27471. vertexData.indices = indices;
  27472. vertexData.positions = positions;
  27473. vertexData.normals = normals;
  27474. vertexData.uvs = uvs;
  27475. return vertexData;
  27476. };
  27477. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  27478. VertexData.CreateTorusKnot = function (options) {
  27479. var indices = [];
  27480. var positions = [];
  27481. var normals = [];
  27482. var uvs = [];
  27483. var radius = options.radius || 2;
  27484. var tube = options.tube || 0.5;
  27485. var radialSegments = options.radialSegments || 32;
  27486. var tubularSegments = options.tubularSegments || 32;
  27487. var p = options.p || 2;
  27488. var q = options.q || 3;
  27489. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27490. // Helper
  27491. var getPos = function (angle) {
  27492. var cu = Math.cos(angle);
  27493. var su = Math.sin(angle);
  27494. var quOverP = q / p * angle;
  27495. var cs = Math.cos(quOverP);
  27496. var tx = radius * (2 + cs) * 0.5 * cu;
  27497. var ty = radius * (2 + cs) * su * 0.5;
  27498. var tz = radius * Math.sin(quOverP) * 0.5;
  27499. return new BABYLON.Vector3(tx, ty, tz);
  27500. };
  27501. // Vertices
  27502. var i;
  27503. var j;
  27504. for (i = 0; i <= radialSegments; i++) {
  27505. var modI = i % radialSegments;
  27506. var u = modI / radialSegments * 2 * p * Math.PI;
  27507. var p1 = getPos(u);
  27508. var p2 = getPos(u + 0.01);
  27509. var tang = p2.subtract(p1);
  27510. var n = p2.add(p1);
  27511. var bitan = BABYLON.Vector3.Cross(tang, n);
  27512. n = BABYLON.Vector3.Cross(bitan, tang);
  27513. bitan.normalize();
  27514. n.normalize();
  27515. for (j = 0; j < tubularSegments; j++) {
  27516. var modJ = j % tubularSegments;
  27517. var v = modJ / tubularSegments * 2 * Math.PI;
  27518. var cx = -tube * Math.cos(v);
  27519. var cy = tube * Math.sin(v);
  27520. positions.push(p1.x + cx * n.x + cy * bitan.x);
  27521. positions.push(p1.y + cx * n.y + cy * bitan.y);
  27522. positions.push(p1.z + cx * n.z + cy * bitan.z);
  27523. uvs.push(i / radialSegments);
  27524. uvs.push(j / tubularSegments);
  27525. }
  27526. }
  27527. for (i = 0; i < radialSegments; i++) {
  27528. for (j = 0; j < tubularSegments; j++) {
  27529. var jNext = (j + 1) % tubularSegments;
  27530. var a = i * tubularSegments + j;
  27531. var b = (i + 1) * tubularSegments + j;
  27532. var c = (i + 1) * tubularSegments + jNext;
  27533. var d = i * tubularSegments + jNext;
  27534. indices.push(d);
  27535. indices.push(b);
  27536. indices.push(a);
  27537. indices.push(d);
  27538. indices.push(c);
  27539. indices.push(b);
  27540. }
  27541. }
  27542. // Normals
  27543. VertexData.ComputeNormals(positions, indices, normals);
  27544. // Sides
  27545. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27546. // Result
  27547. var vertexData = new VertexData();
  27548. vertexData.indices = indices;
  27549. vertexData.positions = positions;
  27550. vertexData.normals = normals;
  27551. vertexData.uvs = uvs;
  27552. return vertexData;
  27553. };
  27554. // Tools
  27555. /**
  27556. * @param {any} - positions (number[] or Float32Array)
  27557. * @param {any} - indices (number[] or Uint16Array)
  27558. * @param {any} - normals (number[] or Float32Array)
  27559. */
  27560. VertexData.ComputeNormals = function (positions, indices, normals) {
  27561. var index = 0;
  27562. // temp Vector3
  27563. var p1p2 = BABYLON.Vector3.Zero();
  27564. var p3p2 = BABYLON.Vector3.Zero();
  27565. var faceNormal = BABYLON.Vector3.Zero();
  27566. var vertexNormali1 = BABYLON.Vector3.Zero();
  27567. for (index = 0; index < positions.length; index++) {
  27568. normals[index] = 0.0;
  27569. }
  27570. // indice triplet = 1 face
  27571. var nbFaces = indices.length / 3;
  27572. for (index = 0; index < nbFaces; index++) {
  27573. var i1 = indices[index * 3];
  27574. var i2 = indices[index * 3 + 1];
  27575. var i3 = indices[index * 3 + 2];
  27576. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  27577. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  27578. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  27579. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  27580. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  27581. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  27582. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  27583. faceNormal.normalize();
  27584. normals[i1 * 3] += faceNormal.x;
  27585. normals[i1 * 3 + 1] += faceNormal.y;
  27586. normals[i1 * 3 + 2] += faceNormal.z;
  27587. normals[i2 * 3] += faceNormal.x;
  27588. normals[i2 * 3 + 1] += faceNormal.y;
  27589. normals[i2 * 3 + 2] += faceNormal.z;
  27590. normals[i3 * 3] += faceNormal.x;
  27591. normals[i3 * 3 + 1] += faceNormal.y;
  27592. normals[i3 * 3 + 2] += faceNormal.z;
  27593. }
  27594. // last normalization
  27595. for (index = 0; index < normals.length / 3; index++) {
  27596. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  27597. vertexNormali1.normalize();
  27598. normals[index * 3] = vertexNormali1.x;
  27599. normals[index * 3 + 1] = vertexNormali1.y;
  27600. normals[index * 3 + 2] = vertexNormali1.z;
  27601. }
  27602. };
  27603. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  27604. var li = indices.length;
  27605. var ln = normals.length;
  27606. var i;
  27607. var n;
  27608. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27609. switch (sideOrientation) {
  27610. case BABYLON.Mesh.FRONTSIDE:
  27611. // nothing changed
  27612. break;
  27613. case BABYLON.Mesh.BACKSIDE:
  27614. var tmp;
  27615. // indices
  27616. for (i = 0; i < li; i += 3) {
  27617. tmp = indices[i];
  27618. indices[i] = indices[i + 2];
  27619. indices[i + 2] = tmp;
  27620. }
  27621. // normals
  27622. for (n = 0; n < ln; n++) {
  27623. normals[n] = -normals[n];
  27624. }
  27625. break;
  27626. case BABYLON.Mesh.DOUBLESIDE:
  27627. // positions
  27628. var lp = positions.length;
  27629. var l = lp / 3;
  27630. for (var p = 0; p < lp; p++) {
  27631. positions[lp + p] = positions[p];
  27632. }
  27633. // indices
  27634. for (i = 0; i < li; i += 3) {
  27635. indices[i + li] = indices[i + 2] + l;
  27636. indices[i + 1 + li] = indices[i + 1] + l;
  27637. indices[i + 2 + li] = indices[i] + l;
  27638. }
  27639. // normals
  27640. for (n = 0; n < ln; n++) {
  27641. normals[ln + n] = -normals[n];
  27642. }
  27643. // uvs
  27644. var lu = uvs.length;
  27645. for (var u = 0; u < lu; u++) {
  27646. uvs[u + lu] = uvs[u];
  27647. }
  27648. break;
  27649. }
  27650. };
  27651. return VertexData;
  27652. })();
  27653. BABYLON.VertexData = VertexData;
  27654. })(BABYLON || (BABYLON = {}));
  27655. var BABYLON;
  27656. (function (BABYLON) {
  27657. var AnaglyphPostProcess = (function (_super) {
  27658. __extends(AnaglyphPostProcess, _super);
  27659. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27660. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27661. }
  27662. return AnaglyphPostProcess;
  27663. })(BABYLON.PostProcess);
  27664. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27665. })(BABYLON || (BABYLON = {}));
  27666. var BABYLON;
  27667. (function (BABYLON) {
  27668. var Tags = (function () {
  27669. function Tags() {
  27670. }
  27671. Tags.EnableFor = function (obj) {
  27672. obj._tags = obj._tags || {};
  27673. obj.hasTags = function () {
  27674. return Tags.HasTags(obj);
  27675. };
  27676. obj.addTags = function (tagsString) {
  27677. return Tags.AddTagsTo(obj, tagsString);
  27678. };
  27679. obj.removeTags = function (tagsString) {
  27680. return Tags.RemoveTagsFrom(obj, tagsString);
  27681. };
  27682. obj.matchesTagsQuery = function (tagsQuery) {
  27683. return Tags.MatchesQuery(obj, tagsQuery);
  27684. };
  27685. };
  27686. Tags.DisableFor = function (obj) {
  27687. delete obj._tags;
  27688. delete obj.hasTags;
  27689. delete obj.addTags;
  27690. delete obj.removeTags;
  27691. delete obj.matchesTagsQuery;
  27692. };
  27693. Tags.HasTags = function (obj) {
  27694. if (!obj._tags) {
  27695. return false;
  27696. }
  27697. return !BABYLON.Tools.IsEmpty(obj._tags);
  27698. };
  27699. Tags.GetTags = function (obj) {
  27700. if (!obj._tags) {
  27701. return null;
  27702. }
  27703. return obj._tags;
  27704. };
  27705. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27706. // a tag cannot start with '||', '&&', and '!'
  27707. // it cannot contain whitespaces
  27708. Tags.AddTagsTo = function (obj, tagsString) {
  27709. if (!tagsString) {
  27710. return;
  27711. }
  27712. var tags = tagsString.split(" ");
  27713. for (var t in tags) {
  27714. Tags._AddTagTo(obj, tags[t]);
  27715. }
  27716. };
  27717. Tags._AddTagTo = function (obj, tag) {
  27718. tag = tag.trim();
  27719. if (tag === "" || tag === "true" || tag === "false") {
  27720. return;
  27721. }
  27722. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27723. return;
  27724. }
  27725. Tags.EnableFor(obj);
  27726. obj._tags[tag] = true;
  27727. };
  27728. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27729. if (!Tags.HasTags(obj)) {
  27730. return;
  27731. }
  27732. var tags = tagsString.split(" ");
  27733. for (var t in tags) {
  27734. Tags._RemoveTagFrom(obj, tags[t]);
  27735. }
  27736. };
  27737. Tags._RemoveTagFrom = function (obj, tag) {
  27738. delete obj._tags[tag];
  27739. };
  27740. Tags.MatchesQuery = function (obj, tagsQuery) {
  27741. if (tagsQuery === undefined) {
  27742. return true;
  27743. }
  27744. if (tagsQuery === "") {
  27745. return Tags.HasTags(obj);
  27746. }
  27747. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27748. };
  27749. return Tags;
  27750. })();
  27751. BABYLON.Tags = Tags;
  27752. })(BABYLON || (BABYLON = {}));
  27753. var BABYLON;
  27754. (function (BABYLON) {
  27755. var Internals;
  27756. (function (Internals) {
  27757. var AndOrNotEvaluator = (function () {
  27758. function AndOrNotEvaluator() {
  27759. }
  27760. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27761. if (!query.match(/\([^\(\)]*\)/g)) {
  27762. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27763. }
  27764. else {
  27765. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27766. // remove parenthesis
  27767. r = r.slice(1, r.length - 1);
  27768. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27769. });
  27770. }
  27771. if (query === "true") {
  27772. return true;
  27773. }
  27774. if (query === "false") {
  27775. return false;
  27776. }
  27777. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27778. };
  27779. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27780. evaluateCallback = evaluateCallback || (function (r) {
  27781. return r === "true" ? true : false;
  27782. });
  27783. var result;
  27784. var or = parenthesisContent.split("||");
  27785. for (var i in or) {
  27786. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27787. var and = ori.split("&&");
  27788. if (and.length > 1) {
  27789. for (var j = 0; j < and.length; ++j) {
  27790. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27791. if (andj !== "true" && andj !== "false") {
  27792. if (andj[0] === "!") {
  27793. result = !evaluateCallback(andj.substring(1));
  27794. }
  27795. else {
  27796. result = evaluateCallback(andj);
  27797. }
  27798. }
  27799. else {
  27800. result = andj === "true" ? true : false;
  27801. }
  27802. if (!result) {
  27803. ori = "false";
  27804. break;
  27805. }
  27806. }
  27807. }
  27808. if (result || ori === "true") {
  27809. result = true;
  27810. break;
  27811. }
  27812. // result equals false (or undefined)
  27813. if (ori !== "true" && ori !== "false") {
  27814. if (ori[0] === "!") {
  27815. result = !evaluateCallback(ori.substring(1));
  27816. }
  27817. else {
  27818. result = evaluateCallback(ori);
  27819. }
  27820. }
  27821. else {
  27822. result = ori === "true" ? true : false;
  27823. }
  27824. }
  27825. // the whole parenthesis scope is replaced by 'true' or 'false'
  27826. return result ? "true" : "false";
  27827. };
  27828. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27829. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27830. // remove whitespaces
  27831. r = r.replace(/[\s]/g, function () { return ""; });
  27832. return r.length % 2 ? "!" : "";
  27833. });
  27834. booleanString = booleanString.trim();
  27835. if (booleanString === "!true") {
  27836. booleanString = "false";
  27837. }
  27838. else if (booleanString === "!false") {
  27839. booleanString = "true";
  27840. }
  27841. return booleanString;
  27842. };
  27843. return AndOrNotEvaluator;
  27844. })();
  27845. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27847. })(BABYLON || (BABYLON = {}));
  27848. var BABYLON;
  27849. (function (BABYLON) {
  27850. var PostProcessRenderPass = (function () {
  27851. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27852. this._enabled = true;
  27853. this._refCount = 0;
  27854. this._name = name;
  27855. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27856. this.setRenderList(renderList);
  27857. this._renderTexture.onBeforeRender = beforeRender;
  27858. this._renderTexture.onAfterRender = afterRender;
  27859. this._scene = scene;
  27860. this._renderList = renderList;
  27861. }
  27862. // private
  27863. PostProcessRenderPass.prototype._incRefCount = function () {
  27864. if (this._refCount === 0) {
  27865. this._scene.customRenderTargets.push(this._renderTexture);
  27866. }
  27867. return ++this._refCount;
  27868. };
  27869. PostProcessRenderPass.prototype._decRefCount = function () {
  27870. this._refCount--;
  27871. if (this._refCount <= 0) {
  27872. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27873. }
  27874. return this._refCount;
  27875. };
  27876. PostProcessRenderPass.prototype._update = function () {
  27877. this.setRenderList(this._renderList);
  27878. };
  27879. // public
  27880. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27881. this._renderTexture.renderList = renderList;
  27882. };
  27883. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27884. return this._renderTexture;
  27885. };
  27886. return PostProcessRenderPass;
  27887. })();
  27888. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27889. })(BABYLON || (BABYLON = {}));
  27890. var BABYLON;
  27891. (function (BABYLON) {
  27892. var PostProcessRenderEffect = (function () {
  27893. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27894. this._engine = engine;
  27895. this._name = name;
  27896. this._singleInstance = singleInstance || true;
  27897. this._getPostProcess = getPostProcess;
  27898. this._cameras = [];
  27899. this._indicesForCamera = [];
  27900. this._postProcesses = {};
  27901. this._renderPasses = {};
  27902. this._renderEffectAsPasses = {};
  27903. }
  27904. PostProcessRenderEffect.prototype._update = function () {
  27905. for (var renderPassName in this._renderPasses) {
  27906. this._renderPasses[renderPassName]._update();
  27907. }
  27908. };
  27909. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27910. this._renderPasses[renderPass._name] = renderPass;
  27911. this._linkParameters();
  27912. };
  27913. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27914. delete this._renderPasses[renderPass._name];
  27915. this._linkParameters();
  27916. };
  27917. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27918. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27919. this._linkParameters();
  27920. };
  27921. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27922. for (var renderPassName in this._renderPasses) {
  27923. if (renderPassName === passName) {
  27924. return this._renderPasses[passName];
  27925. }
  27926. }
  27927. };
  27928. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27929. this._renderPasses = {};
  27930. this._linkParameters();
  27931. };
  27932. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27933. var cameraKey;
  27934. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27935. for (var i = 0; i < _cam.length; i++) {
  27936. var camera = _cam[i];
  27937. var cameraName = camera.name;
  27938. if (this._singleInstance) {
  27939. cameraKey = 0;
  27940. }
  27941. else {
  27942. cameraKey = cameraName;
  27943. }
  27944. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27945. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27946. if (!this._indicesForCamera[cameraName]) {
  27947. this._indicesForCamera[cameraName] = [];
  27948. }
  27949. this._indicesForCamera[cameraName].push(index);
  27950. if (this._cameras.indexOf(camera) === -1) {
  27951. this._cameras[cameraName] = camera;
  27952. }
  27953. for (var passName in this._renderPasses) {
  27954. this._renderPasses[passName]._incRefCount();
  27955. }
  27956. }
  27957. this._linkParameters();
  27958. };
  27959. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27960. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27961. for (var i = 0; i < _cam.length; i++) {
  27962. var camera = _cam[i];
  27963. var cameraName = camera.name;
  27964. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27965. var index = this._cameras.indexOf(cameraName);
  27966. this._indicesForCamera.splice(index, 1);
  27967. this._cameras.splice(index, 1);
  27968. for (var passName in this._renderPasses) {
  27969. this._renderPasses[passName]._decRefCount();
  27970. }
  27971. }
  27972. };
  27973. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27974. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27975. for (var i = 0; i < _cam.length; i++) {
  27976. var camera = _cam[i];
  27977. var cameraName = camera.name;
  27978. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27979. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27980. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27981. }
  27982. }
  27983. for (var passName in this._renderPasses) {
  27984. this._renderPasses[passName]._incRefCount();
  27985. }
  27986. }
  27987. };
  27988. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27989. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27990. for (var i = 0; i < _cam.length; i++) {
  27991. var camera = _cam[i];
  27992. var cameraName = camera.Name;
  27993. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27994. for (var passName in this._renderPasses) {
  27995. this._renderPasses[passName]._decRefCount();
  27996. }
  27997. }
  27998. };
  27999. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  28000. if (this._singleInstance) {
  28001. return this._postProcesses[0];
  28002. }
  28003. else {
  28004. return this._postProcesses[camera.name];
  28005. }
  28006. };
  28007. PostProcessRenderEffect.prototype._linkParameters = function () {
  28008. var _this = this;
  28009. for (var index in this._postProcesses) {
  28010. if (this.applyParameters) {
  28011. this.applyParameters(this._postProcesses[index]);
  28012. }
  28013. this._postProcesses[index].onBeforeRender = function (effect) {
  28014. _this._linkTextures(effect);
  28015. };
  28016. }
  28017. };
  28018. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  28019. for (var renderPassName in this._renderPasses) {
  28020. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  28021. }
  28022. for (var renderEffectName in this._renderEffectAsPasses) {
  28023. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  28024. }
  28025. };
  28026. return PostProcessRenderEffect;
  28027. })();
  28028. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  28029. })(BABYLON || (BABYLON = {}));
  28030. var BABYLON;
  28031. (function (BABYLON) {
  28032. var PostProcessRenderPipeline = (function () {
  28033. function PostProcessRenderPipeline(engine, name) {
  28034. this._engine = engine;
  28035. this._name = name;
  28036. this._renderEffects = {};
  28037. this._renderEffectsForIsolatedPass = {};
  28038. this._cameras = [];
  28039. }
  28040. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  28041. this._renderEffects[renderEffect._name] = renderEffect;
  28042. };
  28043. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  28044. var renderEffects = this._renderEffects[renderEffectName];
  28045. if (!renderEffects) {
  28046. return;
  28047. }
  28048. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28049. };
  28050. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  28051. var renderEffects = this._renderEffects[renderEffectName];
  28052. if (!renderEffects) {
  28053. return;
  28054. }
  28055. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  28056. };
  28057. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  28058. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28059. var indicesToDelete = [];
  28060. for (var i = 0; i < _cam.length; i++) {
  28061. var camera = _cam[i];
  28062. var cameraName = camera.name;
  28063. if (this._cameras.indexOf(camera) === -1) {
  28064. this._cameras[cameraName] = camera;
  28065. }
  28066. else if (unique) {
  28067. indicesToDelete.push(i);
  28068. }
  28069. }
  28070. for (var i = 0; i < indicesToDelete.length; i++) {
  28071. cameras.splice(indicesToDelete[i], 1);
  28072. }
  28073. for (var renderEffectName in this._renderEffects) {
  28074. this._renderEffects[renderEffectName]._attachCameras(_cam);
  28075. }
  28076. };
  28077. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  28078. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28079. for (var renderEffectName in this._renderEffects) {
  28080. this._renderEffects[renderEffectName]._detachCameras(_cam);
  28081. }
  28082. for (var i = 0; i < _cam.length; i++) {
  28083. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  28084. }
  28085. };
  28086. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  28087. var _this = this;
  28088. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28089. var pass = null;
  28090. for (var renderEffectName in this._renderEffects) {
  28091. pass = this._renderEffects[renderEffectName].getPass(passName);
  28092. if (pass != null) {
  28093. break;
  28094. }
  28095. }
  28096. if (pass === null) {
  28097. return;
  28098. }
  28099. for (var renderEffectName in this._renderEffects) {
  28100. this._renderEffects[renderEffectName]._disable(_cam);
  28101. }
  28102. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  28103. for (var i = 0; i < _cam.length; i++) {
  28104. var camera = _cam[i];
  28105. var cameraName = camera.name;
  28106. 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); });
  28107. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  28108. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  28109. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  28110. }
  28111. };
  28112. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  28113. var _this = this;
  28114. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  28115. for (var i = 0; i < _cam.length; i++) {
  28116. var camera = _cam[i];
  28117. var cameraName = camera.name;
  28118. 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); });
  28119. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  28120. }
  28121. for (var renderEffectName in this._renderEffects) {
  28122. this._renderEffects[renderEffectName]._enable(_cam);
  28123. }
  28124. };
  28125. PostProcessRenderPipeline.prototype._update = function () {
  28126. for (var renderEffectName in this._renderEffects) {
  28127. this._renderEffects[renderEffectName]._update();
  28128. }
  28129. for (var i = 0; i < this._cameras.length; i++) {
  28130. var cameraName = this._cameras[i].name;
  28131. if (this._renderEffectsForIsolatedPass[cameraName]) {
  28132. this._renderEffectsForIsolatedPass[cameraName]._update();
  28133. }
  28134. }
  28135. };
  28136. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  28137. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  28138. return PostProcessRenderPipeline;
  28139. })();
  28140. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  28141. })(BABYLON || (BABYLON = {}));
  28142. var BABYLON;
  28143. (function (BABYLON) {
  28144. var PostProcessRenderPipelineManager = (function () {
  28145. function PostProcessRenderPipelineManager() {
  28146. this._renderPipelines = {};
  28147. }
  28148. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  28149. this._renderPipelines[renderPipeline._name] = renderPipeline;
  28150. };
  28151. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  28152. var renderPipeline = this._renderPipelines[renderPipelineName];
  28153. if (!renderPipeline) {
  28154. return;
  28155. }
  28156. renderPipeline._attachCameras(cameras, unique);
  28157. };
  28158. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  28159. var renderPipeline = this._renderPipelines[renderPipelineName];
  28160. if (!renderPipeline) {
  28161. return;
  28162. }
  28163. renderPipeline._detachCameras(cameras);
  28164. };
  28165. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28166. var renderPipeline = this._renderPipelines[renderPipelineName];
  28167. if (!renderPipeline) {
  28168. return;
  28169. }
  28170. renderPipeline._enableEffect(renderEffectName, cameras);
  28171. };
  28172. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  28173. var renderPipeline = this._renderPipelines[renderPipelineName];
  28174. if (!renderPipeline) {
  28175. return;
  28176. }
  28177. renderPipeline._disableEffect(renderEffectName, cameras);
  28178. };
  28179. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  28180. var renderPipeline = this._renderPipelines[renderPipelineName];
  28181. if (!renderPipeline) {
  28182. return;
  28183. }
  28184. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  28185. };
  28186. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  28187. var renderPipeline = this._renderPipelines[renderPipelineName];
  28188. if (!renderPipeline) {
  28189. return;
  28190. }
  28191. renderPipeline._disableDisplayOnlyPass(cameras);
  28192. };
  28193. PostProcessRenderPipelineManager.prototype.update = function () {
  28194. for (var renderPipelineName in this._renderPipelines) {
  28195. this._renderPipelines[renderPipelineName]._update();
  28196. }
  28197. };
  28198. return PostProcessRenderPipelineManager;
  28199. })();
  28200. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  28201. })(BABYLON || (BABYLON = {}));
  28202. var BABYLON;
  28203. (function (BABYLON) {
  28204. var DisplayPassPostProcess = (function (_super) {
  28205. __extends(DisplayPassPostProcess, _super);
  28206. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28207. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28208. }
  28209. return DisplayPassPostProcess;
  28210. })(BABYLON.PostProcess);
  28211. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28212. })(BABYLON || (BABYLON = {}));
  28213. var BABYLON;
  28214. (function (BABYLON) {
  28215. var BoundingBoxRenderer = (function () {
  28216. function BoundingBoxRenderer(scene) {
  28217. this.frontColor = new BABYLON.Color3(1, 1, 1);
  28218. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  28219. this.showBackLines = true;
  28220. this.renderList = new BABYLON.SmartArray(32);
  28221. this._scene = scene;
  28222. }
  28223. BoundingBoxRenderer.prototype._prepareRessources = function () {
  28224. if (this._colorShader) {
  28225. return;
  28226. }
  28227. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  28228. attributes: ["position"],
  28229. uniforms: ["worldViewProjection", "color"]
  28230. });
  28231. var engine = this._scene.getEngine();
  28232. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  28233. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  28234. 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]);
  28235. };
  28236. BoundingBoxRenderer.prototype.reset = function () {
  28237. this.renderList.reset();
  28238. };
  28239. BoundingBoxRenderer.prototype.render = function () {
  28240. if (this.renderList.length === 0) {
  28241. return;
  28242. }
  28243. this._prepareRessources();
  28244. if (!this._colorShader.isReady()) {
  28245. return;
  28246. }
  28247. var engine = this._scene.getEngine();
  28248. engine.setDepthWrite(false);
  28249. this._colorShader._preBind();
  28250. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  28251. var boundingBox = this.renderList.data[boundingBoxIndex];
  28252. var min = boundingBox.minimum;
  28253. var max = boundingBox.maximum;
  28254. var diff = max.subtract(min);
  28255. var median = min.add(diff.scale(0.5));
  28256. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  28257. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  28258. .multiply(boundingBox.getWorldMatrix());
  28259. // VBOs
  28260. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  28261. if (this.showBackLines) {
  28262. // Back
  28263. engine.setDepthFunctionToGreaterOrEqual();
  28264. this._scene.resetCachedMaterial();
  28265. this._colorShader.setColor4("color", this.backColor.toColor4());
  28266. this._colorShader.bind(worldMatrix);
  28267. // Draw order
  28268. engine.draw(false, 0, 24);
  28269. }
  28270. // Front
  28271. engine.setDepthFunctionToLess();
  28272. this._scene.resetCachedMaterial();
  28273. this._colorShader.setColor4("color", this.frontColor.toColor4());
  28274. this._colorShader.bind(worldMatrix);
  28275. // Draw order
  28276. engine.draw(false, 0, 24);
  28277. }
  28278. this._colorShader.unbind();
  28279. engine.setDepthFunctionToLessOrEqual();
  28280. engine.setDepthWrite(true);
  28281. };
  28282. BoundingBoxRenderer.prototype.dispose = function () {
  28283. if (!this._colorShader) {
  28284. return;
  28285. }
  28286. this._colorShader.dispose();
  28287. this._vb.dispose();
  28288. this._scene.getEngine()._releaseBuffer(this._ib);
  28289. };
  28290. return BoundingBoxRenderer;
  28291. })();
  28292. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  28293. })(BABYLON || (BABYLON = {}));
  28294. var BABYLON;
  28295. (function (BABYLON) {
  28296. var Condition = (function () {
  28297. function Condition(actionManager) {
  28298. this._actionManager = actionManager;
  28299. }
  28300. Condition.prototype.isValid = function () {
  28301. return true;
  28302. };
  28303. Condition.prototype._getProperty = function (propertyPath) {
  28304. return this._actionManager._getProperty(propertyPath);
  28305. };
  28306. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  28307. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28308. };
  28309. return Condition;
  28310. })();
  28311. BABYLON.Condition = Condition;
  28312. var ValueCondition = (function (_super) {
  28313. __extends(ValueCondition, _super);
  28314. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  28315. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  28316. _super.call(this, actionManager);
  28317. this.propertyPath = propertyPath;
  28318. this.value = value;
  28319. this.operator = operator;
  28320. this._target = this._getEffectiveTarget(target, this.propertyPath);
  28321. this._property = this._getProperty(this.propertyPath);
  28322. }
  28323. Object.defineProperty(ValueCondition, "IsEqual", {
  28324. get: function () {
  28325. return ValueCondition._IsEqual;
  28326. },
  28327. enumerable: true,
  28328. configurable: true
  28329. });
  28330. Object.defineProperty(ValueCondition, "IsDifferent", {
  28331. get: function () {
  28332. return ValueCondition._IsDifferent;
  28333. },
  28334. enumerable: true,
  28335. configurable: true
  28336. });
  28337. Object.defineProperty(ValueCondition, "IsGreater", {
  28338. get: function () {
  28339. return ValueCondition._IsGreater;
  28340. },
  28341. enumerable: true,
  28342. configurable: true
  28343. });
  28344. Object.defineProperty(ValueCondition, "IsLesser", {
  28345. get: function () {
  28346. return ValueCondition._IsLesser;
  28347. },
  28348. enumerable: true,
  28349. configurable: true
  28350. });
  28351. // Methods
  28352. ValueCondition.prototype.isValid = function () {
  28353. switch (this.operator) {
  28354. case ValueCondition.IsGreater:
  28355. return this._target[this._property] > this.value;
  28356. case ValueCondition.IsLesser:
  28357. return this._target[this._property] < this.value;
  28358. case ValueCondition.IsEqual:
  28359. case ValueCondition.IsDifferent:
  28360. var check;
  28361. if (this.value.equals) {
  28362. check = this.value.equals(this._target[this._property]);
  28363. }
  28364. else {
  28365. check = this.value === this._target[this._property];
  28366. }
  28367. return this.operator === ValueCondition.IsEqual ? check : !check;
  28368. }
  28369. return false;
  28370. };
  28371. // Statics
  28372. ValueCondition._IsEqual = 0;
  28373. ValueCondition._IsDifferent = 1;
  28374. ValueCondition._IsGreater = 2;
  28375. ValueCondition._IsLesser = 3;
  28376. return ValueCondition;
  28377. })(Condition);
  28378. BABYLON.ValueCondition = ValueCondition;
  28379. var PredicateCondition = (function (_super) {
  28380. __extends(PredicateCondition, _super);
  28381. function PredicateCondition(actionManager, predicate) {
  28382. _super.call(this, actionManager);
  28383. this.predicate = predicate;
  28384. }
  28385. PredicateCondition.prototype.isValid = function () {
  28386. return this.predicate();
  28387. };
  28388. return PredicateCondition;
  28389. })(Condition);
  28390. BABYLON.PredicateCondition = PredicateCondition;
  28391. var StateCondition = (function (_super) {
  28392. __extends(StateCondition, _super);
  28393. function StateCondition(actionManager, target, value) {
  28394. _super.call(this, actionManager);
  28395. this.value = value;
  28396. this._target = target;
  28397. }
  28398. // Methods
  28399. StateCondition.prototype.isValid = function () {
  28400. return this._target.state === this.value;
  28401. };
  28402. return StateCondition;
  28403. })(Condition);
  28404. BABYLON.StateCondition = StateCondition;
  28405. })(BABYLON || (BABYLON = {}));
  28406. var BABYLON;
  28407. (function (BABYLON) {
  28408. var Action = (function () {
  28409. function Action(triggerOptions, condition) {
  28410. this.triggerOptions = triggerOptions;
  28411. if (triggerOptions.parameter) {
  28412. this.trigger = triggerOptions.trigger;
  28413. this._triggerParameter = triggerOptions.parameter;
  28414. }
  28415. else {
  28416. this.trigger = triggerOptions;
  28417. }
  28418. this._nextActiveAction = this;
  28419. this._condition = condition;
  28420. }
  28421. // Methods
  28422. Action.prototype._prepare = function () {
  28423. };
  28424. Action.prototype.getTriggerParameter = function () {
  28425. return this._triggerParameter;
  28426. };
  28427. Action.prototype._executeCurrent = function (evt) {
  28428. if (this._nextActiveAction._condition) {
  28429. var condition = this._nextActiveAction._condition;
  28430. var currentRenderId = this._actionManager.getScene().getRenderId();
  28431. // We cache the current evaluation for the current frame
  28432. if (condition._evaluationId === currentRenderId) {
  28433. if (!condition._currentResult) {
  28434. return;
  28435. }
  28436. }
  28437. else {
  28438. condition._evaluationId = currentRenderId;
  28439. if (!condition.isValid()) {
  28440. condition._currentResult = false;
  28441. return;
  28442. }
  28443. condition._currentResult = true;
  28444. }
  28445. }
  28446. this._nextActiveAction.execute(evt);
  28447. if (this._nextActiveAction._child) {
  28448. if (!this._nextActiveAction._child._actionManager) {
  28449. this._nextActiveAction._child._actionManager = this._actionManager;
  28450. }
  28451. this._nextActiveAction = this._nextActiveAction._child;
  28452. }
  28453. else {
  28454. this._nextActiveAction = this;
  28455. }
  28456. };
  28457. Action.prototype.execute = function (evt) {
  28458. };
  28459. Action.prototype.then = function (action) {
  28460. this._child = action;
  28461. action._actionManager = this._actionManager;
  28462. action._prepare();
  28463. return action;
  28464. };
  28465. Action.prototype._getProperty = function (propertyPath) {
  28466. return this._actionManager._getProperty(propertyPath);
  28467. };
  28468. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  28469. return this._actionManager._getEffectiveTarget(target, propertyPath);
  28470. };
  28471. return Action;
  28472. })();
  28473. BABYLON.Action = Action;
  28474. })(BABYLON || (BABYLON = {}));
  28475. var BABYLON;
  28476. (function (BABYLON) {
  28477. /**
  28478. * ActionEvent is the event beint sent when an action is triggered.
  28479. */
  28480. var ActionEvent = (function () {
  28481. /**
  28482. * @constructor
  28483. * @param source The mesh that triggered the action.
  28484. * @param pointerX the X mouse cursor position at the time of the event
  28485. * @param pointerY the Y mouse cursor position at the time of the event
  28486. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  28487. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  28488. */
  28489. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  28490. this.source = source;
  28491. this.pointerX = pointerX;
  28492. this.pointerY = pointerY;
  28493. this.meshUnderPointer = meshUnderPointer;
  28494. this.sourceEvent = sourceEvent;
  28495. this.additionalData = additionalData;
  28496. }
  28497. /**
  28498. * Helper function to auto-create an ActionEvent from a source mesh.
  28499. * @param source the source mesh that triggered the event
  28500. * @param evt {Event} The original (browser) event
  28501. */
  28502. ActionEvent.CreateNew = function (source, evt, additionalData) {
  28503. var scene = source.getScene();
  28504. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  28505. };
  28506. /**
  28507. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  28508. * @param scene the scene where the event occurred
  28509. * @param evt {Event} The original (browser) event
  28510. */
  28511. ActionEvent.CreateNewFromScene = function (scene, evt) {
  28512. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  28513. };
  28514. return ActionEvent;
  28515. })();
  28516. BABYLON.ActionEvent = ActionEvent;
  28517. /**
  28518. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  28519. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  28520. */
  28521. var ActionManager = (function () {
  28522. function ActionManager(scene) {
  28523. // Members
  28524. this.actions = new Array();
  28525. this._scene = scene;
  28526. scene._actionManagers.push(this);
  28527. }
  28528. Object.defineProperty(ActionManager, "NothingTrigger", {
  28529. get: function () {
  28530. return ActionManager._NothingTrigger;
  28531. },
  28532. enumerable: true,
  28533. configurable: true
  28534. });
  28535. Object.defineProperty(ActionManager, "OnPickTrigger", {
  28536. get: function () {
  28537. return ActionManager._OnPickTrigger;
  28538. },
  28539. enumerable: true,
  28540. configurable: true
  28541. });
  28542. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  28543. get: function () {
  28544. return ActionManager._OnLeftPickTrigger;
  28545. },
  28546. enumerable: true,
  28547. configurable: true
  28548. });
  28549. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  28550. get: function () {
  28551. return ActionManager._OnRightPickTrigger;
  28552. },
  28553. enumerable: true,
  28554. configurable: true
  28555. });
  28556. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  28557. get: function () {
  28558. return ActionManager._OnCenterPickTrigger;
  28559. },
  28560. enumerable: true,
  28561. configurable: true
  28562. });
  28563. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  28564. get: function () {
  28565. return ActionManager._OnPointerOverTrigger;
  28566. },
  28567. enumerable: true,
  28568. configurable: true
  28569. });
  28570. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  28571. get: function () {
  28572. return ActionManager._OnPointerOutTrigger;
  28573. },
  28574. enumerable: true,
  28575. configurable: true
  28576. });
  28577. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  28578. get: function () {
  28579. return ActionManager._OnEveryFrameTrigger;
  28580. },
  28581. enumerable: true,
  28582. configurable: true
  28583. });
  28584. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  28585. get: function () {
  28586. return ActionManager._OnIntersectionEnterTrigger;
  28587. },
  28588. enumerable: true,
  28589. configurable: true
  28590. });
  28591. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  28592. get: function () {
  28593. return ActionManager._OnIntersectionExitTrigger;
  28594. },
  28595. enumerable: true,
  28596. configurable: true
  28597. });
  28598. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  28599. get: function () {
  28600. return ActionManager._OnKeyDownTrigger;
  28601. },
  28602. enumerable: true,
  28603. configurable: true
  28604. });
  28605. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  28606. get: function () {
  28607. return ActionManager._OnKeyUpTrigger;
  28608. },
  28609. enumerable: true,
  28610. configurable: true
  28611. });
  28612. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  28613. get: function () {
  28614. return ActionManager._OnPickUpTrigger;
  28615. },
  28616. enumerable: true,
  28617. configurable: true
  28618. });
  28619. // Methods
  28620. ActionManager.prototype.dispose = function () {
  28621. var index = this._scene._actionManagers.indexOf(this);
  28622. if (index > -1) {
  28623. this._scene._actionManagers.splice(index, 1);
  28624. }
  28625. };
  28626. ActionManager.prototype.getScene = function () {
  28627. return this._scene;
  28628. };
  28629. /**
  28630. * Does this action manager handles actions of any of the given triggers
  28631. * @param {number[]} triggers - the triggers to be tested
  28632. * @return {boolean} whether one (or more) of the triggers is handeled
  28633. */
  28634. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  28635. for (var index = 0; index < this.actions.length; index++) {
  28636. var action = this.actions[index];
  28637. if (triggers.indexOf(action.trigger) > -1) {
  28638. return true;
  28639. }
  28640. }
  28641. return false;
  28642. };
  28643. /**
  28644. * Does this action manager handles actions of a given trigger
  28645. * @param {number} trigger - the trigger to be tested
  28646. * @return {boolean} whether the trigger is handeled
  28647. */
  28648. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  28649. for (var index = 0; index < this.actions.length; index++) {
  28650. var action = this.actions[index];
  28651. if (action.trigger === trigger) {
  28652. return true;
  28653. }
  28654. }
  28655. return false;
  28656. };
  28657. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28658. /**
  28659. * Does this action manager has pointer triggers
  28660. * @return {boolean} whether or not it has pointer triggers
  28661. */
  28662. get: function () {
  28663. for (var index = 0; index < this.actions.length; index++) {
  28664. var action = this.actions[index];
  28665. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28666. return true;
  28667. }
  28668. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28669. return true;
  28670. }
  28671. }
  28672. return false;
  28673. },
  28674. enumerable: true,
  28675. configurable: true
  28676. });
  28677. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28678. /**
  28679. * Does this action manager has pick triggers
  28680. * @return {boolean} whether or not it has pick triggers
  28681. */
  28682. get: function () {
  28683. for (var index = 0; index < this.actions.length; index++) {
  28684. var action = this.actions[index];
  28685. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28686. return true;
  28687. }
  28688. }
  28689. return false;
  28690. },
  28691. enumerable: true,
  28692. configurable: true
  28693. });
  28694. /**
  28695. * Registers an action to this action manager
  28696. * @param {BABYLON.Action} action - the action to be registered
  28697. * @return {BABYLON.Action} the action amended (prepared) after registration
  28698. */
  28699. ActionManager.prototype.registerAction = function (action) {
  28700. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28701. if (this.getScene().actionManager !== this) {
  28702. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28703. return null;
  28704. }
  28705. }
  28706. this.actions.push(action);
  28707. action._actionManager = this;
  28708. action._prepare();
  28709. return action;
  28710. };
  28711. /**
  28712. * Process a specific trigger
  28713. * @param {number} trigger - the trigger to process
  28714. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28715. */
  28716. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28717. for (var index = 0; index < this.actions.length; index++) {
  28718. var action = this.actions[index];
  28719. if (action.trigger === trigger) {
  28720. if (trigger === ActionManager.OnKeyUpTrigger
  28721. || trigger === ActionManager.OnKeyDownTrigger) {
  28722. var parameter = action.getTriggerParameter();
  28723. if (parameter) {
  28724. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28725. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28726. if (actualkey !== parameter.toLowerCase()) {
  28727. continue;
  28728. }
  28729. }
  28730. }
  28731. action._executeCurrent(evt);
  28732. }
  28733. }
  28734. };
  28735. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28736. var properties = propertyPath.split(".");
  28737. for (var index = 0; index < properties.length - 1; index++) {
  28738. target = target[properties[index]];
  28739. }
  28740. return target;
  28741. };
  28742. ActionManager.prototype._getProperty = function (propertyPath) {
  28743. var properties = propertyPath.split(".");
  28744. return properties[properties.length - 1];
  28745. };
  28746. // Statics
  28747. ActionManager._NothingTrigger = 0;
  28748. ActionManager._OnPickTrigger = 1;
  28749. ActionManager._OnLeftPickTrigger = 2;
  28750. ActionManager._OnRightPickTrigger = 3;
  28751. ActionManager._OnCenterPickTrigger = 4;
  28752. ActionManager._OnPointerOverTrigger = 5;
  28753. ActionManager._OnPointerOutTrigger = 6;
  28754. ActionManager._OnEveryFrameTrigger = 7;
  28755. ActionManager._OnIntersectionEnterTrigger = 8;
  28756. ActionManager._OnIntersectionExitTrigger = 9;
  28757. ActionManager._OnKeyDownTrigger = 10;
  28758. ActionManager._OnKeyUpTrigger = 11;
  28759. ActionManager._OnPickUpTrigger = 12;
  28760. return ActionManager;
  28761. })();
  28762. BABYLON.ActionManager = ActionManager;
  28763. })(BABYLON || (BABYLON = {}));
  28764. var BABYLON;
  28765. (function (BABYLON) {
  28766. var InterpolateValueAction = (function (_super) {
  28767. __extends(InterpolateValueAction, _super);
  28768. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  28769. if (duration === void 0) { duration = 1000; }
  28770. _super.call(this, triggerOptions, condition);
  28771. this.propertyPath = propertyPath;
  28772. this.value = value;
  28773. this.duration = duration;
  28774. this.stopOtherAnimations = stopOtherAnimations;
  28775. this.onInterpolationDone = onInterpolationDone;
  28776. this._target = target;
  28777. }
  28778. InterpolateValueAction.prototype._prepare = function () {
  28779. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28780. this._property = this._getProperty(this.propertyPath);
  28781. };
  28782. InterpolateValueAction.prototype.execute = function () {
  28783. var scene = this._actionManager.getScene();
  28784. var keys = [
  28785. {
  28786. frame: 0,
  28787. value: this._target[this._property]
  28788. }, {
  28789. frame: 100,
  28790. value: this.value
  28791. }
  28792. ];
  28793. var dataType;
  28794. if (typeof this.value === "number") {
  28795. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28796. }
  28797. else if (this.value instanceof BABYLON.Color3) {
  28798. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28799. }
  28800. else if (this.value instanceof BABYLON.Vector3) {
  28801. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28802. }
  28803. else if (this.value instanceof BABYLON.Matrix) {
  28804. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28805. }
  28806. else if (this.value instanceof BABYLON.Quaternion) {
  28807. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28808. }
  28809. else {
  28810. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28811. return;
  28812. }
  28813. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28814. animation.setKeys(keys);
  28815. if (this.stopOtherAnimations) {
  28816. scene.stopAnimation(this._target);
  28817. }
  28818. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  28819. };
  28820. return InterpolateValueAction;
  28821. })(BABYLON.Action);
  28822. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28823. })(BABYLON || (BABYLON = {}));
  28824. var BABYLON;
  28825. (function (BABYLON) {
  28826. var SwitchBooleanAction = (function (_super) {
  28827. __extends(SwitchBooleanAction, _super);
  28828. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28829. _super.call(this, triggerOptions, condition);
  28830. this.propertyPath = propertyPath;
  28831. this._target = target;
  28832. }
  28833. SwitchBooleanAction.prototype._prepare = function () {
  28834. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28835. this._property = this._getProperty(this.propertyPath);
  28836. };
  28837. SwitchBooleanAction.prototype.execute = function () {
  28838. this._target[this._property] = !this._target[this._property];
  28839. };
  28840. return SwitchBooleanAction;
  28841. })(BABYLON.Action);
  28842. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28843. var SetStateAction = (function (_super) {
  28844. __extends(SetStateAction, _super);
  28845. function SetStateAction(triggerOptions, target, value, condition) {
  28846. _super.call(this, triggerOptions, condition);
  28847. this.value = value;
  28848. this._target = target;
  28849. }
  28850. SetStateAction.prototype.execute = function () {
  28851. this._target.state = this.value;
  28852. };
  28853. return SetStateAction;
  28854. })(BABYLON.Action);
  28855. BABYLON.SetStateAction = SetStateAction;
  28856. var SetValueAction = (function (_super) {
  28857. __extends(SetValueAction, _super);
  28858. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28859. _super.call(this, triggerOptions, condition);
  28860. this.propertyPath = propertyPath;
  28861. this.value = value;
  28862. this._target = target;
  28863. }
  28864. SetValueAction.prototype._prepare = function () {
  28865. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28866. this._property = this._getProperty(this.propertyPath);
  28867. };
  28868. SetValueAction.prototype.execute = function () {
  28869. this._target[this._property] = this.value;
  28870. };
  28871. return SetValueAction;
  28872. })(BABYLON.Action);
  28873. BABYLON.SetValueAction = SetValueAction;
  28874. var IncrementValueAction = (function (_super) {
  28875. __extends(IncrementValueAction, _super);
  28876. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28877. _super.call(this, triggerOptions, condition);
  28878. this.propertyPath = propertyPath;
  28879. this.value = value;
  28880. this._target = target;
  28881. }
  28882. IncrementValueAction.prototype._prepare = function () {
  28883. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28884. this._property = this._getProperty(this.propertyPath);
  28885. if (typeof this._target[this._property] !== "number") {
  28886. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28887. }
  28888. };
  28889. IncrementValueAction.prototype.execute = function () {
  28890. this._target[this._property] += this.value;
  28891. };
  28892. return IncrementValueAction;
  28893. })(BABYLON.Action);
  28894. BABYLON.IncrementValueAction = IncrementValueAction;
  28895. var PlayAnimationAction = (function (_super) {
  28896. __extends(PlayAnimationAction, _super);
  28897. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28898. _super.call(this, triggerOptions, condition);
  28899. this.from = from;
  28900. this.to = to;
  28901. this.loop = loop;
  28902. this._target = target;
  28903. }
  28904. PlayAnimationAction.prototype._prepare = function () {
  28905. };
  28906. PlayAnimationAction.prototype.execute = function () {
  28907. var scene = this._actionManager.getScene();
  28908. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28909. };
  28910. return PlayAnimationAction;
  28911. })(BABYLON.Action);
  28912. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28913. var StopAnimationAction = (function (_super) {
  28914. __extends(StopAnimationAction, _super);
  28915. function StopAnimationAction(triggerOptions, target, condition) {
  28916. _super.call(this, triggerOptions, condition);
  28917. this._target = target;
  28918. }
  28919. StopAnimationAction.prototype._prepare = function () {
  28920. };
  28921. StopAnimationAction.prototype.execute = function () {
  28922. var scene = this._actionManager.getScene();
  28923. scene.stopAnimation(this._target);
  28924. };
  28925. return StopAnimationAction;
  28926. })(BABYLON.Action);
  28927. BABYLON.StopAnimationAction = StopAnimationAction;
  28928. var DoNothingAction = (function (_super) {
  28929. __extends(DoNothingAction, _super);
  28930. function DoNothingAction(triggerOptions, condition) {
  28931. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28932. _super.call(this, triggerOptions, condition);
  28933. }
  28934. DoNothingAction.prototype.execute = function () {
  28935. };
  28936. return DoNothingAction;
  28937. })(BABYLON.Action);
  28938. BABYLON.DoNothingAction = DoNothingAction;
  28939. var CombineAction = (function (_super) {
  28940. __extends(CombineAction, _super);
  28941. function CombineAction(triggerOptions, children, condition) {
  28942. _super.call(this, triggerOptions, condition);
  28943. this.children = children;
  28944. }
  28945. CombineAction.prototype._prepare = function () {
  28946. for (var index = 0; index < this.children.length; index++) {
  28947. this.children[index]._actionManager = this._actionManager;
  28948. this.children[index]._prepare();
  28949. }
  28950. };
  28951. CombineAction.prototype.execute = function (evt) {
  28952. for (var index = 0; index < this.children.length; index++) {
  28953. this.children[index].execute(evt);
  28954. }
  28955. };
  28956. return CombineAction;
  28957. })(BABYLON.Action);
  28958. BABYLON.CombineAction = CombineAction;
  28959. var ExecuteCodeAction = (function (_super) {
  28960. __extends(ExecuteCodeAction, _super);
  28961. function ExecuteCodeAction(triggerOptions, func, condition) {
  28962. _super.call(this, triggerOptions, condition);
  28963. this.func = func;
  28964. }
  28965. ExecuteCodeAction.prototype.execute = function (evt) {
  28966. this.func(evt);
  28967. };
  28968. return ExecuteCodeAction;
  28969. })(BABYLON.Action);
  28970. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28971. var SetParentAction = (function (_super) {
  28972. __extends(SetParentAction, _super);
  28973. function SetParentAction(triggerOptions, target, parent, condition) {
  28974. _super.call(this, triggerOptions, condition);
  28975. this._target = target;
  28976. this._parent = parent;
  28977. }
  28978. SetParentAction.prototype._prepare = function () {
  28979. };
  28980. SetParentAction.prototype.execute = function () {
  28981. if (this._target.parent === this._parent) {
  28982. return;
  28983. }
  28984. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28985. invertParentWorldMatrix.invert();
  28986. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28987. this._target.parent = this._parent;
  28988. };
  28989. return SetParentAction;
  28990. })(BABYLON.Action);
  28991. BABYLON.SetParentAction = SetParentAction;
  28992. var PlaySoundAction = (function (_super) {
  28993. __extends(PlaySoundAction, _super);
  28994. function PlaySoundAction(triggerOptions, sound, condition) {
  28995. _super.call(this, triggerOptions, condition);
  28996. this._sound = sound;
  28997. }
  28998. PlaySoundAction.prototype._prepare = function () {
  28999. };
  29000. PlaySoundAction.prototype.execute = function () {
  29001. if (this._sound !== undefined)
  29002. this._sound.play();
  29003. };
  29004. return PlaySoundAction;
  29005. })(BABYLON.Action);
  29006. BABYLON.PlaySoundAction = PlaySoundAction;
  29007. var StopSoundAction = (function (_super) {
  29008. __extends(StopSoundAction, _super);
  29009. function StopSoundAction(triggerOptions, sound, condition) {
  29010. _super.call(this, triggerOptions, condition);
  29011. this._sound = sound;
  29012. }
  29013. StopSoundAction.prototype._prepare = function () {
  29014. };
  29015. StopSoundAction.prototype.execute = function () {
  29016. if (this._sound !== undefined)
  29017. this._sound.stop();
  29018. };
  29019. return StopSoundAction;
  29020. })(BABYLON.Action);
  29021. BABYLON.StopSoundAction = StopSoundAction;
  29022. })(BABYLON || (BABYLON = {}));
  29023. var BABYLON;
  29024. (function (BABYLON) {
  29025. var Geometry = (function () {
  29026. function Geometry(id, scene, vertexData, updatable, mesh) {
  29027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29028. this._totalVertices = 0;
  29029. this._indices = [];
  29030. this._isDisposed = false;
  29031. this.id = id;
  29032. this._engine = scene.getEngine();
  29033. this._meshes = [];
  29034. this._scene = scene;
  29035. // vertexData
  29036. if (vertexData) {
  29037. this.setAllVerticesData(vertexData, updatable);
  29038. }
  29039. else {
  29040. this._totalVertices = 0;
  29041. this._indices = [];
  29042. }
  29043. // applyToMesh
  29044. if (mesh) {
  29045. this.applyToMesh(mesh);
  29046. mesh.computeWorldMatrix(true);
  29047. }
  29048. }
  29049. Geometry.prototype.getScene = function () {
  29050. return this._scene;
  29051. };
  29052. Geometry.prototype.getEngine = function () {
  29053. return this._engine;
  29054. };
  29055. Geometry.prototype.isReady = function () {
  29056. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29057. };
  29058. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29059. vertexData.applyToGeometry(this, updatable);
  29060. this.notifyUpdate();
  29061. };
  29062. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29063. this._vertexBuffers = this._vertexBuffers || {};
  29064. if (this._vertexBuffers[kind]) {
  29065. this._vertexBuffers[kind].dispose();
  29066. }
  29067. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29068. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29069. stride = this._vertexBuffers[kind].getStrideSize();
  29070. this._totalVertices = data.length / stride;
  29071. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29072. var meshes = this._meshes;
  29073. var numOfMeshes = meshes.length;
  29074. for (var index = 0; index < numOfMeshes; index++) {
  29075. var mesh = meshes[index];
  29076. mesh._resetPointsArrayCache();
  29077. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29078. mesh._createGlobalSubMesh();
  29079. mesh.computeWorldMatrix(true);
  29080. }
  29081. }
  29082. this.notifyUpdate(kind);
  29083. };
  29084. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29085. var vertexBuffer = this.getVertexBuffer(kind);
  29086. if (!vertexBuffer) {
  29087. return;
  29088. }
  29089. vertexBuffer.updateDirectly(data, offset);
  29090. this.notifyUpdate(kind);
  29091. };
  29092. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29093. var vertexBuffer = this.getVertexBuffer(kind);
  29094. if (!vertexBuffer) {
  29095. return;
  29096. }
  29097. vertexBuffer.update(data);
  29098. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29099. var extend;
  29100. var stride = vertexBuffer.getStrideSize();
  29101. this._totalVertices = data.length / stride;
  29102. if (updateExtends) {
  29103. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  29104. }
  29105. var meshes = this._meshes;
  29106. var numOfMeshes = meshes.length;
  29107. for (var index = 0; index < numOfMeshes; index++) {
  29108. var mesh = meshes[index];
  29109. mesh._resetPointsArrayCache();
  29110. if (updateExtends) {
  29111. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29112. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29113. var subMesh = mesh.subMeshes[subIndex];
  29114. subMesh.refreshBoundingInfo();
  29115. }
  29116. }
  29117. }
  29118. }
  29119. this.notifyUpdate(kind);
  29120. };
  29121. Geometry.prototype.getTotalVertices = function () {
  29122. if (!this.isReady()) {
  29123. return 0;
  29124. }
  29125. return this._totalVertices;
  29126. };
  29127. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  29128. var vertexBuffer = this.getVertexBuffer(kind);
  29129. if (!vertexBuffer) {
  29130. return null;
  29131. }
  29132. var orig = vertexBuffer.getData();
  29133. if (!copyWhenShared || this._meshes.length === 1) {
  29134. return orig;
  29135. }
  29136. else {
  29137. var len = orig.length;
  29138. var copy = [];
  29139. for (var i = 0; i < len; i++) {
  29140. copy.push(orig[i]);
  29141. }
  29142. return copy;
  29143. }
  29144. };
  29145. Geometry.prototype.getVertexBuffer = function (kind) {
  29146. if (!this.isReady()) {
  29147. return null;
  29148. }
  29149. return this._vertexBuffers[kind];
  29150. };
  29151. Geometry.prototype.getVertexBuffers = function () {
  29152. if (!this.isReady()) {
  29153. return null;
  29154. }
  29155. return this._vertexBuffers;
  29156. };
  29157. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29158. if (!this._vertexBuffers) {
  29159. if (this._delayInfo) {
  29160. return this._delayInfo.indexOf(kind) !== -1;
  29161. }
  29162. return false;
  29163. }
  29164. return this._vertexBuffers[kind] !== undefined;
  29165. };
  29166. Geometry.prototype.getVerticesDataKinds = function () {
  29167. var result = [];
  29168. if (!this._vertexBuffers && this._delayInfo) {
  29169. for (var kind in this._delayInfo) {
  29170. result.push(kind);
  29171. }
  29172. }
  29173. else {
  29174. for (kind in this._vertexBuffers) {
  29175. result.push(kind);
  29176. }
  29177. }
  29178. return result;
  29179. };
  29180. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29181. if (this._indexBuffer) {
  29182. this._engine._releaseBuffer(this._indexBuffer);
  29183. }
  29184. this._indices = indices;
  29185. if (this._meshes.length !== 0 && this._indices) {
  29186. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29187. }
  29188. if (totalVertices !== undefined) {
  29189. this._totalVertices = totalVertices;
  29190. }
  29191. var meshes = this._meshes;
  29192. var numOfMeshes = meshes.length;
  29193. for (var index = 0; index < numOfMeshes; index++) {
  29194. meshes[index]._createGlobalSubMesh();
  29195. }
  29196. this.notifyUpdate();
  29197. };
  29198. Geometry.prototype.getTotalIndices = function () {
  29199. if (!this.isReady()) {
  29200. return 0;
  29201. }
  29202. return this._indices.length;
  29203. };
  29204. Geometry.prototype.getIndices = function (copyWhenShared) {
  29205. if (!this.isReady()) {
  29206. return null;
  29207. }
  29208. var orig = this._indices;
  29209. if (!copyWhenShared || this._meshes.length === 1) {
  29210. return orig;
  29211. }
  29212. else {
  29213. var len = orig.length;
  29214. var copy = [];
  29215. for (var i = 0; i < len; i++) {
  29216. copy.push(orig[i]);
  29217. }
  29218. return copy;
  29219. }
  29220. };
  29221. Geometry.prototype.getIndexBuffer = function () {
  29222. if (!this.isReady()) {
  29223. return null;
  29224. }
  29225. return this._indexBuffer;
  29226. };
  29227. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29228. var meshes = this._meshes;
  29229. var index = meshes.indexOf(mesh);
  29230. if (index === -1) {
  29231. return;
  29232. }
  29233. for (var kind in this._vertexBuffers) {
  29234. this._vertexBuffers[kind].dispose();
  29235. }
  29236. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  29237. this._indexBuffer = null;
  29238. }
  29239. meshes.splice(index, 1);
  29240. mesh._geometry = null;
  29241. if (meshes.length === 0 && shouldDispose) {
  29242. this.dispose();
  29243. }
  29244. };
  29245. Geometry.prototype.applyToMesh = function (mesh) {
  29246. if (mesh._geometry === this) {
  29247. return;
  29248. }
  29249. var previousGeometry = mesh._geometry;
  29250. if (previousGeometry) {
  29251. previousGeometry.releaseForMesh(mesh);
  29252. }
  29253. var meshes = this._meshes;
  29254. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29255. mesh._geometry = this;
  29256. this._scene.pushGeometry(this);
  29257. meshes.push(mesh);
  29258. if (this.isReady()) {
  29259. this._applyToMesh(mesh);
  29260. }
  29261. else {
  29262. mesh._boundingInfo = this._boundingInfo;
  29263. }
  29264. };
  29265. Geometry.prototype._applyToMesh = function (mesh) {
  29266. var numOfMeshes = this._meshes.length;
  29267. // vertexBuffers
  29268. for (var kind in this._vertexBuffers) {
  29269. if (numOfMeshes === 1) {
  29270. this._vertexBuffers[kind].create();
  29271. }
  29272. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  29273. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29274. mesh._resetPointsArrayCache();
  29275. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  29276. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29277. mesh._createGlobalSubMesh();
  29278. //bounding info was just created again, world matrix should be applied again.
  29279. mesh._updateBoundingInfo();
  29280. }
  29281. }
  29282. // indexBuffer
  29283. if (numOfMeshes === 1 && this._indices) {
  29284. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29285. }
  29286. if (this._indexBuffer) {
  29287. this._indexBuffer.references = numOfMeshes;
  29288. }
  29289. };
  29290. Geometry.prototype.notifyUpdate = function (kind) {
  29291. if (this.onGeometryUpdated) {
  29292. this.onGeometryUpdated(this, kind);
  29293. }
  29294. };
  29295. Geometry.prototype.load = function (scene, onLoaded) {
  29296. var _this = this;
  29297. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29298. return;
  29299. }
  29300. if (this.isReady()) {
  29301. if (onLoaded) {
  29302. onLoaded();
  29303. }
  29304. return;
  29305. }
  29306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29307. scene._addPendingData(this);
  29308. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29309. _this._delayLoadingFunction(JSON.parse(data), _this);
  29310. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29311. _this._delayInfo = [];
  29312. scene._removePendingData(_this);
  29313. var meshes = _this._meshes;
  29314. var numOfMeshes = meshes.length;
  29315. for (var index = 0; index < numOfMeshes; index++) {
  29316. _this._applyToMesh(meshes[index]);
  29317. }
  29318. if (onLoaded) {
  29319. onLoaded();
  29320. }
  29321. }, function () { }, scene.database);
  29322. };
  29323. Geometry.prototype.isDisposed = function () {
  29324. return this._isDisposed;
  29325. };
  29326. Geometry.prototype.dispose = function () {
  29327. var meshes = this._meshes;
  29328. var numOfMeshes = meshes.length;
  29329. var index;
  29330. for (index = 0; index < numOfMeshes; index++) {
  29331. this.releaseForMesh(meshes[index]);
  29332. }
  29333. this._meshes = [];
  29334. for (var kind in this._vertexBuffers) {
  29335. this._vertexBuffers[kind].dispose();
  29336. }
  29337. this._vertexBuffers = [];
  29338. this._totalVertices = 0;
  29339. if (this._indexBuffer) {
  29340. this._engine._releaseBuffer(this._indexBuffer);
  29341. }
  29342. this._indexBuffer = null;
  29343. this._indices = [];
  29344. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29345. this.delayLoadingFile = null;
  29346. this._delayLoadingFunction = null;
  29347. this._delayInfo = [];
  29348. this._boundingInfo = null; // todo: .dispose()
  29349. this._scene.removeGeometry(this);
  29350. this._isDisposed = true;
  29351. };
  29352. Geometry.prototype.copy = function (id) {
  29353. var vertexData = new BABYLON.VertexData();
  29354. vertexData.indices = [];
  29355. var indices = this.getIndices();
  29356. for (var index = 0; index < indices.length; index++) {
  29357. vertexData.indices.push(indices[index]);
  29358. }
  29359. var updatable = false;
  29360. var stopChecking = false;
  29361. var kind;
  29362. for (kind in this._vertexBuffers) {
  29363. // using slice() to make a copy of the array and not just reference it
  29364. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  29365. if (!stopChecking) {
  29366. updatable = this.getVertexBuffer(kind).isUpdatable();
  29367. stopChecking = !updatable;
  29368. }
  29369. }
  29370. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29371. geometry.delayLoadState = this.delayLoadState;
  29372. geometry.delayLoadingFile = this.delayLoadingFile;
  29373. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29374. for (kind in this._delayInfo) {
  29375. geometry._delayInfo = geometry._delayInfo || [];
  29376. geometry._delayInfo.push(kind);
  29377. }
  29378. // Bounding info
  29379. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  29380. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29381. return geometry;
  29382. };
  29383. // Statics
  29384. Geometry.ExtractFromMesh = function (mesh, id) {
  29385. var geometry = mesh._geometry;
  29386. if (!geometry) {
  29387. return null;
  29388. }
  29389. return geometry.copy(id);
  29390. };
  29391. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29392. // be aware Math.random() could cause collisions
  29393. Geometry.RandomId = function () {
  29394. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  29395. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  29396. return v.toString(16);
  29397. });
  29398. };
  29399. return Geometry;
  29400. })();
  29401. BABYLON.Geometry = Geometry;
  29402. /////// Primitives //////////////////////////////////////////////
  29403. var Geometry;
  29404. (function (Geometry) {
  29405. var Primitives;
  29406. (function (Primitives) {
  29407. /// Abstract class
  29408. var _Primitive = (function (_super) {
  29409. __extends(_Primitive, _super);
  29410. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  29411. this._beingRegenerated = true;
  29412. this._canBeRegenerated = canBeRegenerated;
  29413. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  29414. this._beingRegenerated = false;
  29415. }
  29416. _Primitive.prototype.canBeRegenerated = function () {
  29417. return this._canBeRegenerated;
  29418. };
  29419. _Primitive.prototype.regenerate = function () {
  29420. if (!this._canBeRegenerated) {
  29421. return;
  29422. }
  29423. this._beingRegenerated = true;
  29424. this.setAllVerticesData(this._regenerateVertexData(), false);
  29425. this._beingRegenerated = false;
  29426. };
  29427. _Primitive.prototype.asNewGeometry = function (id) {
  29428. return _super.prototype.copy.call(this, id);
  29429. };
  29430. // overrides
  29431. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29432. if (!this._beingRegenerated) {
  29433. return;
  29434. }
  29435. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29436. };
  29437. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29438. if (!this._beingRegenerated) {
  29439. return;
  29440. }
  29441. _super.prototype.setVerticesData.call(this, kind, data, false);
  29442. };
  29443. // to override
  29444. // protected
  29445. _Primitive.prototype._regenerateVertexData = function () {
  29446. throw new Error("Abstract method");
  29447. };
  29448. _Primitive.prototype.copy = function (id) {
  29449. throw new Error("Must be overriden in sub-classes.");
  29450. };
  29451. return _Primitive;
  29452. })(Geometry);
  29453. Primitives._Primitive = _Primitive;
  29454. var Ribbon = (function (_super) {
  29455. __extends(Ribbon, _super);
  29456. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29458. this.pathArray = pathArray;
  29459. this.closeArray = closeArray;
  29460. this.closePath = closePath;
  29461. this.offset = offset;
  29462. this.side = side;
  29463. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29464. }
  29465. Ribbon.prototype._regenerateVertexData = function () {
  29466. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29467. };
  29468. Ribbon.prototype.copy = function (id) {
  29469. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29470. };
  29471. return Ribbon;
  29472. })(_Primitive);
  29473. Primitives.Ribbon = Ribbon;
  29474. var Box = (function (_super) {
  29475. __extends(Box, _super);
  29476. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29477. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29478. this.size = size;
  29479. this.side = side;
  29480. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29481. }
  29482. Box.prototype._regenerateVertexData = function () {
  29483. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29484. };
  29485. Box.prototype.copy = function (id) {
  29486. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29487. };
  29488. return Box;
  29489. })(_Primitive);
  29490. Primitives.Box = Box;
  29491. var Sphere = (function (_super) {
  29492. __extends(Sphere, _super);
  29493. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29494. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29495. this.segments = segments;
  29496. this.diameter = diameter;
  29497. this.side = side;
  29498. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29499. }
  29500. Sphere.prototype._regenerateVertexData = function () {
  29501. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29502. };
  29503. Sphere.prototype.copy = function (id) {
  29504. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29505. };
  29506. return Sphere;
  29507. })(_Primitive);
  29508. Primitives.Sphere = Sphere;
  29509. var Disc = (function (_super) {
  29510. __extends(Disc, _super);
  29511. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29512. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29513. this.radius = radius;
  29514. this.tessellation = tessellation;
  29515. this.side = side;
  29516. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29517. }
  29518. Disc.prototype._regenerateVertexData = function () {
  29519. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29520. };
  29521. Disc.prototype.copy = function (id) {
  29522. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29523. };
  29524. return Disc;
  29525. })(_Primitive);
  29526. Primitives.Disc = Disc;
  29527. var Cylinder = (function (_super) {
  29528. __extends(Cylinder, _super);
  29529. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29530. if (subdivisions === void 0) { subdivisions = 1; }
  29531. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29532. this.height = height;
  29533. this.diameterTop = diameterTop;
  29534. this.diameterBottom = diameterBottom;
  29535. this.tessellation = tessellation;
  29536. this.subdivisions = subdivisions;
  29537. this.side = side;
  29538. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29539. }
  29540. Cylinder.prototype._regenerateVertexData = function () {
  29541. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29542. };
  29543. Cylinder.prototype.copy = function (id) {
  29544. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29545. };
  29546. return Cylinder;
  29547. })(_Primitive);
  29548. Primitives.Cylinder = Cylinder;
  29549. var Torus = (function (_super) {
  29550. __extends(Torus, _super);
  29551. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29552. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29553. this.diameter = diameter;
  29554. this.thickness = thickness;
  29555. this.tessellation = tessellation;
  29556. this.side = side;
  29557. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29558. }
  29559. Torus.prototype._regenerateVertexData = function () {
  29560. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29561. };
  29562. Torus.prototype.copy = function (id) {
  29563. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29564. };
  29565. return Torus;
  29566. })(_Primitive);
  29567. Primitives.Torus = Torus;
  29568. var Ground = (function (_super) {
  29569. __extends(Ground, _super);
  29570. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29571. this.width = width;
  29572. this.height = height;
  29573. this.subdivisions = subdivisions;
  29574. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29575. }
  29576. Ground.prototype._regenerateVertexData = function () {
  29577. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29578. };
  29579. Ground.prototype.copy = function (id) {
  29580. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29581. };
  29582. return Ground;
  29583. })(_Primitive);
  29584. Primitives.Ground = Ground;
  29585. var TiledGround = (function (_super) {
  29586. __extends(TiledGround, _super);
  29587. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29588. this.xmin = xmin;
  29589. this.zmin = zmin;
  29590. this.xmax = xmax;
  29591. this.zmax = zmax;
  29592. this.subdivisions = subdivisions;
  29593. this.precision = precision;
  29594. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29595. }
  29596. TiledGround.prototype._regenerateVertexData = function () {
  29597. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29598. };
  29599. TiledGround.prototype.copy = function (id) {
  29600. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29601. };
  29602. return TiledGround;
  29603. })(_Primitive);
  29604. Primitives.TiledGround = TiledGround;
  29605. var Plane = (function (_super) {
  29606. __extends(Plane, _super);
  29607. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29608. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29609. this.size = size;
  29610. this.side = side;
  29611. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29612. }
  29613. Plane.prototype._regenerateVertexData = function () {
  29614. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29615. };
  29616. Plane.prototype.copy = function (id) {
  29617. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29618. };
  29619. return Plane;
  29620. })(_Primitive);
  29621. Primitives.Plane = Plane;
  29622. var TorusKnot = (function (_super) {
  29623. __extends(TorusKnot, _super);
  29624. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29626. this.radius = radius;
  29627. this.tube = tube;
  29628. this.radialSegments = radialSegments;
  29629. this.tubularSegments = tubularSegments;
  29630. this.p = p;
  29631. this.q = q;
  29632. this.side = side;
  29633. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  29634. }
  29635. TorusKnot.prototype._regenerateVertexData = function () {
  29636. return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  29637. };
  29638. TorusKnot.prototype.copy = function (id) {
  29639. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29640. };
  29641. return TorusKnot;
  29642. })(_Primitive);
  29643. Primitives.TorusKnot = TorusKnot;
  29644. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29645. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29646. })(BABYLON || (BABYLON = {}));
  29647. var BABYLON;
  29648. (function (BABYLON) {
  29649. var GroundMesh = (function (_super) {
  29650. __extends(GroundMesh, _super);
  29651. function GroundMesh(name, scene) {
  29652. _super.call(this, name, scene);
  29653. this.generateOctree = false;
  29654. this._worldInverse = new BABYLON.Matrix();
  29655. }
  29656. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  29657. get: function () {
  29658. return this._subdivisions;
  29659. },
  29660. enumerable: true,
  29661. configurable: true
  29662. });
  29663. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  29664. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  29665. this._subdivisions = chunksCount;
  29666. this.subdivide(this._subdivisions);
  29667. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  29668. };
  29669. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  29670. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  29671. this.getWorldMatrix().invertToRef(this._worldInverse);
  29672. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  29673. var pickInfo = this.intersects(ray);
  29674. if (pickInfo.hit) {
  29675. return pickInfo.pickedPoint.y;
  29676. }
  29677. return 0;
  29678. };
  29679. return GroundMesh;
  29680. })(BABYLON.Mesh);
  29681. BABYLON.GroundMesh = GroundMesh;
  29682. })(BABYLON || (BABYLON = {}));
  29683. var BABYLON;
  29684. (function (BABYLON) {
  29685. var LinesMesh = (function (_super) {
  29686. __extends(LinesMesh, _super);
  29687. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29688. if (parent === void 0) { parent = null; }
  29689. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29690. this.color = new BABYLON.Color3(1, 1, 1);
  29691. this.alpha = 1;
  29692. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29693. attributes: ["position"],
  29694. uniforms: ["worldViewProjection", "color"],
  29695. needAlphaBlending: true
  29696. });
  29697. }
  29698. Object.defineProperty(LinesMesh.prototype, "material", {
  29699. get: function () {
  29700. return this._colorShader;
  29701. },
  29702. enumerable: true,
  29703. configurable: true
  29704. });
  29705. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29706. get: function () {
  29707. return false;
  29708. },
  29709. enumerable: true,
  29710. configurable: true
  29711. });
  29712. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29713. get: function () {
  29714. return false;
  29715. },
  29716. enumerable: true,
  29717. configurable: true
  29718. });
  29719. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29720. var engine = this.getScene().getEngine();
  29721. var indexToBind = this._geometry.getIndexBuffer();
  29722. // VBOs
  29723. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29724. // Color
  29725. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29726. };
  29727. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29728. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29729. return;
  29730. }
  29731. var engine = this.getScene().getEngine();
  29732. // Draw order
  29733. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29734. };
  29735. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29736. return null;
  29737. };
  29738. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29739. this._colorShader.dispose();
  29740. _super.prototype.dispose.call(this, doNotRecurse);
  29741. };
  29742. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29743. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29744. };
  29745. return LinesMesh;
  29746. })(BABYLON.Mesh);
  29747. BABYLON.LinesMesh = LinesMesh;
  29748. })(BABYLON || (BABYLON = {}));
  29749. var BABYLON;
  29750. (function (BABYLON) {
  29751. var OutlineRenderer = (function () {
  29752. function OutlineRenderer(scene) {
  29753. this._scene = scene;
  29754. }
  29755. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29756. var _this = this;
  29757. if (useOverlay === void 0) { useOverlay = false; }
  29758. var scene = this._scene;
  29759. var engine = this._scene.getEngine();
  29760. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29761. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29762. return;
  29763. }
  29764. var mesh = subMesh.getRenderingMesh();
  29765. var material = subMesh.getMaterial();
  29766. engine.enableEffect(this._effect);
  29767. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29768. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29769. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29770. // Bones
  29771. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29772. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29773. }
  29774. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29775. // Alpha test
  29776. if (material && material.needAlphaTesting()) {
  29777. var alphaTexture = material.getAlphaTestTexture();
  29778. this._effect.setTexture("diffuseSampler", alphaTexture);
  29779. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29780. }
  29781. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29782. };
  29783. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29784. var defines = [];
  29785. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29786. var mesh = subMesh.getMesh();
  29787. var material = subMesh.getMaterial();
  29788. // Alpha test
  29789. if (material && material.needAlphaTesting()) {
  29790. defines.push("#define ALPHATEST");
  29791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29792. attribs.push(BABYLON.VertexBuffer.UVKind);
  29793. defines.push("#define UV1");
  29794. }
  29795. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29796. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29797. defines.push("#define UV2");
  29798. }
  29799. }
  29800. // Bones
  29801. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29802. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29803. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29804. defines.push("#define BONES");
  29805. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29806. }
  29807. // Instances
  29808. if (useInstances) {
  29809. defines.push("#define INSTANCES");
  29810. attribs.push("world0");
  29811. attribs.push("world1");
  29812. attribs.push("world2");
  29813. attribs.push("world3");
  29814. }
  29815. // Get correct effect
  29816. var join = defines.join("\n");
  29817. if (this._cachedDefines !== join) {
  29818. this._cachedDefines = join;
  29819. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29820. }
  29821. return this._effect.isReady();
  29822. };
  29823. return OutlineRenderer;
  29824. })();
  29825. BABYLON.OutlineRenderer = OutlineRenderer;
  29826. })(BABYLON || (BABYLON = {}));
  29827. var BABYLON;
  29828. (function (BABYLON) {
  29829. var MeshAssetTask = (function () {
  29830. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29831. this.name = name;
  29832. this.meshesNames = meshesNames;
  29833. this.rootUrl = rootUrl;
  29834. this.sceneFilename = sceneFilename;
  29835. this.isCompleted = false;
  29836. }
  29837. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29838. var _this = this;
  29839. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29840. _this.loadedMeshes = meshes;
  29841. _this.loadedParticleSystems = particleSystems;
  29842. _this.loadedSkeletons = skeletons;
  29843. _this.isCompleted = true;
  29844. if (_this.onSuccess) {
  29845. _this.onSuccess(_this);
  29846. }
  29847. onSuccess();
  29848. }, null, function () {
  29849. if (_this.onError) {
  29850. _this.onError(_this);
  29851. }
  29852. onError();
  29853. });
  29854. };
  29855. return MeshAssetTask;
  29856. })();
  29857. BABYLON.MeshAssetTask = MeshAssetTask;
  29858. var TextFileAssetTask = (function () {
  29859. function TextFileAssetTask(name, url) {
  29860. this.name = name;
  29861. this.url = url;
  29862. this.isCompleted = false;
  29863. }
  29864. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29865. var _this = this;
  29866. BABYLON.Tools.LoadFile(this.url, function (data) {
  29867. _this.text = data;
  29868. _this.isCompleted = true;
  29869. if (_this.onSuccess) {
  29870. _this.onSuccess(_this);
  29871. }
  29872. onSuccess();
  29873. }, null, scene.database, false, function () {
  29874. if (_this.onError) {
  29875. _this.onError(_this);
  29876. }
  29877. onError();
  29878. });
  29879. };
  29880. return TextFileAssetTask;
  29881. })();
  29882. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29883. var BinaryFileAssetTask = (function () {
  29884. function BinaryFileAssetTask(name, url) {
  29885. this.name = name;
  29886. this.url = url;
  29887. this.isCompleted = false;
  29888. }
  29889. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29890. var _this = this;
  29891. BABYLON.Tools.LoadFile(this.url, function (data) {
  29892. _this.data = data;
  29893. _this.isCompleted = true;
  29894. if (_this.onSuccess) {
  29895. _this.onSuccess(_this);
  29896. }
  29897. onSuccess();
  29898. }, null, scene.database, true, function () {
  29899. if (_this.onError) {
  29900. _this.onError(_this);
  29901. }
  29902. onError();
  29903. });
  29904. };
  29905. return BinaryFileAssetTask;
  29906. })();
  29907. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29908. var ImageAssetTask = (function () {
  29909. function ImageAssetTask(name, url) {
  29910. this.name = name;
  29911. this.url = url;
  29912. this.isCompleted = false;
  29913. }
  29914. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29915. var _this = this;
  29916. var img = new Image();
  29917. img.onload = function () {
  29918. _this.image = img;
  29919. _this.isCompleted = true;
  29920. if (_this.onSuccess) {
  29921. _this.onSuccess(_this);
  29922. }
  29923. onSuccess();
  29924. };
  29925. img.onerror = function () {
  29926. if (_this.onError) {
  29927. _this.onError(_this);
  29928. }
  29929. onError();
  29930. };
  29931. img.src = this.url;
  29932. };
  29933. return ImageAssetTask;
  29934. })();
  29935. BABYLON.ImageAssetTask = ImageAssetTask;
  29936. var TextureAssetTask = (function () {
  29937. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29939. this.name = name;
  29940. this.url = url;
  29941. this.noMipmap = noMipmap;
  29942. this.invertY = invertY;
  29943. this.samplingMode = samplingMode;
  29944. this.isCompleted = false;
  29945. }
  29946. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29947. var _this = this;
  29948. var onload = function () {
  29949. _this.isCompleted = true;
  29950. if (_this.onSuccess) {
  29951. _this.onSuccess(_this);
  29952. }
  29953. onSuccess();
  29954. };
  29955. var onerror = function () {
  29956. if (_this.onError) {
  29957. _this.onError(_this);
  29958. }
  29959. onError();
  29960. };
  29961. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29962. };
  29963. return TextureAssetTask;
  29964. })();
  29965. BABYLON.TextureAssetTask = TextureAssetTask;
  29966. var AssetsManager = (function () {
  29967. function AssetsManager(scene) {
  29968. this._tasks = new Array();
  29969. this._waitingTasksCount = 0;
  29970. this.useDefaultLoadingScreen = true;
  29971. this._scene = scene;
  29972. }
  29973. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29974. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29975. this._tasks.push(task);
  29976. return task;
  29977. };
  29978. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29979. var task = new TextFileAssetTask(taskName, url);
  29980. this._tasks.push(task);
  29981. return task;
  29982. };
  29983. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29984. var task = new BinaryFileAssetTask(taskName, url);
  29985. this._tasks.push(task);
  29986. return task;
  29987. };
  29988. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29989. var task = new ImageAssetTask(taskName, url);
  29990. this._tasks.push(task);
  29991. return task;
  29992. };
  29993. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29995. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29996. this._tasks.push(task);
  29997. return task;
  29998. };
  29999. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  30000. this._waitingTasksCount--;
  30001. if (this._waitingTasksCount === 0) {
  30002. if (this.onFinish) {
  30003. this.onFinish(this._tasks);
  30004. }
  30005. this._scene.getEngine().hideLoadingUI();
  30006. }
  30007. };
  30008. AssetsManager.prototype._runTask = function (task) {
  30009. var _this = this;
  30010. task.run(this._scene, function () {
  30011. if (_this.onTaskSuccess) {
  30012. _this.onTaskSuccess(task);
  30013. }
  30014. _this._decreaseWaitingTasksCount();
  30015. }, function () {
  30016. if (_this.onTaskError) {
  30017. _this.onTaskError(task);
  30018. }
  30019. _this._decreaseWaitingTasksCount();
  30020. });
  30021. };
  30022. AssetsManager.prototype.reset = function () {
  30023. this._tasks = new Array();
  30024. return this;
  30025. };
  30026. AssetsManager.prototype.load = function () {
  30027. this._waitingTasksCount = this._tasks.length;
  30028. if (this._waitingTasksCount === 0) {
  30029. if (this.onFinish) {
  30030. this.onFinish(this._tasks);
  30031. }
  30032. return this;
  30033. }
  30034. if (this.useDefaultLoadingScreen) {
  30035. this._scene.getEngine().displayLoadingUI();
  30036. }
  30037. for (var index = 0; index < this._tasks.length; index++) {
  30038. var task = this._tasks[index];
  30039. this._runTask(task);
  30040. }
  30041. return this;
  30042. };
  30043. return AssetsManager;
  30044. })();
  30045. BABYLON.AssetsManager = AssetsManager;
  30046. })(BABYLON || (BABYLON = {}));
  30047. var BABYLON;
  30048. (function (BABYLON) {
  30049. var VRDeviceOrientationFreeCamera = (function (_super) {
  30050. __extends(VRDeviceOrientationFreeCamera, _super);
  30051. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  30052. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30053. _super.call(this, name, position, scene);
  30054. this._alpha = 0;
  30055. this._beta = 0;
  30056. this._gamma = 0;
  30057. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30058. metrics.compensateDistortion = compensateDistortion;
  30059. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30060. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30061. }
  30062. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30063. this._alpha = +evt.alpha | 0;
  30064. this._beta = +evt.beta | 0;
  30065. this._gamma = +evt.gamma | 0;
  30066. if (this._gamma < 0) {
  30067. this._gamma = 90 + this._gamma;
  30068. }
  30069. else {
  30070. // Incline it in the correct angle.
  30071. this._gamma = 270 - this._gamma;
  30072. }
  30073. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30074. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30075. this.rotation.z = this._beta / 180.0 * Math.PI;
  30076. };
  30077. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30078. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30079. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30080. };
  30081. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  30082. _super.prototype.detachControl.call(this, element);
  30083. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  30084. };
  30085. return VRDeviceOrientationFreeCamera;
  30086. })(BABYLON.FreeCamera);
  30087. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  30088. })(BABYLON || (BABYLON = {}));
  30089. var BABYLON;
  30090. (function (BABYLON) {
  30091. var WebVRFreeCamera = (function (_super) {
  30092. __extends(WebVRFreeCamera, _super);
  30093. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  30094. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30095. _super.call(this, name, position, scene);
  30096. this._hmdDevice = null;
  30097. this._sensorDevice = null;
  30098. this._cacheState = null;
  30099. this._cacheQuaternion = new BABYLON.Quaternion();
  30100. this._cacheRotation = BABYLON.Vector3.Zero();
  30101. this._vrEnabled = false;
  30102. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30103. metrics.compensateDistortion = compensateDistortion;
  30104. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30105. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  30106. }
  30107. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  30108. var size = devices.length;
  30109. var i = 0;
  30110. // Reset devices.
  30111. this._sensorDevice = null;
  30112. this._hmdDevice = null;
  30113. // Search for a HmdDevice.
  30114. while (i < size && this._hmdDevice === null) {
  30115. if (devices[i] instanceof HMDVRDevice) {
  30116. this._hmdDevice = devices[i];
  30117. }
  30118. i++;
  30119. }
  30120. i = 0;
  30121. while (i < size && this._sensorDevice === null) {
  30122. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  30123. this._sensorDevice = devices[i];
  30124. }
  30125. i++;
  30126. }
  30127. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  30128. };
  30129. WebVRFreeCamera.prototype._checkInputs = function () {
  30130. if (this._vrEnabled) {
  30131. this._cacheState = this._sensorDevice.getState();
  30132. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  30133. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  30134. this.rotation.x = -this._cacheRotation.z;
  30135. this.rotation.y = -this._cacheRotation.y;
  30136. this.rotation.z = this._cacheRotation.x;
  30137. }
  30138. _super.prototype._checkInputs.call(this);
  30139. };
  30140. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30141. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30142. if (navigator.getVRDevices) {
  30143. navigator.getVRDevices().then(this._getWebVRDevices);
  30144. }
  30145. else if (navigator.mozGetVRDevices) {
  30146. navigator.mozGetVRDevices(this._getWebVRDevices);
  30147. }
  30148. };
  30149. WebVRFreeCamera.prototype.detachControl = function (element) {
  30150. _super.prototype.detachControl.call(this, element);
  30151. this._vrEnabled = false;
  30152. };
  30153. return WebVRFreeCamera;
  30154. })(BABYLON.FreeCamera);
  30155. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  30156. })(BABYLON || (BABYLON = {}));
  30157. var BABYLON;
  30158. (function (BABYLON) {
  30159. // Standard optimizations
  30160. var SceneOptimization = (function () {
  30161. function SceneOptimization(priority) {
  30162. if (priority === void 0) { priority = 0; }
  30163. this.priority = priority;
  30164. this.apply = function (scene) {
  30165. return true; // Return true if everything that can be done was applied
  30166. };
  30167. }
  30168. return SceneOptimization;
  30169. })();
  30170. BABYLON.SceneOptimization = SceneOptimization;
  30171. var TextureOptimization = (function (_super) {
  30172. __extends(TextureOptimization, _super);
  30173. function TextureOptimization(priority, maximumSize) {
  30174. var _this = this;
  30175. if (priority === void 0) { priority = 0; }
  30176. if (maximumSize === void 0) { maximumSize = 1024; }
  30177. _super.call(this, priority);
  30178. this.priority = priority;
  30179. this.maximumSize = maximumSize;
  30180. this.apply = function (scene) {
  30181. var allDone = true;
  30182. for (var index = 0; index < scene.textures.length; index++) {
  30183. var texture = scene.textures[index];
  30184. if (!texture.canRescale) {
  30185. continue;
  30186. }
  30187. var currentSize = texture.getSize();
  30188. var maxDimension = Math.max(currentSize.width, currentSize.height);
  30189. if (maxDimension > _this.maximumSize) {
  30190. texture.scale(0.5);
  30191. allDone = false;
  30192. }
  30193. }
  30194. return allDone;
  30195. };
  30196. }
  30197. return TextureOptimization;
  30198. })(SceneOptimization);
  30199. BABYLON.TextureOptimization = TextureOptimization;
  30200. var HardwareScalingOptimization = (function (_super) {
  30201. __extends(HardwareScalingOptimization, _super);
  30202. function HardwareScalingOptimization(priority, maximumScale) {
  30203. var _this = this;
  30204. if (priority === void 0) { priority = 0; }
  30205. if (maximumScale === void 0) { maximumScale = 2; }
  30206. _super.call(this, priority);
  30207. this.priority = priority;
  30208. this.maximumScale = maximumScale;
  30209. this._currentScale = 1;
  30210. this.apply = function (scene) {
  30211. _this._currentScale++;
  30212. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  30213. return _this._currentScale >= _this.maximumScale;
  30214. };
  30215. }
  30216. return HardwareScalingOptimization;
  30217. })(SceneOptimization);
  30218. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  30219. var ShadowsOptimization = (function (_super) {
  30220. __extends(ShadowsOptimization, _super);
  30221. function ShadowsOptimization() {
  30222. _super.apply(this, arguments);
  30223. this.apply = function (scene) {
  30224. scene.shadowsEnabled = false;
  30225. return true;
  30226. };
  30227. }
  30228. return ShadowsOptimization;
  30229. })(SceneOptimization);
  30230. BABYLON.ShadowsOptimization = ShadowsOptimization;
  30231. var PostProcessesOptimization = (function (_super) {
  30232. __extends(PostProcessesOptimization, _super);
  30233. function PostProcessesOptimization() {
  30234. _super.apply(this, arguments);
  30235. this.apply = function (scene) {
  30236. scene.postProcessesEnabled = false;
  30237. return true;
  30238. };
  30239. }
  30240. return PostProcessesOptimization;
  30241. })(SceneOptimization);
  30242. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  30243. var LensFlaresOptimization = (function (_super) {
  30244. __extends(LensFlaresOptimization, _super);
  30245. function LensFlaresOptimization() {
  30246. _super.apply(this, arguments);
  30247. this.apply = function (scene) {
  30248. scene.lensFlaresEnabled = false;
  30249. return true;
  30250. };
  30251. }
  30252. return LensFlaresOptimization;
  30253. })(SceneOptimization);
  30254. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  30255. var ParticlesOptimization = (function (_super) {
  30256. __extends(ParticlesOptimization, _super);
  30257. function ParticlesOptimization() {
  30258. _super.apply(this, arguments);
  30259. this.apply = function (scene) {
  30260. scene.particlesEnabled = false;
  30261. return true;
  30262. };
  30263. }
  30264. return ParticlesOptimization;
  30265. })(SceneOptimization);
  30266. BABYLON.ParticlesOptimization = ParticlesOptimization;
  30267. var RenderTargetsOptimization = (function (_super) {
  30268. __extends(RenderTargetsOptimization, _super);
  30269. function RenderTargetsOptimization() {
  30270. _super.apply(this, arguments);
  30271. this.apply = function (scene) {
  30272. scene.renderTargetsEnabled = false;
  30273. return true;
  30274. };
  30275. }
  30276. return RenderTargetsOptimization;
  30277. })(SceneOptimization);
  30278. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  30279. var MergeMeshesOptimization = (function (_super) {
  30280. __extends(MergeMeshesOptimization, _super);
  30281. function MergeMeshesOptimization() {
  30282. var _this = this;
  30283. _super.apply(this, arguments);
  30284. this._canBeMerged = function (abstractMesh) {
  30285. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  30286. return false;
  30287. }
  30288. var mesh = abstractMesh;
  30289. if (!mesh.isVisible || !mesh.isEnabled()) {
  30290. return false;
  30291. }
  30292. if (mesh.instances.length > 0) {
  30293. return false;
  30294. }
  30295. if (mesh.skeleton || mesh.hasLODLevels) {
  30296. return false;
  30297. }
  30298. return true;
  30299. };
  30300. this.apply = function (scene, updateSelectionTree) {
  30301. var globalPool = scene.meshes.slice(0);
  30302. var globalLength = globalPool.length;
  30303. for (var index = 0; index < globalLength; index++) {
  30304. var currentPool = new Array();
  30305. var current = globalPool[index];
  30306. // Checks
  30307. if (!_this._canBeMerged(current)) {
  30308. continue;
  30309. }
  30310. currentPool.push(current);
  30311. // Find compatible meshes
  30312. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  30313. var otherMesh = globalPool[subIndex];
  30314. if (!_this._canBeMerged(otherMesh)) {
  30315. continue;
  30316. }
  30317. if (otherMesh.material !== current.material) {
  30318. continue;
  30319. }
  30320. if (otherMesh.checkCollisions !== current.checkCollisions) {
  30321. continue;
  30322. }
  30323. currentPool.push(otherMesh);
  30324. globalLength--;
  30325. globalPool.splice(subIndex, 1);
  30326. subIndex--;
  30327. }
  30328. if (currentPool.length < 2) {
  30329. continue;
  30330. }
  30331. // Merge meshes
  30332. BABYLON.Mesh.MergeMeshes(currentPool);
  30333. }
  30334. if (updateSelectionTree != undefined) {
  30335. if (updateSelectionTree) {
  30336. scene.createOrUpdateSelectionOctree();
  30337. }
  30338. }
  30339. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  30340. scene.createOrUpdateSelectionOctree();
  30341. }
  30342. return true;
  30343. };
  30344. }
  30345. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  30346. get: function () {
  30347. return MergeMeshesOptimization._UpdateSelectionTree;
  30348. },
  30349. set: function (value) {
  30350. MergeMeshesOptimization._UpdateSelectionTree = value;
  30351. },
  30352. enumerable: true,
  30353. configurable: true
  30354. });
  30355. MergeMeshesOptimization._UpdateSelectionTree = false;
  30356. return MergeMeshesOptimization;
  30357. })(SceneOptimization);
  30358. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  30359. // Options
  30360. var SceneOptimizerOptions = (function () {
  30361. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  30362. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  30363. if (trackerDuration === void 0) { trackerDuration = 2000; }
  30364. this.targetFrameRate = targetFrameRate;
  30365. this.trackerDuration = trackerDuration;
  30366. this.optimizations = new Array();
  30367. }
  30368. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  30369. var result = new SceneOptimizerOptions(targetFrameRate);
  30370. var priority = 0;
  30371. result.optimizations.push(new MergeMeshesOptimization(priority));
  30372. result.optimizations.push(new ShadowsOptimization(priority));
  30373. result.optimizations.push(new LensFlaresOptimization(priority));
  30374. // Next priority
  30375. priority++;
  30376. result.optimizations.push(new PostProcessesOptimization(priority));
  30377. result.optimizations.push(new ParticlesOptimization(priority));
  30378. // Next priority
  30379. priority++;
  30380. result.optimizations.push(new TextureOptimization(priority, 1024));
  30381. return result;
  30382. };
  30383. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  30384. var result = new SceneOptimizerOptions(targetFrameRate);
  30385. var priority = 0;
  30386. result.optimizations.push(new MergeMeshesOptimization(priority));
  30387. result.optimizations.push(new ShadowsOptimization(priority));
  30388. result.optimizations.push(new LensFlaresOptimization(priority));
  30389. // Next priority
  30390. priority++;
  30391. result.optimizations.push(new PostProcessesOptimization(priority));
  30392. result.optimizations.push(new ParticlesOptimization(priority));
  30393. // Next priority
  30394. priority++;
  30395. result.optimizations.push(new TextureOptimization(priority, 512));
  30396. // Next priority
  30397. priority++;
  30398. result.optimizations.push(new RenderTargetsOptimization(priority));
  30399. // Next priority
  30400. priority++;
  30401. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  30402. return result;
  30403. };
  30404. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  30405. var result = new SceneOptimizerOptions(targetFrameRate);
  30406. var priority = 0;
  30407. result.optimizations.push(new MergeMeshesOptimization(priority));
  30408. result.optimizations.push(new ShadowsOptimization(priority));
  30409. result.optimizations.push(new LensFlaresOptimization(priority));
  30410. // Next priority
  30411. priority++;
  30412. result.optimizations.push(new PostProcessesOptimization(priority));
  30413. result.optimizations.push(new ParticlesOptimization(priority));
  30414. // Next priority
  30415. priority++;
  30416. result.optimizations.push(new TextureOptimization(priority, 256));
  30417. // Next priority
  30418. priority++;
  30419. result.optimizations.push(new RenderTargetsOptimization(priority));
  30420. // Next priority
  30421. priority++;
  30422. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  30423. return result;
  30424. };
  30425. return SceneOptimizerOptions;
  30426. })();
  30427. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  30428. // Scene optimizer tool
  30429. var SceneOptimizer = (function () {
  30430. function SceneOptimizer() {
  30431. }
  30432. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  30433. // TODO: add an epsilon
  30434. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  30435. if (onSuccess) {
  30436. onSuccess();
  30437. }
  30438. return;
  30439. }
  30440. // Apply current level of optimizations
  30441. var allDone = true;
  30442. var noOptimizationApplied = true;
  30443. for (var index = 0; index < options.optimizations.length; index++) {
  30444. var optimization = options.optimizations[index];
  30445. if (optimization.priority === currentPriorityLevel) {
  30446. noOptimizationApplied = false;
  30447. allDone = allDone && optimization.apply(scene);
  30448. }
  30449. }
  30450. // If no optimization was applied, this is a failure :(
  30451. if (noOptimizationApplied) {
  30452. if (onFailure) {
  30453. onFailure();
  30454. }
  30455. return;
  30456. }
  30457. // If all optimizations were done, move to next level
  30458. if (allDone) {
  30459. currentPriorityLevel++;
  30460. }
  30461. // Let's the system running for a specific amount of time before checking FPS
  30462. scene.executeWhenReady(function () {
  30463. setTimeout(function () {
  30464. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  30465. }, options.trackerDuration);
  30466. });
  30467. };
  30468. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  30469. if (!options) {
  30470. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  30471. }
  30472. // Let's the system running for a specific amount of time before checking FPS
  30473. scene.executeWhenReady(function () {
  30474. setTimeout(function () {
  30475. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  30476. }, options.trackerDuration);
  30477. });
  30478. };
  30479. return SceneOptimizer;
  30480. })();
  30481. BABYLON.SceneOptimizer = SceneOptimizer;
  30482. })(BABYLON || (BABYLON = {}));
  30483. var BABYLON;
  30484. (function (BABYLON) {
  30485. var Internals;
  30486. (function (Internals) {
  30487. var MeshLODLevel = (function () {
  30488. function MeshLODLevel(distance, mesh) {
  30489. this.distance = distance;
  30490. this.mesh = mesh;
  30491. }
  30492. return MeshLODLevel;
  30493. })();
  30494. Internals.MeshLODLevel = MeshLODLevel;
  30495. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30496. })(BABYLON || (BABYLON = {}));
  30497. var BABYLON;
  30498. (function (BABYLON) {
  30499. var AudioEngine = (function () {
  30500. function AudioEngine() {
  30501. this._audioContext = null;
  30502. this._audioContextInitialized = false;
  30503. this.canUseWebAudio = false;
  30504. this.WarnedWebAudioUnsupported = false;
  30505. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  30506. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  30507. this.canUseWebAudio = true;
  30508. }
  30509. }
  30510. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  30511. get: function () {
  30512. if (!this._audioContextInitialized) {
  30513. this._initializeAudioContext();
  30514. }
  30515. return this._audioContext;
  30516. },
  30517. enumerable: true,
  30518. configurable: true
  30519. });
  30520. AudioEngine.prototype._initializeAudioContext = function () {
  30521. try {
  30522. if (this.canUseWebAudio) {
  30523. this._audioContext = new AudioContext();
  30524. // create a global volume gain node
  30525. this.masterGain = this._audioContext.createGain();
  30526. this.masterGain.gain.value = 1;
  30527. this.masterGain.connect(this._audioContext.destination);
  30528. this._audioContextInitialized = true;
  30529. }
  30530. }
  30531. catch (e) {
  30532. this.canUseWebAudio = false;
  30533. BABYLON.Tools.Error("Web Audio: " + e.message);
  30534. }
  30535. };
  30536. AudioEngine.prototype.dispose = function () {
  30537. if (this.canUseWebAudio && this._audioContextInitialized) {
  30538. if (this._connectedAnalyser) {
  30539. this._connectedAnalyser.stopDebugCanvas();
  30540. this._connectedAnalyser.dispose();
  30541. this.masterGain.disconnect();
  30542. this.masterGain.connect(this._audioContext.destination);
  30543. this._connectedAnalyser = null;
  30544. }
  30545. this.masterGain.gain.value = 1;
  30546. }
  30547. this.WarnedWebAudioUnsupported = false;
  30548. };
  30549. AudioEngine.prototype.getGlobalVolume = function () {
  30550. if (this.canUseWebAudio && this._audioContextInitialized) {
  30551. return this.masterGain.gain.value;
  30552. }
  30553. else {
  30554. return -1;
  30555. }
  30556. };
  30557. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  30558. if (this.canUseWebAudio && this._audioContextInitialized) {
  30559. this.masterGain.gain.value = newVolume;
  30560. }
  30561. };
  30562. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  30563. if (this._connectedAnalyser) {
  30564. this._connectedAnalyser.stopDebugCanvas();
  30565. }
  30566. if (this.canUseWebAudio && this._audioContextInitialized) {
  30567. this._connectedAnalyser = analyser;
  30568. this.masterGain.disconnect();
  30569. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  30570. }
  30571. };
  30572. return AudioEngine;
  30573. })();
  30574. BABYLON.AudioEngine = AudioEngine;
  30575. })(BABYLON || (BABYLON = {}));
  30576. var BABYLON;
  30577. (function (BABYLON) {
  30578. var Sound = (function () {
  30579. /**
  30580. * Create a sound and attach it to a scene
  30581. * @param name Name of your sound
  30582. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  30583. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  30584. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  30585. */
  30586. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  30587. var _this = this;
  30588. this.autoplay = false;
  30589. this.loop = false;
  30590. this.useCustomAttenuation = false;
  30591. this.spatialSound = false;
  30592. this.refDistance = 1;
  30593. this.rolloffFactor = 1;
  30594. this.maxDistance = 100;
  30595. this.distanceModel = "linear";
  30596. this._panningModel = "equalpower";
  30597. this._playbackRate = 1;
  30598. this._startTime = 0;
  30599. this._startOffset = 0;
  30600. this._position = BABYLON.Vector3.Zero();
  30601. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  30602. this._volume = 1;
  30603. this._isLoaded = false;
  30604. this._isReadyToPlay = false;
  30605. this.isPlaying = false;
  30606. this.isPaused = false;
  30607. this._isDirectional = false;
  30608. // Used if you'd like to create a directional sound.
  30609. // If not set, the sound will be omnidirectional
  30610. this._coneInnerAngle = 360;
  30611. this._coneOuterAngle = 360;
  30612. this._coneOuterGain = 0;
  30613. this._isOutputConnected = false;
  30614. this.name = name;
  30615. this._scene = scene;
  30616. this._readyToPlayCallback = readyToPlayCallback;
  30617. // Default custom attenuation function is a linear attenuation
  30618. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  30619. if (currentDistance < maxDistance) {
  30620. return currentVolume * (1 - currentDistance / maxDistance);
  30621. }
  30622. else {
  30623. return 0;
  30624. }
  30625. };
  30626. if (options) {
  30627. this.autoplay = options.autoplay || false;
  30628. this.loop = options.loop || false;
  30629. // if volume === 0, we need another way to check this option
  30630. if (options.volume !== undefined) {
  30631. this._volume = options.volume;
  30632. }
  30633. this.spatialSound = options.spatialSound || false;
  30634. this.maxDistance = options.maxDistance || 100;
  30635. this.useCustomAttenuation = options.useCustomAttenuation || false;
  30636. this.rolloffFactor = options.rolloffFactor || 1;
  30637. this.refDistance = options.refDistance || 1;
  30638. this.distanceModel = options.distanceModel || "linear";
  30639. this._playbackRate = options.playbackRate || 1;
  30640. }
  30641. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30642. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  30643. this._soundGain.gain.value = this._volume;
  30644. this._inputAudioNode = this._soundGain;
  30645. this._ouputAudioNode = this._soundGain;
  30646. if (this.spatialSound) {
  30647. this._createSpatialParameters();
  30648. }
  30649. this._scene.mainSoundTrack.AddSound(this);
  30650. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  30651. if (urlOrArrayBuffer) {
  30652. // If it's an URL
  30653. if (typeof (urlOrArrayBuffer) === "string") {
  30654. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  30655. }
  30656. else {
  30657. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  30658. this._soundLoaded(urlOrArrayBuffer);
  30659. }
  30660. else {
  30661. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  30662. }
  30663. }
  30664. }
  30665. }
  30666. else {
  30667. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  30668. this._scene.mainSoundTrack.AddSound(this);
  30669. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  30670. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  30671. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  30672. }
  30673. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  30674. if (this._readyToPlayCallback) {
  30675. window.setTimeout(function () {
  30676. _this._readyToPlayCallback();
  30677. }, 1000);
  30678. }
  30679. }
  30680. }
  30681. Sound.prototype.dispose = function () {
  30682. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30683. if (this.isPlaying) {
  30684. this.stop();
  30685. }
  30686. this._isReadyToPlay = false;
  30687. if (this.soundTrackId === -1) {
  30688. this._scene.mainSoundTrack.RemoveSound(this);
  30689. }
  30690. else {
  30691. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30692. }
  30693. if (this._soundGain) {
  30694. this._soundGain.disconnect();
  30695. this._soundGain = null;
  30696. }
  30697. if (this._soundPanner) {
  30698. this._soundPanner.disconnect();
  30699. this._soundPanner = null;
  30700. }
  30701. if (this._soundSource) {
  30702. this._soundSource.disconnect();
  30703. this._soundSource = null;
  30704. }
  30705. this._audioBuffer = null;
  30706. if (this._connectedMesh) {
  30707. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30708. this._connectedMesh = null;
  30709. }
  30710. }
  30711. };
  30712. Sound.prototype._soundLoaded = function (audioData) {
  30713. var _this = this;
  30714. this._isLoaded = true;
  30715. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30716. _this._audioBuffer = buffer;
  30717. _this._isReadyToPlay = true;
  30718. if (_this.autoplay) {
  30719. _this.play();
  30720. }
  30721. if (_this._readyToPlayCallback) {
  30722. _this._readyToPlayCallback();
  30723. }
  30724. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30725. };
  30726. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30727. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30728. this._audioBuffer = audioBuffer;
  30729. this._isReadyToPlay = true;
  30730. }
  30731. };
  30732. Sound.prototype.updateOptions = function (options) {
  30733. if (options) {
  30734. this.loop = options.loop || this.loop;
  30735. this.maxDistance = options.maxDistance || this.maxDistance;
  30736. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30737. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30738. this.refDistance = options.refDistance || this.refDistance;
  30739. this.distanceModel = options.distanceModel || this.distanceModel;
  30740. this._playbackRate = options.playbackRate || this._playbackRate;
  30741. this._updateSpatialParameters();
  30742. if (this.isPlaying) {
  30743. this._soundSource.playbackRate.value = this._playbackRate;
  30744. }
  30745. }
  30746. };
  30747. Sound.prototype._createSpatialParameters = function () {
  30748. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30749. if (this._scene.headphone) {
  30750. this._panningModel = "HRTF";
  30751. }
  30752. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30753. this._updateSpatialParameters();
  30754. this._soundPanner.connect(this._ouputAudioNode);
  30755. this._inputAudioNode = this._soundPanner;
  30756. }
  30757. };
  30758. Sound.prototype._updateSpatialParameters = function () {
  30759. if (this.spatialSound) {
  30760. if (this.useCustomAttenuation) {
  30761. // Tricks to disable in a way embedded Web Audio attenuation
  30762. this._soundPanner.distanceModel = "linear";
  30763. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30764. this._soundPanner.refDistance = 1;
  30765. this._soundPanner.rolloffFactor = 1;
  30766. this._soundPanner.panningModel = this._panningModel;
  30767. }
  30768. else {
  30769. this._soundPanner.distanceModel = this.distanceModel;
  30770. this._soundPanner.maxDistance = this.maxDistance;
  30771. this._soundPanner.refDistance = this.refDistance;
  30772. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30773. this._soundPanner.panningModel = this._panningModel;
  30774. }
  30775. }
  30776. };
  30777. Sound.prototype.switchPanningModelToHRTF = function () {
  30778. this._panningModel = "HRTF";
  30779. this._switchPanningModel();
  30780. };
  30781. Sound.prototype.switchPanningModelToEqualPower = function () {
  30782. this._panningModel = "equalpower";
  30783. this._switchPanningModel();
  30784. };
  30785. Sound.prototype._switchPanningModel = function () {
  30786. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30787. this._soundPanner.panningModel = this._panningModel;
  30788. }
  30789. };
  30790. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30791. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30792. if (this._isOutputConnected) {
  30793. this._ouputAudioNode.disconnect();
  30794. }
  30795. this._ouputAudioNode.connect(soundTrackAudioNode);
  30796. this._isOutputConnected = true;
  30797. }
  30798. };
  30799. /**
  30800. * Transform this sound into a directional source
  30801. * @param coneInnerAngle Size of the inner cone in degree
  30802. * @param coneOuterAngle Size of the outer cone in degree
  30803. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30804. */
  30805. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30806. if (coneOuterAngle < coneInnerAngle) {
  30807. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30808. return;
  30809. }
  30810. this._coneInnerAngle = coneInnerAngle;
  30811. this._coneOuterAngle = coneOuterAngle;
  30812. this._coneOuterGain = coneOuterGain;
  30813. this._isDirectional = true;
  30814. if (this.isPlaying && this.loop) {
  30815. this.stop();
  30816. this.play();
  30817. }
  30818. };
  30819. Sound.prototype.setPosition = function (newPosition) {
  30820. this._position = newPosition;
  30821. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30822. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30823. }
  30824. };
  30825. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30826. this._localDirection = newLocalDirection;
  30827. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30828. this._updateDirection();
  30829. }
  30830. };
  30831. Sound.prototype._updateDirection = function () {
  30832. var mat = this._connectedMesh.getWorldMatrix();
  30833. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30834. direction.normalize();
  30835. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30836. };
  30837. Sound.prototype.updateDistanceFromListener = function () {
  30838. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30839. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30840. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30841. }
  30842. };
  30843. Sound.prototype.setAttenuationFunction = function (callback) {
  30844. this._customAttenuationFunction = callback;
  30845. };
  30846. /**
  30847. * Play the sound
  30848. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30849. */
  30850. Sound.prototype.play = function (time) {
  30851. var _this = this;
  30852. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30853. try {
  30854. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30855. if (!this._soundSource) {
  30856. if (this.spatialSound) {
  30857. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30858. if (this._isDirectional) {
  30859. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30860. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30861. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30862. if (this._connectedMesh) {
  30863. this._updateDirection();
  30864. }
  30865. else {
  30866. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30867. }
  30868. }
  30869. }
  30870. }
  30871. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30872. this._soundSource.buffer = this._audioBuffer;
  30873. this._soundSource.connect(this._inputAudioNode);
  30874. this._soundSource.loop = this.loop;
  30875. this._soundSource.playbackRate.value = this._playbackRate;
  30876. this._startTime = startTime;
  30877. this._soundSource.onended = function () { _this._onended(); };
  30878. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30879. this.isPlaying = true;
  30880. this.isPaused = false;
  30881. }
  30882. catch (ex) {
  30883. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30884. }
  30885. }
  30886. };
  30887. Sound.prototype._onended = function () {
  30888. this.isPlaying = false;
  30889. if (this.onended) {
  30890. this.onended();
  30891. }
  30892. };
  30893. /**
  30894. * Stop the sound
  30895. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30896. */
  30897. Sound.prototype.stop = function (time) {
  30898. if (this.isPlaying) {
  30899. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30900. this._soundSource.stop(stopTime);
  30901. this.isPlaying = false;
  30902. }
  30903. };
  30904. Sound.prototype.pause = function () {
  30905. if (this.isPlaying) {
  30906. this.stop(0);
  30907. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30908. this.isPaused = true;
  30909. }
  30910. };
  30911. Sound.prototype.setVolume = function (newVolume, time) {
  30912. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30913. if (time) {
  30914. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30915. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30916. }
  30917. else {
  30918. this._soundGain.gain.value = newVolume;
  30919. }
  30920. }
  30921. this._volume = newVolume;
  30922. };
  30923. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30924. this._playbackRate = newPlaybackRate;
  30925. if (this.isPlaying) {
  30926. this._soundSource.playbackRate.value = this._playbackRate;
  30927. }
  30928. };
  30929. Sound.prototype.getVolume = function () {
  30930. return this._volume;
  30931. };
  30932. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30933. var _this = this;
  30934. this._connectedMesh = meshToConnectTo;
  30935. if (!this.spatialSound) {
  30936. this.spatialSound = true;
  30937. this._createSpatialParameters();
  30938. if (this.isPlaying && this.loop) {
  30939. this.stop();
  30940. this.play();
  30941. }
  30942. }
  30943. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30944. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30945. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30946. };
  30947. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30948. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30949. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30950. this._updateDirection();
  30951. }
  30952. };
  30953. return Sound;
  30954. })();
  30955. BABYLON.Sound = Sound;
  30956. })(BABYLON || (BABYLON = {}));
  30957. var BABYLON;
  30958. (function (BABYLON) {
  30959. var SoundTrack = (function () {
  30960. function SoundTrack(scene, options) {
  30961. this.id = -1;
  30962. this._isMainTrack = false;
  30963. this._scene = scene;
  30964. this._audioEngine = BABYLON.Engine.audioEngine;
  30965. this.soundCollection = new Array();
  30966. if (this._audioEngine.canUseWebAudio) {
  30967. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30968. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30969. if (options) {
  30970. if (options.volume) {
  30971. this._outputAudioNode.gain.value = options.volume;
  30972. }
  30973. if (options.mainTrack) {
  30974. this._isMainTrack = options.mainTrack;
  30975. }
  30976. }
  30977. }
  30978. if (!this._isMainTrack) {
  30979. this._scene.soundTracks.push(this);
  30980. this.id = this._scene.soundTracks.length - 1;
  30981. }
  30982. }
  30983. SoundTrack.prototype.dispose = function () {
  30984. if (this._audioEngine.canUseWebAudio) {
  30985. if (this._connectedAnalyser) {
  30986. this._connectedAnalyser.stopDebugCanvas();
  30987. }
  30988. while (this.soundCollection.length) {
  30989. this.soundCollection[0].dispose();
  30990. }
  30991. if (this._outputAudioNode) {
  30992. this._outputAudioNode.disconnect();
  30993. }
  30994. this._outputAudioNode = null;
  30995. }
  30996. };
  30997. SoundTrack.prototype.AddSound = function (sound) {
  30998. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30999. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  31000. }
  31001. if (sound.soundTrackId) {
  31002. if (sound.soundTrackId === -1) {
  31003. this._scene.mainSoundTrack.RemoveSound(sound);
  31004. }
  31005. else {
  31006. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  31007. }
  31008. }
  31009. this.soundCollection.push(sound);
  31010. sound.soundTrackId = this.id;
  31011. };
  31012. SoundTrack.prototype.RemoveSound = function (sound) {
  31013. var index = this.soundCollection.indexOf(sound);
  31014. if (index !== -1) {
  31015. this.soundCollection.splice(index, 1);
  31016. }
  31017. };
  31018. SoundTrack.prototype.setVolume = function (newVolume) {
  31019. if (this._audioEngine.canUseWebAudio) {
  31020. this._outputAudioNode.gain.value = newVolume;
  31021. }
  31022. };
  31023. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  31024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31025. for (var i = 0; i < this.soundCollection.length; i++) {
  31026. this.soundCollection[i].switchPanningModelToHRTF();
  31027. }
  31028. }
  31029. };
  31030. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  31031. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31032. for (var i = 0; i < this.soundCollection.length; i++) {
  31033. this.soundCollection[i].switchPanningModelToEqualPower();
  31034. }
  31035. }
  31036. };
  31037. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  31038. if (this._connectedAnalyser) {
  31039. this._connectedAnalyser.stopDebugCanvas();
  31040. }
  31041. this._connectedAnalyser = analyser;
  31042. if (this._audioEngine.canUseWebAudio) {
  31043. this._outputAudioNode.disconnect();
  31044. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  31045. }
  31046. };
  31047. return SoundTrack;
  31048. })();
  31049. BABYLON.SoundTrack = SoundTrack;
  31050. })(BABYLON || (BABYLON = {}));
  31051. var BABYLON;
  31052. (function (BABYLON) {
  31053. var DebugLayer = (function () {
  31054. function DebugLayer(scene) {
  31055. var _this = this;
  31056. this._transformationMatrix = BABYLON.Matrix.Identity();
  31057. this._enabled = false;
  31058. this._labelsEnabled = false;
  31059. this._displayStatistics = true;
  31060. this._displayTree = false;
  31061. this._displayLogs = false;
  31062. this._identityMatrix = BABYLON.Matrix.Identity();
  31063. this.axisRatio = 0.02;
  31064. this.accentColor = "orange";
  31065. this._scene = scene;
  31066. this._syncPositions = function () {
  31067. var engine = _this._scene.getEngine();
  31068. var canvasRect = engine.getRenderingCanvasClientRect();
  31069. if (_this._showUI) {
  31070. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  31071. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  31072. _this._statsDiv.style.width = "400px";
  31073. _this._statsDiv.style.height = "auto";
  31074. _this._statsSubsetDiv.style.maxHeight = "240px";
  31075. _this._optionsDiv.style.left = "0px";
  31076. _this._optionsDiv.style.top = "10px";
  31077. _this._optionsDiv.style.width = "200px";
  31078. _this._optionsDiv.style.height = "auto";
  31079. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  31080. _this._logDiv.style.left = "0px";
  31081. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  31082. _this._logDiv.style.width = "600px";
  31083. _this._logDiv.style.height = "160px";
  31084. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  31085. _this._treeDiv.style.top = "10px";
  31086. _this._treeDiv.style.width = "300px";
  31087. _this._treeDiv.style.height = "auto";
  31088. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  31089. }
  31090. _this._globalDiv.style.left = canvasRect.left + "px";
  31091. _this._globalDiv.style.top = canvasRect.top + "px";
  31092. _this._drawingCanvas.style.left = "0px";
  31093. _this._drawingCanvas.style.top = "0px";
  31094. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  31095. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  31096. var devicePixelRatio = window.devicePixelRatio || 1;
  31097. var context = _this._drawingContext;
  31098. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  31099. context.mozBackingStorePixelRatio ||
  31100. context.msBackingStorePixelRatio ||
  31101. context.oBackingStorePixelRatio ||
  31102. context.backingStorePixelRatio || 1;
  31103. _this._ratio = devicePixelRatio / backingStoreRatio;
  31104. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  31105. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  31106. };
  31107. this._onCanvasClick = function (evt) {
  31108. _this._clickPosition = {
  31109. x: evt.clientX * _this._ratio,
  31110. y: evt.clientY * _this._ratio
  31111. };
  31112. };
  31113. this._syncUI = function () {
  31114. if (_this._showUI) {
  31115. if (_this._displayStatistics) {
  31116. _this._displayStats();
  31117. _this._statsDiv.style.display = "";
  31118. }
  31119. else {
  31120. _this._statsDiv.style.display = "none";
  31121. }
  31122. if (_this._displayLogs) {
  31123. _this._logDiv.style.display = "";
  31124. }
  31125. else {
  31126. _this._logDiv.style.display = "none";
  31127. }
  31128. if (_this._displayTree) {
  31129. _this._treeDiv.style.display = "";
  31130. if (_this._needToRefreshMeshesTree) {
  31131. _this._needToRefreshMeshesTree = false;
  31132. _this._refreshMeshesTreeContent();
  31133. }
  31134. }
  31135. else {
  31136. _this._treeDiv.style.display = "none";
  31137. }
  31138. }
  31139. };
  31140. this._syncData = function () {
  31141. if (_this._labelsEnabled || !_this._showUI) {
  31142. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  31143. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  31144. var engine = _this._scene.getEngine();
  31145. var viewport = _this._camera.viewport;
  31146. var globalViewport = viewport.toGlobal(engine);
  31147. // Meshes
  31148. var meshes = _this._camera.getActiveMeshes();
  31149. for (var index = 0; index < meshes.length; index++) {
  31150. var mesh = meshes.data[index];
  31151. var position = mesh.getBoundingInfo().boundingSphere.center;
  31152. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31153. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  31154. _this._renderAxis(projectedPosition, mesh, globalViewport);
  31155. }
  31156. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  31157. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  31158. }
  31159. }
  31160. // Cameras
  31161. var cameras = _this._scene.cameras;
  31162. for (index = 0; index < cameras.length; index++) {
  31163. var camera = cameras[index];
  31164. if (camera === _this._camera) {
  31165. continue;
  31166. }
  31167. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  31168. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  31169. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  31170. _this._camera.detachControl(engine.getRenderingCanvas());
  31171. _this._camera = camera;
  31172. _this._camera.attachControl(engine.getRenderingCanvas());
  31173. }, function () { return "purple"; });
  31174. }
  31175. }
  31176. // Lights
  31177. var lights = _this._scene.lights;
  31178. for (index = 0; index < lights.length; index++) {
  31179. var light = lights[index];
  31180. if (light.position) {
  31181. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  31182. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  31183. _this._renderLabel(light.name, projectedPosition, -20, function () {
  31184. light.setEnabled(!light.isEnabled());
  31185. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  31186. }
  31187. }
  31188. }
  31189. }
  31190. _this._clickPosition = undefined;
  31191. };
  31192. }
  31193. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  31194. while (this._treeSubsetDiv.hasChildNodes()) {
  31195. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  31196. }
  31197. // Add meshes
  31198. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  31199. sortedArray.sort(function (a, b) {
  31200. if (a.name === b.name) {
  31201. return 0;
  31202. }
  31203. return (a.name > b.name) ? 1 : -1;
  31204. });
  31205. for (var index = 0; index < sortedArray.length; index++) {
  31206. var mesh = sortedArray[index];
  31207. if (!mesh.isEnabled()) {
  31208. continue;
  31209. }
  31210. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  31211. m.isVisible = element.checked;
  31212. }, mesh);
  31213. }
  31214. };
  31215. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  31216. this._drawingContext.beginPath();
  31217. this._drawingContext.moveTo(zero.x, zero.y);
  31218. this._drawingContext.lineTo(unit.x, unit.y);
  31219. this._drawingContext.strokeStyle = color;
  31220. this._drawingContext.lineWidth = 4;
  31221. this._drawingContext.stroke();
  31222. this._drawingContext.font = "normal 14px Segoe UI";
  31223. this._drawingContext.fillStyle = color;
  31224. this._drawingContext.fillText(label, unitText.x, unitText.y);
  31225. };
  31226. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  31227. var position = mesh.getBoundingInfo().boundingSphere.center;
  31228. var worldMatrix = mesh.getWorldMatrix();
  31229. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  31230. var unit = (unprojectedVector.subtract(position)).length();
  31231. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31232. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31233. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  31234. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31235. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  31236. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  31237. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  31238. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  31239. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  31240. };
  31241. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  31242. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  31243. this._drawingContext.font = "normal 12px Segoe UI";
  31244. var textMetrics = this._drawingContext.measureText(text);
  31245. var centerX = projectedPosition.x - textMetrics.width / 2;
  31246. var centerY = projectedPosition.y;
  31247. var clientRect = this._drawingCanvas.getBoundingClientRect();
  31248. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  31249. onClick();
  31250. }
  31251. this._drawingContext.beginPath();
  31252. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  31253. this._drawingContext.fillStyle = getFillStyle();
  31254. this._drawingContext.globalAlpha = 0.5;
  31255. this._drawingContext.fill();
  31256. this._drawingContext.globalAlpha = 1.0;
  31257. this._drawingContext.strokeStyle = '#FFFFFF';
  31258. this._drawingContext.lineWidth = 1;
  31259. this._drawingContext.stroke();
  31260. this._drawingContext.fillStyle = "#FFFFFF";
  31261. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  31262. this._drawingContext.beginPath();
  31263. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  31264. this._drawingContext.fill();
  31265. }
  31266. };
  31267. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  31268. if (!this._clickPosition) {
  31269. return false;
  31270. }
  31271. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  31272. return false;
  31273. }
  31274. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  31275. return false;
  31276. }
  31277. return true;
  31278. };
  31279. DebugLayer.prototype.isVisible = function () {
  31280. return this._enabled;
  31281. };
  31282. DebugLayer.prototype.hide = function () {
  31283. if (!this._enabled) {
  31284. return;
  31285. }
  31286. this._enabled = false;
  31287. var engine = this._scene.getEngine();
  31288. this._scene.unregisterBeforeRender(this._syncData);
  31289. this._scene.unregisterAfterRender(this._syncUI);
  31290. document.body.removeChild(this._globalDiv);
  31291. window.removeEventListener("resize", this._syncPositions);
  31292. this._scene.forceShowBoundingBoxes = false;
  31293. this._scene.forceWireframe = false;
  31294. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  31295. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  31296. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  31297. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  31298. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  31299. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  31300. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  31301. BABYLON.StandardMaterial.LightmapEnabled = true;
  31302. this._scene.shadowsEnabled = true;
  31303. this._scene.particlesEnabled = true;
  31304. this._scene.postProcessesEnabled = true;
  31305. this._scene.collisionsEnabled = true;
  31306. this._scene.lightsEnabled = true;
  31307. this._scene.texturesEnabled = true;
  31308. this._scene.lensFlaresEnabled = true;
  31309. this._scene.proceduralTexturesEnabled = true;
  31310. this._scene.renderTargetsEnabled = true;
  31311. this._scene.probesEnabled = true;
  31312. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  31313. };
  31314. DebugLayer.prototype.show = function (showUI, camera) {
  31315. if (showUI === void 0) { showUI = true; }
  31316. if (camera === void 0) { camera = null; }
  31317. if (this._enabled) {
  31318. return;
  31319. }
  31320. this._enabled = true;
  31321. if (camera) {
  31322. this._camera = camera;
  31323. }
  31324. else {
  31325. this._camera = this._scene.activeCamera;
  31326. }
  31327. this._showUI = showUI;
  31328. var engine = this._scene.getEngine();
  31329. this._globalDiv = document.createElement("div");
  31330. document.body.appendChild(this._globalDiv);
  31331. this._generateDOMelements();
  31332. window.addEventListener("resize", this._syncPositions);
  31333. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  31334. this._syncPositions();
  31335. this._scene.registerBeforeRender(this._syncData);
  31336. this._scene.registerAfterRender(this._syncUI);
  31337. };
  31338. DebugLayer.prototype._clearLabels = function () {
  31339. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  31340. for (var index = 0; index < this._scene.meshes.length; index++) {
  31341. var mesh = this._scene.meshes[index];
  31342. mesh.renderOverlay = false;
  31343. }
  31344. };
  31345. DebugLayer.prototype._generateheader = function (root, text) {
  31346. var header = document.createElement("div");
  31347. header.innerHTML = text + "&nbsp;";
  31348. header.style.textAlign = "right";
  31349. header.style.width = "100%";
  31350. header.style.color = "white";
  31351. header.style.backgroundColor = "Black";
  31352. header.style.padding = "5px 5px 4px 0px";
  31353. header.style.marginLeft = "-5px";
  31354. header.style.fontWeight = "bold";
  31355. root.appendChild(header);
  31356. };
  31357. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  31358. var label = document.createElement("label");
  31359. label.innerHTML = title;
  31360. label.style.color = color;
  31361. root.appendChild(label);
  31362. root.appendChild(document.createElement("br"));
  31363. };
  31364. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  31365. if (tag === void 0) { tag = null; }
  31366. var label = document.createElement("label");
  31367. var boundingBoxesCheckbox = document.createElement("input");
  31368. boundingBoxesCheckbox.type = "checkbox";
  31369. boundingBoxesCheckbox.checked = initialState;
  31370. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  31371. task(evt.target, tag);
  31372. });
  31373. label.appendChild(boundingBoxesCheckbox);
  31374. var container = document.createElement("span");
  31375. var leftPart = document.createElement("span");
  31376. var rightPart = document.createElement("span");
  31377. rightPart.style.cssFloat = "right";
  31378. leftPart.innerHTML = leftTitle;
  31379. rightPart.innerHTML = rightTitle;
  31380. rightPart.style.fontSize = "12px";
  31381. rightPart.style.maxWidth = "200px";
  31382. container.appendChild(leftPart);
  31383. container.appendChild(rightPart);
  31384. label.appendChild(container);
  31385. root.appendChild(label);
  31386. root.appendChild(document.createElement("br"));
  31387. };
  31388. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  31389. if (tag === void 0) { tag = null; }
  31390. var label = document.createElement("label");
  31391. var checkBox = document.createElement("input");
  31392. checkBox.type = "checkbox";
  31393. checkBox.checked = initialState;
  31394. checkBox.addEventListener("change", function (evt) {
  31395. task(evt.target, tag);
  31396. });
  31397. label.appendChild(checkBox);
  31398. label.appendChild(document.createTextNode(title));
  31399. root.appendChild(label);
  31400. root.appendChild(document.createElement("br"));
  31401. };
  31402. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  31403. if (tag === void 0) { tag = null; }
  31404. var button = document.createElement("button");
  31405. button.innerHTML = title;
  31406. button.style.height = "24px";
  31407. button.style.color = "#444444";
  31408. button.style.border = "1px solid white";
  31409. button.className = "debugLayerButton";
  31410. button.addEventListener("click", function (evt) {
  31411. task(evt.target, tag);
  31412. });
  31413. root.appendChild(button);
  31414. root.appendChild(document.createElement("br"));
  31415. };
  31416. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  31417. if (tag === void 0) { tag = null; }
  31418. var label = document.createElement("label");
  31419. var boundingBoxesRadio = document.createElement("input");
  31420. boundingBoxesRadio.type = "radio";
  31421. boundingBoxesRadio.name = name;
  31422. boundingBoxesRadio.checked = initialState;
  31423. boundingBoxesRadio.addEventListener("change", function (evt) {
  31424. task(evt.target, tag);
  31425. });
  31426. label.appendChild(boundingBoxesRadio);
  31427. label.appendChild(document.createTextNode(title));
  31428. root.appendChild(label);
  31429. root.appendChild(document.createElement("br"));
  31430. };
  31431. DebugLayer.prototype._generateDOMelements = function () {
  31432. var _this = this;
  31433. this._globalDiv.id = "DebugLayer";
  31434. this._globalDiv.style.position = "absolute";
  31435. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  31436. this._globalDiv.style.fontSize = "14px";
  31437. this._globalDiv.style.color = "white";
  31438. // Drawing canvas
  31439. this._drawingCanvas = document.createElement("canvas");
  31440. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  31441. this._drawingCanvas.style.position = "absolute";
  31442. this._drawingCanvas.style.pointerEvents = "none";
  31443. this._drawingContext = this._drawingCanvas.getContext("2d");
  31444. this._globalDiv.appendChild(this._drawingCanvas);
  31445. if (this._showUI) {
  31446. var background = "rgba(128, 128, 128, 0.4)";
  31447. var border = "rgb(180, 180, 180) solid 1px";
  31448. // Stats
  31449. this._statsDiv = document.createElement("div");
  31450. this._statsDiv.id = "DebugLayerStats";
  31451. this._statsDiv.style.border = border;
  31452. this._statsDiv.style.position = "absolute";
  31453. this._statsDiv.style.background = background;
  31454. this._statsDiv.style.padding = "0px 0px 0px 5px";
  31455. this._generateheader(this._statsDiv, "STATISTICS");
  31456. this._statsSubsetDiv = document.createElement("div");
  31457. this._statsSubsetDiv.style.paddingTop = "5px";
  31458. this._statsSubsetDiv.style.paddingBottom = "5px";
  31459. this._statsSubsetDiv.style.overflowY = "auto";
  31460. this._statsDiv.appendChild(this._statsSubsetDiv);
  31461. // Tree
  31462. this._treeDiv = document.createElement("div");
  31463. this._treeDiv.id = "DebugLayerTree";
  31464. this._treeDiv.style.border = border;
  31465. this._treeDiv.style.position = "absolute";
  31466. this._treeDiv.style.background = background;
  31467. this._treeDiv.style.padding = "0px 0px 0px 5px";
  31468. this._treeDiv.style.display = "none";
  31469. this._generateheader(this._treeDiv, "MESHES TREE");
  31470. this._treeSubsetDiv = document.createElement("div");
  31471. this._treeSubsetDiv.style.paddingTop = "5px";
  31472. this._treeSubsetDiv.style.paddingRight = "5px";
  31473. this._treeSubsetDiv.style.overflowY = "auto";
  31474. this._treeSubsetDiv.style.maxHeight = "300px";
  31475. this._treeDiv.appendChild(this._treeSubsetDiv);
  31476. this._needToRefreshMeshesTree = true;
  31477. // Logs
  31478. this._logDiv = document.createElement("div");
  31479. this._logDiv.style.border = border;
  31480. this._logDiv.id = "DebugLayerLogs";
  31481. this._logDiv.style.position = "absolute";
  31482. this._logDiv.style.background = background;
  31483. this._logDiv.style.padding = "0px 0px 0px 5px";
  31484. this._logDiv.style.display = "none";
  31485. this._generateheader(this._logDiv, "LOGS");
  31486. this._logSubsetDiv = document.createElement("div");
  31487. this._logSubsetDiv.style.height = "127px";
  31488. this._logSubsetDiv.style.paddingTop = "5px";
  31489. this._logSubsetDiv.style.overflowY = "auto";
  31490. this._logSubsetDiv.style.fontSize = "12px";
  31491. this._logSubsetDiv.style.fontFamily = "consolas";
  31492. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  31493. this._logDiv.appendChild(this._logSubsetDiv);
  31494. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  31495. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  31496. };
  31497. // Options
  31498. this._optionsDiv = document.createElement("div");
  31499. this._optionsDiv.id = "DebugLayerOptions";
  31500. this._optionsDiv.style.border = border;
  31501. this._optionsDiv.style.position = "absolute";
  31502. this._optionsDiv.style.background = background;
  31503. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  31504. this._optionsDiv.style.overflowY = "auto";
  31505. this._generateheader(this._optionsDiv, "OPTIONS");
  31506. this._optionsSubsetDiv = document.createElement("div");
  31507. this._optionsSubsetDiv.style.paddingTop = "5px";
  31508. this._optionsSubsetDiv.style.paddingBottom = "5px";
  31509. this._optionsSubsetDiv.style.overflowY = "auto";
  31510. this._optionsSubsetDiv.style.maxHeight = "200px";
  31511. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  31512. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  31513. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  31514. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  31515. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  31516. _this._displayTree = element.checked;
  31517. _this._needToRefreshMeshesTree = true;
  31518. });
  31519. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31520. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  31521. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  31522. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  31523. _this._labelsEnabled = element.checked;
  31524. if (!_this._labelsEnabled) {
  31525. _this._clearLabels();
  31526. }
  31527. });
  31528. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  31529. if (element.checked) {
  31530. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  31531. }
  31532. else {
  31533. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  31534. }
  31535. });
  31536. ;
  31537. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31538. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  31539. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  31540. if (element.checked) {
  31541. _this._scene.forceWireframe = false;
  31542. _this._scene.forcePointsCloud = false;
  31543. }
  31544. });
  31545. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  31546. if (element.checked) {
  31547. _this._scene.forceWireframe = true;
  31548. _this._scene.forcePointsCloud = false;
  31549. }
  31550. });
  31551. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  31552. if (element.checked) {
  31553. _this._scene.forceWireframe = false;
  31554. _this._scene.forcePointsCloud = true;
  31555. }
  31556. });
  31557. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31558. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  31559. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  31560. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  31561. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  31562. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  31563. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  31564. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  31565. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  31566. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  31567. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  31568. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31569. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  31570. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  31571. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  31572. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  31573. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  31574. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  31575. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  31576. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  31577. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  31578. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  31579. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  31580. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  31581. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  31582. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  31583. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  31584. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31585. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31586. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  31587. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  31588. if (element.checked) {
  31589. _this._scene.headphone = true;
  31590. }
  31591. });
  31592. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  31593. if (element.checked) {
  31594. _this._scene.headphone = false;
  31595. }
  31596. });
  31597. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  31598. _this._scene.audioEnabled = !element.checked;
  31599. });
  31600. }
  31601. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31602. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  31603. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  31604. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  31605. this._globalDiv.appendChild(this._statsDiv);
  31606. this._globalDiv.appendChild(this._logDiv);
  31607. this._globalDiv.appendChild(this._optionsDiv);
  31608. this._globalDiv.appendChild(this._treeDiv);
  31609. }
  31610. };
  31611. DebugLayer.prototype._displayStats = function () {
  31612. var scene = this._scene;
  31613. var engine = scene.getEngine();
  31614. var glInfo = engine.getGlInfo();
  31615. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  31616. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31617. + "<b>Count</b><br>"
  31618. + "Total meshes: " + scene.meshes.length + "<br>"
  31619. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  31620. + "Total materials: " + scene.materials.length + "<br>"
  31621. + "Total textures: " + scene.textures.length + "<br>"
  31622. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  31623. + "Active indices: " + scene.getActiveIndices() + "<br>"
  31624. + "Active bones: " + scene.getActiveBones() + "<br>"
  31625. + "Active particles: " + scene.getActiveParticles() + "<br>"
  31626. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  31627. + "<b>Duration</b><br>"
  31628. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  31629. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  31630. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  31631. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  31632. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  31633. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  31634. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  31635. + "</div>"
  31636. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  31637. + "<b>Extensions</b><br>"
  31638. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  31639. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  31640. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  31641. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  31642. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  31643. + "<b>Caps.</b><br>"
  31644. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  31645. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  31646. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  31647. + "</div><br>"
  31648. + "<b>Info</b><br>"
  31649. + glInfo.version + "<br>"
  31650. + glInfo.renderer + "<br>";
  31651. if (this.customStatsFunction) {
  31652. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  31653. }
  31654. };
  31655. return DebugLayer;
  31656. })();
  31657. BABYLON.DebugLayer = DebugLayer;
  31658. })(BABYLON || (BABYLON = {}));
  31659. var BABYLON;
  31660. (function (BABYLON) {
  31661. var RawTexture = (function (_super) {
  31662. __extends(RawTexture, _super);
  31663. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31664. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31665. if (invertY === void 0) { invertY = false; }
  31666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31667. _super.call(this, null, scene, !generateMipMaps, invertY);
  31668. this.format = format;
  31669. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31670. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31671. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31672. }
  31673. RawTexture.prototype.update = function (data) {
  31674. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31675. };
  31676. // Statics
  31677. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31678. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31679. if (invertY === void 0) { invertY = false; }
  31680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31681. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31682. };
  31683. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31684. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31685. if (invertY === void 0) { invertY = false; }
  31686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31687. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31688. };
  31689. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31690. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31691. if (invertY === void 0) { invertY = false; }
  31692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31693. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31694. };
  31695. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31696. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31697. if (invertY === void 0) { invertY = false; }
  31698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31699. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31700. };
  31701. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31702. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31703. if (invertY === void 0) { invertY = false; }
  31704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31705. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31706. };
  31707. return RawTexture;
  31708. })(BABYLON.Texture);
  31709. BABYLON.RawTexture = RawTexture;
  31710. })(BABYLON || (BABYLON = {}));
  31711. var BABYLON;
  31712. (function (BABYLON) {
  31713. var IndexedVector2 = (function (_super) {
  31714. __extends(IndexedVector2, _super);
  31715. function IndexedVector2(original, index) {
  31716. _super.call(this, original.x, original.y);
  31717. this.index = index;
  31718. }
  31719. return IndexedVector2;
  31720. })(BABYLON.Vector2);
  31721. var PolygonPoints = (function () {
  31722. function PolygonPoints() {
  31723. this.elements = new Array();
  31724. }
  31725. PolygonPoints.prototype.add = function (originalPoints) {
  31726. var _this = this;
  31727. var result = new Array();
  31728. originalPoints.forEach(function (point) {
  31729. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31730. var newPoint = new IndexedVector2(point, _this.elements.length);
  31731. result.push(newPoint);
  31732. _this.elements.push(newPoint);
  31733. }
  31734. });
  31735. return result;
  31736. };
  31737. PolygonPoints.prototype.computeBounds = function () {
  31738. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31739. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31740. this.elements.forEach(function (point) {
  31741. // x
  31742. if (point.x < lmin.x) {
  31743. lmin.x = point.x;
  31744. }
  31745. else if (point.x > lmax.x) {
  31746. lmax.x = point.x;
  31747. }
  31748. // y
  31749. if (point.y < lmin.y) {
  31750. lmin.y = point.y;
  31751. }
  31752. else if (point.y > lmax.y) {
  31753. lmax.y = point.y;
  31754. }
  31755. });
  31756. return {
  31757. min: lmin,
  31758. max: lmax,
  31759. width: lmax.x - lmin.x,
  31760. height: lmax.y - lmin.y
  31761. };
  31762. };
  31763. return PolygonPoints;
  31764. })();
  31765. var Polygon = (function () {
  31766. function Polygon() {
  31767. }
  31768. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31769. return [
  31770. new BABYLON.Vector2(xmin, ymin),
  31771. new BABYLON.Vector2(xmax, ymin),
  31772. new BABYLON.Vector2(xmax, ymax),
  31773. new BABYLON.Vector2(xmin, ymax)
  31774. ];
  31775. };
  31776. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31777. if (cx === void 0) { cx = 0; }
  31778. if (cy === void 0) { cy = 0; }
  31779. if (numberOfSides === void 0) { numberOfSides = 32; }
  31780. var result = new Array();
  31781. var angle = 0;
  31782. var increment = (Math.PI * 2) / numberOfSides;
  31783. for (var i = 0; i < numberOfSides; i++) {
  31784. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31785. angle -= increment;
  31786. }
  31787. return result;
  31788. };
  31789. Polygon.Parse = function (input) {
  31790. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31791. var i, result = [];
  31792. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31793. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31794. }
  31795. return result;
  31796. };
  31797. Polygon.StartingAt = function (x, y) {
  31798. return BABYLON.Path2.StartingAt(x, y);
  31799. };
  31800. return Polygon;
  31801. })();
  31802. BABYLON.Polygon = Polygon;
  31803. var PolygonMeshBuilder = (function () {
  31804. function PolygonMeshBuilder(name, contours, scene) {
  31805. this._points = new PolygonPoints();
  31806. this._outlinepoints = new PolygonPoints();
  31807. this._holes = [];
  31808. if (!("poly2tri" in window)) {
  31809. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31810. }
  31811. this._name = name;
  31812. this._scene = scene;
  31813. var points;
  31814. if (contours instanceof BABYLON.Path2) {
  31815. points = contours.getPoints();
  31816. }
  31817. else {
  31818. points = contours;
  31819. }
  31820. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31821. this._outlinepoints.add(points);
  31822. }
  31823. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31824. this._swctx.addHole(this._points.add(hole));
  31825. var holepoints = new PolygonPoints();
  31826. holepoints.add(hole);
  31827. this._holes.push(holepoints);
  31828. return this;
  31829. };
  31830. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31831. var _this = this;
  31832. if (updatable === void 0) { updatable = false; }
  31833. var result = new BABYLON.Mesh(this._name, this._scene);
  31834. var normals = [];
  31835. var positions = [];
  31836. var uvs = [];
  31837. var bounds = this._points.computeBounds();
  31838. this._points.elements.forEach(function (p) {
  31839. normals.push(0, 1.0, 0);
  31840. positions.push(p.x, 0, p.y);
  31841. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31842. });
  31843. var indices = [];
  31844. this._swctx.triangulate();
  31845. this._swctx.getTriangles().forEach(function (triangle) {
  31846. triangle.getPoints().forEach(function (point) {
  31847. indices.push(point.index);
  31848. });
  31849. });
  31850. if (depth > 0) {
  31851. var positionscount = (positions.length / 3); //get the current pointcount
  31852. this._points.elements.forEach(function (p) {
  31853. normals.push(0, -1.0, 0);
  31854. positions.push(p.x, -depth, p.y);
  31855. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31856. });
  31857. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31858. var p2;
  31859. var poscounter = 0;
  31860. this._swctx.getTriangles().forEach(function (triangle) {
  31861. triangle.getPoints().forEach(function (point) {
  31862. switch (poscounter) {
  31863. case 0:
  31864. p1 = point;
  31865. break;
  31866. case 1:
  31867. p2 = point;
  31868. break;
  31869. case 2:
  31870. indices.push(point.index + positionscount);
  31871. indices.push(p2.index + positionscount);
  31872. indices.push(p1.index + positionscount);
  31873. poscounter = -1;
  31874. break;
  31875. }
  31876. poscounter++;
  31877. //indices.push((<IndexedVector2>point).index + positionscount);
  31878. });
  31879. });
  31880. //Add the sides
  31881. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31882. this._holes.forEach(function (hole) {
  31883. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31884. });
  31885. }
  31886. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31887. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31888. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31889. result.setIndices(indices);
  31890. return result;
  31891. };
  31892. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31893. var StartIndex = positions.length / 3;
  31894. var ulength = 0;
  31895. for (var i = 0; i < points.elements.length; i++) {
  31896. var p = points.elements[i];
  31897. var p1;
  31898. if ((i + 1) > points.elements.length - 1) {
  31899. p1 = points.elements[0];
  31900. }
  31901. else {
  31902. p1 = points.elements[i + 1];
  31903. }
  31904. positions.push(p.x, 0, p.y);
  31905. positions.push(p.x, -depth, p.y);
  31906. positions.push(p1.x, 0, p1.y);
  31907. positions.push(p1.x, -depth, p1.y);
  31908. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31909. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31910. var v3 = v2.subtract(v1);
  31911. var v4 = new BABYLON.Vector3(0, 1, 0);
  31912. var vn = BABYLON.Vector3.Cross(v3, v4);
  31913. vn = vn.normalize();
  31914. uvs.push(ulength / bounds.width, 0);
  31915. uvs.push(ulength / bounds.width, 1);
  31916. ulength += v3.length();
  31917. uvs.push((ulength / bounds.width), 0);
  31918. uvs.push((ulength / bounds.width), 1);
  31919. if (!flip) {
  31920. normals.push(-vn.x, -vn.y, -vn.z);
  31921. normals.push(-vn.x, -vn.y, -vn.z);
  31922. normals.push(-vn.x, -vn.y, -vn.z);
  31923. normals.push(-vn.x, -vn.y, -vn.z);
  31924. indices.push(StartIndex);
  31925. indices.push(StartIndex + 1);
  31926. indices.push(StartIndex + 2);
  31927. indices.push(StartIndex + 1);
  31928. indices.push(StartIndex + 3);
  31929. indices.push(StartIndex + 2);
  31930. }
  31931. else {
  31932. normals.push(vn.x, vn.y, vn.z);
  31933. normals.push(vn.x, vn.y, vn.z);
  31934. normals.push(vn.x, vn.y, vn.z);
  31935. normals.push(vn.x, vn.y, vn.z);
  31936. indices.push(StartIndex);
  31937. indices.push(StartIndex + 2);
  31938. indices.push(StartIndex + 1);
  31939. indices.push(StartIndex + 1);
  31940. indices.push(StartIndex + 2);
  31941. indices.push(StartIndex + 3);
  31942. }
  31943. StartIndex += 4;
  31944. }
  31945. ;
  31946. };
  31947. return PolygonMeshBuilder;
  31948. })();
  31949. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31950. })(BABYLON || (BABYLON = {}));
  31951. var BABYLON;
  31952. (function (BABYLON) {
  31953. var SimplificationSettings = (function () {
  31954. function SimplificationSettings(quality, distance, optimizeMesh) {
  31955. this.quality = quality;
  31956. this.distance = distance;
  31957. this.optimizeMesh = optimizeMesh;
  31958. }
  31959. return SimplificationSettings;
  31960. })();
  31961. BABYLON.SimplificationSettings = SimplificationSettings;
  31962. var SimplificationQueue = (function () {
  31963. function SimplificationQueue() {
  31964. this.running = false;
  31965. this._simplificationArray = [];
  31966. }
  31967. SimplificationQueue.prototype.addTask = function (task) {
  31968. this._simplificationArray.push(task);
  31969. };
  31970. SimplificationQueue.prototype.executeNext = function () {
  31971. var task = this._simplificationArray.pop();
  31972. if (task) {
  31973. this.running = true;
  31974. this.runSimplification(task);
  31975. }
  31976. else {
  31977. this.running = false;
  31978. }
  31979. };
  31980. SimplificationQueue.prototype.runSimplification = function (task) {
  31981. var _this = this;
  31982. if (task.parallelProcessing) {
  31983. //parallel simplifier
  31984. task.settings.forEach(function (setting) {
  31985. var simplifier = _this.getSimplifier(task);
  31986. simplifier.simplify(setting, function (newMesh) {
  31987. task.mesh.addLODLevel(setting.distance, newMesh);
  31988. newMesh.isVisible = true;
  31989. //check if it is the last
  31990. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31991. //all done, run the success callback.
  31992. task.successCallback();
  31993. }
  31994. _this.executeNext();
  31995. });
  31996. });
  31997. }
  31998. else {
  31999. //single simplifier.
  32000. var simplifier = this.getSimplifier(task);
  32001. var runDecimation = function (setting, callback) {
  32002. simplifier.simplify(setting, function (newMesh) {
  32003. task.mesh.addLODLevel(setting.distance, newMesh);
  32004. newMesh.isVisible = true;
  32005. //run the next quality level
  32006. callback();
  32007. });
  32008. };
  32009. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  32010. runDecimation(task.settings[loop.index], function () {
  32011. loop.executeNext();
  32012. });
  32013. }, function () {
  32014. //execution ended, run the success callback.
  32015. if (task.successCallback) {
  32016. task.successCallback();
  32017. }
  32018. _this.executeNext();
  32019. });
  32020. }
  32021. };
  32022. SimplificationQueue.prototype.getSimplifier = function (task) {
  32023. switch (task.simplificationType) {
  32024. case SimplificationType.QUADRATIC:
  32025. default:
  32026. return new QuadraticErrorSimplification(task.mesh);
  32027. }
  32028. };
  32029. return SimplificationQueue;
  32030. })();
  32031. BABYLON.SimplificationQueue = SimplificationQueue;
  32032. /**
  32033. * The implemented types of simplification.
  32034. * At the moment only Quadratic Error Decimation is implemented.
  32035. */
  32036. (function (SimplificationType) {
  32037. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  32038. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  32039. var SimplificationType = BABYLON.SimplificationType;
  32040. var DecimationTriangle = (function () {
  32041. function DecimationTriangle(vertices) {
  32042. this.vertices = vertices;
  32043. this.error = new Array(4);
  32044. this.deleted = false;
  32045. this.isDirty = false;
  32046. this.deletePending = false;
  32047. this.borderFactor = 0;
  32048. }
  32049. return DecimationTriangle;
  32050. })();
  32051. BABYLON.DecimationTriangle = DecimationTriangle;
  32052. var DecimationVertex = (function () {
  32053. function DecimationVertex(position, id) {
  32054. this.position = position;
  32055. this.id = id;
  32056. this.isBorder = true;
  32057. this.q = new QuadraticMatrix();
  32058. this.triangleCount = 0;
  32059. this.triangleStart = 0;
  32060. this.originalOffsets = [];
  32061. }
  32062. DecimationVertex.prototype.updatePosition = function (newPosition) {
  32063. this.position.copyFrom(newPosition);
  32064. };
  32065. return DecimationVertex;
  32066. })();
  32067. BABYLON.DecimationVertex = DecimationVertex;
  32068. var QuadraticMatrix = (function () {
  32069. function QuadraticMatrix(data) {
  32070. this.data = new Array(10);
  32071. for (var i = 0; i < 10; ++i) {
  32072. if (data && data[i]) {
  32073. this.data[i] = data[i];
  32074. }
  32075. else {
  32076. this.data[i] = 0;
  32077. }
  32078. }
  32079. }
  32080. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  32081. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  32082. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  32083. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  32084. return det;
  32085. };
  32086. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  32087. for (var i = 0; i < 10; ++i) {
  32088. this.data[i] += matrix.data[i];
  32089. }
  32090. };
  32091. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  32092. for (var i = 0; i < 10; ++i) {
  32093. this.data[i] += data[i];
  32094. }
  32095. };
  32096. QuadraticMatrix.prototype.add = function (matrix) {
  32097. var m = new QuadraticMatrix();
  32098. for (var i = 0; i < 10; ++i) {
  32099. m.data[i] = this.data[i] + matrix.data[i];
  32100. }
  32101. return m;
  32102. };
  32103. QuadraticMatrix.FromData = function (a, b, c, d) {
  32104. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  32105. };
  32106. //returning an array to avoid garbage collection
  32107. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  32108. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  32109. };
  32110. return QuadraticMatrix;
  32111. })();
  32112. BABYLON.QuadraticMatrix = QuadraticMatrix;
  32113. var Reference = (function () {
  32114. function Reference(vertexId, triangleId) {
  32115. this.vertexId = vertexId;
  32116. this.triangleId = triangleId;
  32117. }
  32118. return Reference;
  32119. })();
  32120. BABYLON.Reference = Reference;
  32121. /**
  32122. * An implementation of the Quadratic Error simplification algorithm.
  32123. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  32124. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  32125. * @author RaananW
  32126. */
  32127. var QuadraticErrorSimplification = (function () {
  32128. function QuadraticErrorSimplification(_mesh) {
  32129. this._mesh = _mesh;
  32130. this.initialized = false;
  32131. this.syncIterations = 5000;
  32132. this.aggressiveness = 7;
  32133. this.decimationIterations = 100;
  32134. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  32135. }
  32136. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  32137. var _this = this;
  32138. this.initDecimatedMesh();
  32139. //iterating through the submeshes array, one after the other.
  32140. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  32141. _this.initWithMesh(loop.index, function () {
  32142. _this.runDecimation(settings, loop.index, function () {
  32143. loop.executeNext();
  32144. });
  32145. }, settings.optimizeMesh);
  32146. }, function () {
  32147. setTimeout(function () {
  32148. successCallback(_this._reconstructedMesh);
  32149. }, 0);
  32150. });
  32151. };
  32152. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  32153. var _this = this;
  32154. var gCount = 0;
  32155. triangle.vertices.forEach(function (vertex) {
  32156. var count = 0;
  32157. var vPos = vertex.position;
  32158. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  32159. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  32160. ++count;
  32161. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  32162. ++count;
  32163. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  32164. ++count;
  32165. if (count > 1) {
  32166. ++gCount;
  32167. }
  32168. ;
  32169. });
  32170. if (gCount > 1) {
  32171. console.log(triangle, gCount);
  32172. }
  32173. return gCount > 1;
  32174. };
  32175. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  32176. var _this = this;
  32177. var targetCount = ~~(this.triangles.length * settings.quality);
  32178. var deletedTriangles = 0;
  32179. var triangleCount = this.triangles.length;
  32180. var iterationFunction = function (iteration, callback) {
  32181. setTimeout(function () {
  32182. if (iteration % 5 === 0) {
  32183. _this.updateMesh(iteration === 0);
  32184. }
  32185. for (var i = 0; i < _this.triangles.length; ++i) {
  32186. _this.triangles[i].isDirty = false;
  32187. }
  32188. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  32189. var trianglesIterator = function (i) {
  32190. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  32191. var t = _this.triangles[tIdx];
  32192. if (!t)
  32193. return;
  32194. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  32195. return;
  32196. }
  32197. for (var j = 0; j < 3; ++j) {
  32198. if (t.error[j] < threshold) {
  32199. var deleted0 = [];
  32200. var deleted1 = [];
  32201. var v0 = t.vertices[j];
  32202. var v1 = t.vertices[(j + 1) % 3];
  32203. if (v0.isBorder !== v1.isBorder)
  32204. continue;
  32205. var p = BABYLON.Vector3.Zero();
  32206. var n = BABYLON.Vector3.Zero();
  32207. var uv = BABYLON.Vector2.Zero();
  32208. var color = new BABYLON.Color4(0, 0, 0, 1);
  32209. _this.calculateError(v0, v1, p, n, uv, color);
  32210. var delTr = [];
  32211. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  32212. continue;
  32213. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  32214. continue;
  32215. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  32216. continue;
  32217. var uniqueArray = [];
  32218. delTr.forEach(function (deletedT) {
  32219. if (uniqueArray.indexOf(deletedT) === -1) {
  32220. deletedT.deletePending = true;
  32221. uniqueArray.push(deletedT);
  32222. }
  32223. });
  32224. if (uniqueArray.length % 2 != 0) {
  32225. continue;
  32226. }
  32227. v0.q = v1.q.add(v0.q);
  32228. v0.updatePosition(p);
  32229. var tStart = _this.references.length;
  32230. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  32231. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  32232. var tCount = _this.references.length - tStart;
  32233. if (tCount <= v0.triangleCount) {
  32234. if (tCount) {
  32235. for (var c = 0; c < tCount; c++) {
  32236. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  32237. }
  32238. }
  32239. }
  32240. else {
  32241. v0.triangleStart = tStart;
  32242. }
  32243. v0.triangleCount = tCount;
  32244. break;
  32245. }
  32246. }
  32247. };
  32248. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  32249. }, 0);
  32250. };
  32251. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  32252. if (triangleCount - deletedTriangles <= targetCount)
  32253. loop.breakLoop();
  32254. else {
  32255. iterationFunction(loop.index, function () {
  32256. loop.executeNext();
  32257. });
  32258. }
  32259. }, function () {
  32260. setTimeout(function () {
  32261. //reconstruct this part of the mesh
  32262. _this.reconstructMesh(submeshIndex);
  32263. successCallback();
  32264. }, 0);
  32265. });
  32266. };
  32267. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  32268. var _this = this;
  32269. this.vertices = [];
  32270. this.triangles = [];
  32271. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32272. var indices = this._mesh.getIndices();
  32273. var submesh = this._mesh.subMeshes[submeshIndex];
  32274. var findInVertices = function (positionToSearch) {
  32275. if (optimizeMesh) {
  32276. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  32277. if (_this.vertices[ii].position.equals(positionToSearch)) {
  32278. return _this.vertices[ii];
  32279. }
  32280. }
  32281. }
  32282. return null;
  32283. };
  32284. var vertexReferences = [];
  32285. var vertexInit = function (i) {
  32286. var offset = i + submesh.verticesStart;
  32287. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  32288. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  32289. vertex.originalOffsets.push(offset);
  32290. if (vertex.id == _this.vertices.length) {
  32291. _this.vertices.push(vertex);
  32292. }
  32293. vertexReferences.push(vertex.id);
  32294. };
  32295. //var totalVertices = mesh.getTotalVertices();
  32296. var totalVertices = submesh.verticesCount;
  32297. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  32298. var indicesInit = function (i) {
  32299. var offset = (submesh.indexStart / 3) + i;
  32300. var pos = (offset * 3);
  32301. var i0 = indices[pos + 0];
  32302. var i1 = indices[pos + 1];
  32303. var i2 = indices[pos + 2];
  32304. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  32305. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  32306. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  32307. var triangle = new DecimationTriangle([v0, v1, v2]);
  32308. triangle.originalOffset = pos;
  32309. _this.triangles.push(triangle);
  32310. };
  32311. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  32312. _this.init(callback);
  32313. });
  32314. });
  32315. };
  32316. QuadraticErrorSimplification.prototype.init = function (callback) {
  32317. var _this = this;
  32318. var triangleInit1 = function (i) {
  32319. var t = _this.triangles[i];
  32320. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  32321. for (var j = 0; j < 3; j++) {
  32322. 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))));
  32323. }
  32324. };
  32325. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  32326. var triangleInit2 = function (i) {
  32327. var t = _this.triangles[i];
  32328. for (var j = 0; j < 3; ++j) {
  32329. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  32330. }
  32331. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32332. };
  32333. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  32334. _this.initialized = true;
  32335. callback();
  32336. });
  32337. });
  32338. };
  32339. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  32340. var newTriangles = [];
  32341. var i;
  32342. for (i = 0; i < this.vertices.length; ++i) {
  32343. this.vertices[i].triangleCount = 0;
  32344. }
  32345. var t;
  32346. var j;
  32347. for (i = 0; i < this.triangles.length; ++i) {
  32348. if (!this.triangles[i].deleted) {
  32349. t = this.triangles[i];
  32350. for (j = 0; j < 3; ++j) {
  32351. t.vertices[j].triangleCount = 1;
  32352. }
  32353. newTriangles.push(t);
  32354. }
  32355. }
  32356. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  32357. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  32358. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  32359. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  32360. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32361. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32362. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  32363. var vertexCount = 0;
  32364. for (i = 0; i < this.vertices.length; ++i) {
  32365. var vertex = this.vertices[i];
  32366. vertex.id = vertexCount;
  32367. if (vertex.triangleCount) {
  32368. vertex.originalOffsets.forEach(function (originalOffset) {
  32369. newPositionData.push(vertex.position.x);
  32370. newPositionData.push(vertex.position.y);
  32371. newPositionData.push(vertex.position.z);
  32372. newNormalData.push(normalData[originalOffset * 3]);
  32373. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  32374. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  32375. if (uvs && uvs.length) {
  32376. newUVsData.push(uvs[(originalOffset * 2)]);
  32377. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  32378. }
  32379. else if (colorsData && colorsData.length) {
  32380. newColorsData.push(colorsData[(originalOffset * 4)]);
  32381. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  32382. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  32383. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  32384. }
  32385. ++vertexCount;
  32386. });
  32387. }
  32388. }
  32389. var startingIndex = this._reconstructedMesh.getTotalIndices();
  32390. var startingVertex = this._reconstructedMesh.getTotalVertices();
  32391. var submeshesArray = this._reconstructedMesh.subMeshes;
  32392. this._reconstructedMesh.subMeshes = [];
  32393. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  32394. var originalIndices = this._mesh.getIndices();
  32395. for (i = 0; i < newTriangles.length; ++i) {
  32396. var t = newTriangles[i];
  32397. //now get the new referencing point for each vertex
  32398. [0, 1, 2].forEach(function (idx) {
  32399. var id = originalIndices[t.originalOffset + idx];
  32400. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  32401. if (offset < 0)
  32402. offset = 0;
  32403. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  32404. });
  32405. }
  32406. //overwriting the old vertex buffers and indices.
  32407. this._reconstructedMesh.setIndices(newIndicesArray);
  32408. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  32409. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  32410. if (newUVsData.length > 0)
  32411. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  32412. if (newColorsData.length > 0)
  32413. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  32414. //create submesh
  32415. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  32416. if (submeshIndex > 0) {
  32417. this._reconstructedMesh.subMeshes = [];
  32418. submeshesArray.forEach(function (submesh) {
  32419. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  32420. });
  32421. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  32422. }
  32423. };
  32424. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  32425. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  32426. this._reconstructedMesh.material = this._mesh.material;
  32427. this._reconstructedMesh.parent = this._mesh.parent;
  32428. this._reconstructedMesh.isVisible = false;
  32429. };
  32430. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  32431. for (var i = 0; i < vertex1.triangleCount; ++i) {
  32432. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  32433. if (t.deleted)
  32434. continue;
  32435. var s = this.references[vertex1.triangleStart + i].vertexId;
  32436. var v1 = t.vertices[(s + 1) % 3];
  32437. var v2 = t.vertices[(s + 2) % 3];
  32438. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  32439. deletedArray[i] = true;
  32440. delTr.push(t);
  32441. continue;
  32442. }
  32443. var d1 = v1.position.subtract(point);
  32444. d1 = d1.normalize();
  32445. var d2 = v2.position.subtract(point);
  32446. d2 = d2.normalize();
  32447. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  32448. return true;
  32449. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  32450. deletedArray[i] = false;
  32451. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  32452. return true;
  32453. }
  32454. return false;
  32455. };
  32456. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  32457. var newDeleted = deletedTriangles;
  32458. for (var i = 0; i < vertex.triangleCount; ++i) {
  32459. var ref = this.references[vertex.triangleStart + i];
  32460. var t = this.triangles[ref.triangleId];
  32461. if (t.deleted)
  32462. continue;
  32463. if (deletedArray[i] && t.deletePending) {
  32464. t.deleted = true;
  32465. newDeleted++;
  32466. continue;
  32467. }
  32468. t.vertices[ref.vertexId] = origVertex;
  32469. t.isDirty = true;
  32470. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  32471. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  32472. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  32473. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  32474. this.references.push(ref);
  32475. }
  32476. return newDeleted;
  32477. };
  32478. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  32479. for (var i = 0; i < this.vertices.length; ++i) {
  32480. var vCount = [];
  32481. var vId = [];
  32482. var v = this.vertices[i];
  32483. var j;
  32484. for (j = 0; j < v.triangleCount; ++j) {
  32485. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32486. for (var ii = 0; ii < 3; ii++) {
  32487. var ofs = 0;
  32488. var vv = triangle.vertices[ii];
  32489. while (ofs < vCount.length) {
  32490. if (vId[ofs] === vv.id)
  32491. break;
  32492. ++ofs;
  32493. }
  32494. if (ofs === vCount.length) {
  32495. vCount.push(1);
  32496. vId.push(vv.id);
  32497. }
  32498. else {
  32499. vCount[ofs]++;
  32500. }
  32501. }
  32502. }
  32503. for (j = 0; j < vCount.length; ++j) {
  32504. if (vCount[j] === 1) {
  32505. this.vertices[vId[j]].isBorder = true;
  32506. }
  32507. else {
  32508. this.vertices[vId[j]].isBorder = false;
  32509. }
  32510. }
  32511. }
  32512. };
  32513. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32514. if (identifyBorders === void 0) { identifyBorders = false; }
  32515. var i;
  32516. if (!identifyBorders) {
  32517. var newTrianglesVector = [];
  32518. for (i = 0; i < this.triangles.length; ++i) {
  32519. if (!this.triangles[i].deleted) {
  32520. newTrianglesVector.push(this.triangles[i]);
  32521. }
  32522. }
  32523. this.triangles = newTrianglesVector;
  32524. }
  32525. for (i = 0; i < this.vertices.length; ++i) {
  32526. this.vertices[i].triangleCount = 0;
  32527. this.vertices[i].triangleStart = 0;
  32528. }
  32529. var t;
  32530. var j;
  32531. var v;
  32532. for (i = 0; i < this.triangles.length; ++i) {
  32533. t = this.triangles[i];
  32534. for (j = 0; j < 3; ++j) {
  32535. v = t.vertices[j];
  32536. v.triangleCount++;
  32537. }
  32538. }
  32539. var tStart = 0;
  32540. for (i = 0; i < this.vertices.length; ++i) {
  32541. this.vertices[i].triangleStart = tStart;
  32542. tStart += this.vertices[i].triangleCount;
  32543. this.vertices[i].triangleCount = 0;
  32544. }
  32545. var newReferences = new Array(this.triangles.length * 3);
  32546. for (i = 0; i < this.triangles.length; ++i) {
  32547. t = this.triangles[i];
  32548. for (j = 0; j < 3; ++j) {
  32549. v = t.vertices[j];
  32550. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32551. v.triangleCount++;
  32552. }
  32553. }
  32554. this.references = newReferences;
  32555. if (identifyBorders) {
  32556. this.identifyBorder();
  32557. }
  32558. };
  32559. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32560. var x = point.x;
  32561. var y = point.y;
  32562. var z = point.z;
  32563. 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
  32564. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32565. };
  32566. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32567. var q = vertex1.q.add(vertex2.q);
  32568. var border = vertex1.isBorder && vertex2.isBorder;
  32569. var error = 0;
  32570. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32571. if (qDet !== 0 && !border) {
  32572. if (!pointResult) {
  32573. pointResult = BABYLON.Vector3.Zero();
  32574. }
  32575. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32576. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32577. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32578. error = this.vertexError(q, pointResult);
  32579. }
  32580. else {
  32581. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32582. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32583. var error1 = this.vertexError(q, vertex1.position);
  32584. var error2 = this.vertexError(q, vertex2.position);
  32585. var error3 = this.vertexError(q, p3);
  32586. error = Math.min(error1, error2, error3);
  32587. if (error === error1) {
  32588. if (pointResult) {
  32589. pointResult.copyFrom(vertex1.position);
  32590. }
  32591. }
  32592. else if (error === error2) {
  32593. if (pointResult) {
  32594. pointResult.copyFrom(vertex2.position);
  32595. }
  32596. }
  32597. else {
  32598. if (pointResult) {
  32599. pointResult.copyFrom(p3);
  32600. }
  32601. }
  32602. }
  32603. return error;
  32604. };
  32605. return QuadraticErrorSimplification;
  32606. })();
  32607. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32608. })(BABYLON || (BABYLON = {}));
  32609. var BABYLON;
  32610. (function (BABYLON) {
  32611. var Analyser = (function () {
  32612. function Analyser(scene) {
  32613. this.SMOOTHING = 0.75;
  32614. this.FFT_SIZE = 512;
  32615. this.BARGRAPHAMPLITUDE = 256;
  32616. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32617. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32618. this._scene = scene;
  32619. this._audioEngine = BABYLON.Engine.audioEngine;
  32620. if (this._audioEngine.canUseWebAudio) {
  32621. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32622. this._webAudioAnalyser.minDecibels = -140;
  32623. this._webAudioAnalyser.maxDecibels = 0;
  32624. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32625. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32626. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32627. }
  32628. }
  32629. Analyser.prototype.getFrequencyBinCount = function () {
  32630. if (this._audioEngine.canUseWebAudio) {
  32631. return this._webAudioAnalyser.frequencyBinCount;
  32632. }
  32633. else {
  32634. return 0;
  32635. }
  32636. };
  32637. Analyser.prototype.getByteFrequencyData = function () {
  32638. if (this._audioEngine.canUseWebAudio) {
  32639. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32640. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32641. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32642. }
  32643. return this._byteFreqs;
  32644. };
  32645. Analyser.prototype.getByteTimeDomainData = function () {
  32646. if (this._audioEngine.canUseWebAudio) {
  32647. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32648. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32649. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32650. }
  32651. return this._byteTime;
  32652. };
  32653. Analyser.prototype.getFloatFrequencyData = function () {
  32654. if (this._audioEngine.canUseWebAudio) {
  32655. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32656. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32657. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32658. }
  32659. return this._floatFreqs;
  32660. };
  32661. Analyser.prototype.drawDebugCanvas = function () {
  32662. var _this = this;
  32663. if (this._audioEngine.canUseWebAudio) {
  32664. if (!this._debugCanvas) {
  32665. this._debugCanvas = document.createElement("canvas");
  32666. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32667. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32668. this._debugCanvas.style.position = "absolute";
  32669. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32670. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32671. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32672. document.body.appendChild(this._debugCanvas);
  32673. this._registerFunc = function () {
  32674. _this.drawDebugCanvas();
  32675. };
  32676. this._scene.registerBeforeRender(this._registerFunc);
  32677. }
  32678. if (this._registerFunc) {
  32679. var workingArray = this.getByteFrequencyData();
  32680. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32681. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32682. // Draw the frequency domain chart.
  32683. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32684. var value = workingArray[i];
  32685. var percent = value / this.BARGRAPHAMPLITUDE;
  32686. var height = this.DEBUGCANVASSIZE.height * percent;
  32687. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32688. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32689. var hue = i / this.getFrequencyBinCount() * 360;
  32690. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32691. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32692. }
  32693. }
  32694. }
  32695. };
  32696. Analyser.prototype.stopDebugCanvas = function () {
  32697. if (this._debugCanvas) {
  32698. this._scene.unregisterBeforeRender(this._registerFunc);
  32699. this._registerFunc = null;
  32700. document.body.removeChild(this._debugCanvas);
  32701. this._debugCanvas = null;
  32702. this._debugCanvasContext = null;
  32703. }
  32704. };
  32705. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32706. if (this._audioEngine.canUseWebAudio) {
  32707. inputAudioNode.connect(this._webAudioAnalyser);
  32708. this._webAudioAnalyser.connect(outputAudioNode);
  32709. }
  32710. };
  32711. Analyser.prototype.dispose = function () {
  32712. if (this._audioEngine.canUseWebAudio) {
  32713. this._webAudioAnalyser.disconnect();
  32714. }
  32715. };
  32716. return Analyser;
  32717. })();
  32718. BABYLON.Analyser = Analyser;
  32719. })(BABYLON || (BABYLON = {}));
  32720. var BABYLON;
  32721. (function (BABYLON) {
  32722. var DepthRenderer = (function () {
  32723. function DepthRenderer(scene, type) {
  32724. var _this = this;
  32725. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32726. this._viewMatrix = BABYLON.Matrix.Zero();
  32727. this._projectionMatrix = BABYLON.Matrix.Zero();
  32728. this._transformMatrix = BABYLON.Matrix.Zero();
  32729. this._worldViewProjection = BABYLON.Matrix.Zero();
  32730. this._scene = scene;
  32731. var engine = scene.getEngine();
  32732. // Render target
  32733. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32734. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32735. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32736. this._depthMap.refreshRate = 1;
  32737. this._depthMap.renderParticles = false;
  32738. this._depthMap.renderList = null;
  32739. // set default depth value to 1.0 (far away)
  32740. this._depthMap.onClear = function (engine) {
  32741. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32742. };
  32743. // Custom render function
  32744. var renderSubMesh = function (subMesh) {
  32745. var mesh = subMesh.getRenderingMesh();
  32746. var scene = _this._scene;
  32747. var engine = scene.getEngine();
  32748. // Culling
  32749. engine.setState(subMesh.getMaterial().backFaceCulling);
  32750. // Managing instances
  32751. var batch = mesh._getInstancesRenderList(subMesh._id);
  32752. if (batch.mustReturn) {
  32753. return;
  32754. }
  32755. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32756. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32757. engine.enableEffect(_this._effect);
  32758. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32759. var material = subMesh.getMaterial();
  32760. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32761. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32762. // Alpha test
  32763. if (material && material.needAlphaTesting()) {
  32764. var alphaTexture = material.getAlphaTestTexture();
  32765. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32766. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32767. }
  32768. // Bones
  32769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32770. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32771. }
  32772. // Draw
  32773. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32774. }
  32775. };
  32776. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32777. var index;
  32778. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32779. renderSubMesh(opaqueSubMeshes.data[index]);
  32780. }
  32781. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32782. renderSubMesh(alphaTestSubMeshes.data[index]);
  32783. }
  32784. };
  32785. }
  32786. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32787. var defines = [];
  32788. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32789. var mesh = subMesh.getMesh();
  32790. var scene = mesh.getScene();
  32791. var material = subMesh.getMaterial();
  32792. // Alpha test
  32793. if (material && material.needAlphaTesting()) {
  32794. defines.push("#define ALPHATEST");
  32795. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32796. attribs.push(BABYLON.VertexBuffer.UVKind);
  32797. defines.push("#define UV1");
  32798. }
  32799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32800. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32801. defines.push("#define UV2");
  32802. }
  32803. }
  32804. // Bones
  32805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32806. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32807. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32808. defines.push("#define BONES");
  32809. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32810. }
  32811. // Instances
  32812. if (useInstances) {
  32813. defines.push("#define INSTANCES");
  32814. attribs.push("world0");
  32815. attribs.push("world1");
  32816. attribs.push("world2");
  32817. attribs.push("world3");
  32818. }
  32819. // Get correct effect
  32820. var join = defines.join("\n");
  32821. if (this._cachedDefines !== join) {
  32822. this._cachedDefines = join;
  32823. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32824. }
  32825. return this._effect.isReady();
  32826. };
  32827. DepthRenderer.prototype.getDepthMap = function () {
  32828. return this._depthMap;
  32829. };
  32830. // Methods
  32831. DepthRenderer.prototype.dispose = function () {
  32832. this._depthMap.dispose();
  32833. };
  32834. return DepthRenderer;
  32835. })();
  32836. BABYLON.DepthRenderer = DepthRenderer;
  32837. })(BABYLON || (BABYLON = {}));
  32838. var BABYLON;
  32839. (function (BABYLON) {
  32840. var SSAORenderingPipeline = (function (_super) {
  32841. __extends(SSAORenderingPipeline, _super);
  32842. /**
  32843. * @constructor
  32844. * @param {string} name - The rendering pipeline name
  32845. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32846. * @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 }
  32847. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32848. */
  32849. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32850. var _this = this;
  32851. _super.call(this, scene.getEngine(), name);
  32852. // Members
  32853. /**
  32854. * The PassPostProcess id in the pipeline that contains the original scene color
  32855. * @type {string}
  32856. */
  32857. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32858. /**
  32859. * The SSAO PostProcess id in the pipeline
  32860. * @type {string}
  32861. */
  32862. this.SSAORenderEffect = "SSAORenderEffect";
  32863. /**
  32864. * The horizontal blur PostProcess id in the pipeline
  32865. * @type {string}
  32866. */
  32867. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32868. /**
  32869. * The vertical blur PostProcess id in the pipeline
  32870. * @type {string}
  32871. */
  32872. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32873. /**
  32874. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32875. * @type {string}
  32876. */
  32877. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32878. /**
  32879. * The output strength of the SSAO post-process. Default value is 1.0.
  32880. * @type {number}
  32881. */
  32882. this.totalStrength = 1.0;
  32883. /**
  32884. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32885. * @type {number}
  32886. */
  32887. this.radius = 0.0002;
  32888. /**
  32889. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32890. * Must not be equal to fallOff and superior to fallOff.
  32891. * Default value is 0.0075
  32892. * @type {number}
  32893. */
  32894. this.area = 0.0075;
  32895. /**
  32896. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32897. * Must not be equal to area and inferior to area.
  32898. * Default value is 0.0002
  32899. * @type {number}
  32900. */
  32901. this.fallOff = 0.0002;
  32902. this._firstUpdate = true;
  32903. this._scene = scene;
  32904. // Set up assets
  32905. this._createRandomTexture();
  32906. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32907. var ssaoRatio = ratio.ssaoRatio || ratio;
  32908. var combineRatio = ratio.combineRatio || ratio;
  32909. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32910. this._createSSAOPostProcess(ssaoRatio);
  32911. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32912. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32913. this._createSSAOCombinePostProcess(combineRatio);
  32914. // Set up pipeline
  32915. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32917. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32918. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32920. // Finish
  32921. scene.postProcessRenderPipelineManager.addPipeline(this);
  32922. if (cameras)
  32923. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32924. }
  32925. // Public Methods
  32926. /**
  32927. * Returns the horizontal blur PostProcess
  32928. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32929. */
  32930. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32931. return this._blurHPostProcess;
  32932. };
  32933. /**
  32934. * Returns the vertical blur PostProcess
  32935. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32936. */
  32937. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32938. return this._blurVPostProcess;
  32939. };
  32940. /**
  32941. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32942. */
  32943. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32944. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32945. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32946. this._originalColorPostProcess = undefined;
  32947. this._ssaoPostProcess = undefined;
  32948. this._blurHPostProcess = undefined;
  32949. this._blurVPostProcess = undefined;
  32950. this._ssaoCombinePostProcess = undefined;
  32951. this._randomTexture.dispose();
  32952. if (disableDepthRender)
  32953. this._scene.disableDepthRenderer();
  32954. };
  32955. // Private Methods
  32956. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32957. var _this = this;
  32958. var sampleSphere = [
  32959. 0.5381, 0.1856, -0.4319,
  32960. 0.1379, 0.2486, 0.4430,
  32961. 0.3371, 0.5679, -0.0057,
  32962. -0.6999, -0.0451, -0.0019,
  32963. 0.0689, -0.1598, -0.8547,
  32964. 0.0560, 0.0069, -0.1843,
  32965. -0.0146, 0.1402, 0.0762,
  32966. 0.0100, -0.1924, -0.0344,
  32967. -0.3577, -0.5301, -0.4358,
  32968. -0.3169, 0.1063, 0.0158,
  32969. 0.0103, -0.5869, 0.0046,
  32970. -0.0897, -0.4940, 0.3287,
  32971. 0.7119, -0.0154, -0.0918,
  32972. -0.0533, 0.0596, -0.5411,
  32973. 0.0352, -0.0631, 0.5460,
  32974. -0.4776, 0.2847, -0.0271
  32975. ];
  32976. var samplesFactor = 1.0 / 16.0;
  32977. 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);
  32978. this._ssaoPostProcess.onApply = function (effect) {
  32979. if (_this._firstUpdate) {
  32980. effect.setArray3("sampleSphere", sampleSphere);
  32981. effect.setFloat("samplesFactor", samplesFactor);
  32982. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32983. _this._firstUpdate = false;
  32984. }
  32985. effect.setFloat("totalStrength", _this.totalStrength);
  32986. effect.setFloat("radius", _this.radius);
  32987. effect.setFloat("area", _this.area);
  32988. effect.setFloat("fallOff", _this.fallOff);
  32989. effect.setTexture("textureSampler", _this._depthTexture);
  32990. effect.setTexture("randomSampler", _this._randomTexture);
  32991. };
  32992. };
  32993. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32994. var _this = this;
  32995. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32996. this._ssaoCombinePostProcess.onApply = function (effect) {
  32997. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32998. };
  32999. };
  33000. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  33001. var size = 512;
  33002. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33003. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33004. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33005. var context = this._randomTexture.getContext();
  33006. var rand = function (min, max) {
  33007. return Math.random() * (max - min) + min;
  33008. };
  33009. for (var x = 0; x < size; x++) {
  33010. for (var y = 0; y < size; y++) {
  33011. var randVector = BABYLON.Vector3.Zero();
  33012. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33013. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33014. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33015. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33016. context.fillRect(x, y, 1, 1);
  33017. }
  33018. }
  33019. this._randomTexture.update(false);
  33020. };
  33021. return SSAORenderingPipeline;
  33022. })(BABYLON.PostProcessRenderPipeline);
  33023. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33024. })(BABYLON || (BABYLON = {}));
  33025. var BABYLON;
  33026. (function (BABYLON) {
  33027. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33028. var VolumetricLightScatteringPostProcess = (function (_super) {
  33029. __extends(VolumetricLightScatteringPostProcess, _super);
  33030. /**
  33031. * @constructor
  33032. * @param {string} name - The post-process name
  33033. * @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)
  33034. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33035. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33036. * @param {number} samples - The post-process quality, default 100
  33037. * @param {number} samplingMode - The post-process filtering mode
  33038. * @param {BABYLON.Engine} engine - The babylon engine
  33039. * @param {boolean} reusable - If the post-process is reusable
  33040. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33041. */
  33042. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33043. var _this = this;
  33044. if (samples === void 0) { samples = 100; }
  33045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33046. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33047. this._screenCoordinates = BABYLON.Vector2.Zero();
  33048. /**
  33049. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33050. * @type {boolean}
  33051. */
  33052. this.useCustomMeshPosition = false;
  33053. /**
  33054. * If the post-process should inverse the light scattering direction
  33055. * @type {boolean}
  33056. */
  33057. this.invert = true;
  33058. /**
  33059. * Set to true to use the diffuseColor instead of the diffuseTexture
  33060. * @type {boolean}
  33061. */
  33062. this.useDiffuseColor = false;
  33063. /**
  33064. * Array containing the excluded meshes not rendered in the internal pass
  33065. */
  33066. this.excludedMeshes = new Array();
  33067. /**
  33068. * Controls the overall intensity of the post-process
  33069. * @type {number}
  33070. */
  33071. this.exposure = 0.3;
  33072. /**
  33073. * Dissipates each sample's contribution in range [0, 1]
  33074. * @type {number}
  33075. */
  33076. this.decay = 0.96815;
  33077. /**
  33078. * Controls the overall intensity of each sample
  33079. * @type {number}
  33080. */
  33081. this.weight = 0.58767;
  33082. /**
  33083. * Controls the density of each sample
  33084. * @type {number}
  33085. */
  33086. this.density = 0.926;
  33087. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33088. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33089. // Configure mesh
  33090. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33091. // Configure
  33092. this._createPass(scene, ratio.passRatio || ratio);
  33093. this.onApply = function (effect) {
  33094. _this._updateMeshScreenCoordinates(scene);
  33095. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33096. effect.setFloat("exposure", _this.exposure);
  33097. effect.setFloat("decay", _this.decay);
  33098. effect.setFloat("weight", _this.weight);
  33099. effect.setFloat("density", _this.density);
  33100. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33101. };
  33102. }
  33103. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33104. var mesh = subMesh.getMesh();
  33105. var defines = [];
  33106. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33107. var material = subMesh.getMaterial();
  33108. var needUV = false;
  33109. // Render this.mesh as default
  33110. if (mesh === this.mesh) {
  33111. if (this.useDiffuseColor) {
  33112. defines.push("#define DIFFUSE_COLOR_RENDER");
  33113. }
  33114. else if (material) {
  33115. if (material.diffuseTexture !== undefined) {
  33116. defines.push("#define BASIC_RENDER");
  33117. }
  33118. else {
  33119. defines.push("#define DIFFUSE_COLOR_RENDER");
  33120. }
  33121. }
  33122. defines.push("#define NEED_UV");
  33123. needUV = true;
  33124. }
  33125. // Alpha test
  33126. if (material) {
  33127. if (material.needAlphaTesting()) {
  33128. defines.push("#define ALPHATEST");
  33129. }
  33130. if (material.opacityTexture !== undefined) {
  33131. defines.push("#define OPACITY");
  33132. if (material.opacityTexture.getAlphaFromRGB) {
  33133. defines.push("#define OPACITYRGB");
  33134. }
  33135. if (!needUV) {
  33136. defines.push("#define NEED_UV");
  33137. }
  33138. }
  33139. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33140. attribs.push(BABYLON.VertexBuffer.UVKind);
  33141. defines.push("#define UV1");
  33142. }
  33143. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33145. defines.push("#define UV2");
  33146. }
  33147. }
  33148. // Bones
  33149. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33152. defines.push("#define BONES");
  33153. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33154. }
  33155. // Instances
  33156. if (useInstances) {
  33157. defines.push("#define INSTANCES");
  33158. attribs.push("world0");
  33159. attribs.push("world1");
  33160. attribs.push("world2");
  33161. attribs.push("world3");
  33162. }
  33163. // Get correct effect
  33164. var join = defines.join("\n");
  33165. if (this._cachedDefines !== join) {
  33166. this._cachedDefines = join;
  33167. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33168. }
  33169. return this._volumetricLightScatteringPass.isReady();
  33170. };
  33171. /**
  33172. * Sets the new light position for light scattering effect
  33173. * @param {BABYLON.Vector3} The new custom light position
  33174. */
  33175. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33176. this._customMeshPosition = position;
  33177. };
  33178. /**
  33179. * Returns the light position for light scattering effect
  33180. * @return {BABYLON.Vector3} The custom light position
  33181. */
  33182. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33183. return this._customMeshPosition;
  33184. };
  33185. /**
  33186. * Disposes the internal assets and detaches the post-process from the camera
  33187. */
  33188. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33189. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33190. if (rttIndex !== -1) {
  33191. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33192. }
  33193. this._volumetricLightScatteringRTT.dispose();
  33194. _super.prototype.dispose.call(this, camera);
  33195. };
  33196. /**
  33197. * Returns the render target texture used by the post-process
  33198. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33199. */
  33200. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33201. return this._volumetricLightScatteringRTT;
  33202. };
  33203. // Private methods
  33204. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33205. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33206. return true;
  33207. }
  33208. return false;
  33209. };
  33210. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33211. var _this = this;
  33212. var engine = scene.getEngine();
  33213. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33214. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33215. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33216. this._volumetricLightScatteringRTT.renderList = null;
  33217. this._volumetricLightScatteringRTT.renderParticles = false;
  33218. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33219. // Custom render function for submeshes
  33220. var renderSubMesh = function (subMesh) {
  33221. var mesh = subMesh.getRenderingMesh();
  33222. if (_this._meshExcluded(mesh)) {
  33223. return;
  33224. }
  33225. var scene = mesh.getScene();
  33226. var engine = scene.getEngine();
  33227. // Culling
  33228. engine.setState(subMesh.getMaterial().backFaceCulling);
  33229. // Managing instances
  33230. var batch = mesh._getInstancesRenderList(subMesh._id);
  33231. if (batch.mustReturn) {
  33232. return;
  33233. }
  33234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33235. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33236. engine.enableEffect(_this._volumetricLightScatteringPass);
  33237. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33238. var material = subMesh.getMaterial();
  33239. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33240. // Alpha test
  33241. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33242. var alphaTexture = material.getAlphaTestTexture();
  33243. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33244. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33245. }
  33246. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33247. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33248. if (alphaTexture) {
  33249. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33250. }
  33251. }
  33252. if (material.opacityTexture !== undefined) {
  33253. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33254. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33255. }
  33256. }
  33257. // Bones
  33258. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33259. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33260. }
  33261. // Draw
  33262. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33263. }
  33264. };
  33265. // Render target texture callbacks
  33266. var savedSceneClearColor;
  33267. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33268. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33269. savedSceneClearColor = scene.clearColor;
  33270. scene.clearColor = sceneClearColor;
  33271. };
  33272. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33273. scene.clearColor = savedSceneClearColor;
  33274. };
  33275. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33276. var engine = scene.getEngine();
  33277. var index;
  33278. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33279. renderSubMesh(opaqueSubMeshes.data[index]);
  33280. }
  33281. engine.setAlphaTesting(true);
  33282. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33283. renderSubMesh(alphaTestSubMeshes.data[index]);
  33284. }
  33285. engine.setAlphaTesting(false);
  33286. if (transparentSubMeshes.length) {
  33287. // Sort sub meshes
  33288. for (index = 0; index < transparentSubMeshes.length; index++) {
  33289. var submesh = transparentSubMeshes.data[index];
  33290. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33291. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33292. }
  33293. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33294. sortedArray.sort(function (a, b) {
  33295. // Alpha index first
  33296. if (a._alphaIndex > b._alphaIndex) {
  33297. return 1;
  33298. }
  33299. if (a._alphaIndex < b._alphaIndex) {
  33300. return -1;
  33301. }
  33302. // Then distance to camera
  33303. if (a._distanceToCamera < b._distanceToCamera) {
  33304. return 1;
  33305. }
  33306. if (a._distanceToCamera > b._distanceToCamera) {
  33307. return -1;
  33308. }
  33309. return 0;
  33310. });
  33311. // Render sub meshes
  33312. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33313. for (index = 0; index < sortedArray.length; index++) {
  33314. renderSubMesh(sortedArray[index]);
  33315. }
  33316. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33317. }
  33318. };
  33319. };
  33320. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  33321. var transform = scene.getTransformMatrix();
  33322. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  33323. this._screenCoordinates.x = pos.x / this._viewPort.width;
  33324. this._screenCoordinates.y = pos.y / this._viewPort.height;
  33325. if (this.invert)
  33326. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  33327. };
  33328. // Static methods
  33329. /**
  33330. * Creates a default mesh for the Volumeric Light Scattering post-process
  33331. * @param {string} The mesh name
  33332. * @param {BABYLON.Scene} The scene where to create the mesh
  33333. * @return {BABYLON.Mesh} the default mesh
  33334. */
  33335. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  33336. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  33337. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  33338. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  33339. return mesh;
  33340. };
  33341. return VolumetricLightScatteringPostProcess;
  33342. })(BABYLON.PostProcess);
  33343. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  33344. })(BABYLON || (BABYLON = {}));
  33345. var BABYLON;
  33346. (function (BABYLON) {
  33347. var LensRenderingPipeline = (function (_super) {
  33348. __extends(LensRenderingPipeline, _super);
  33349. /**
  33350. * @constructor
  33351. *
  33352. * Effect parameters are as follow:
  33353. * {
  33354. * chromatic_aberration: number; // from 0 to x (1 for realism)
  33355. * edge_blur: number; // from 0 to x (1 for realism)
  33356. * distortion: number; // from 0 to x (1 for realism)
  33357. * grain_amount: number; // from 0 to 1
  33358. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  33359. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  33360. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  33361. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  33362. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  33363. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  33364. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  33365. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  33366. * }
  33367. * Note: if an effect parameter is unset, effect is disabled
  33368. *
  33369. * @param {string} name - The rendering pipeline name
  33370. * @param {object} parameters - An object containing all parameters (see above)
  33371. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33372. * @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)
  33373. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33374. */
  33375. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  33376. var _this = this;
  33377. if (ratio === void 0) { ratio = 1.0; }
  33378. _super.call(this, scene.getEngine(), name);
  33379. // Lens effects can be of the following:
  33380. // - chromatic aberration (slight shift of RGB colors)
  33381. // - blur on the edge of the lens
  33382. // - lens distortion
  33383. // - depth-of-field blur & highlights enhancing
  33384. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  33385. // - grain effect (noise or custom texture)
  33386. // Two additional texture samplers are needed:
  33387. // - depth map (for depth-of-field)
  33388. // - grain texture
  33389. /**
  33390. * The chromatic aberration PostProcess id in the pipeline
  33391. * @type {string}
  33392. */
  33393. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  33394. /**
  33395. * The highlights enhancing PostProcess id in the pipeline
  33396. * @type {string}
  33397. */
  33398. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  33399. /**
  33400. * The depth-of-field PostProcess id in the pipeline
  33401. * @type {string}
  33402. */
  33403. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  33404. this._scene = scene;
  33405. // Fetch texture samplers
  33406. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33407. if (parameters.grain_texture) {
  33408. this._grainTexture = parameters.grain_texture;
  33409. }
  33410. else {
  33411. this._createGrainTexture();
  33412. }
  33413. // save parameters
  33414. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  33415. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  33416. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  33417. this._distortion = parameters.distortion ? parameters.distortion : 0;
  33418. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  33419. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  33420. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  33421. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  33422. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  33423. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  33424. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  33425. // Create effects
  33426. this._createChromaticAberrationPostProcess(ratio);
  33427. this._createHighlightsPostProcess(ratio);
  33428. this._createDepthOfFieldPostProcess(ratio / 4);
  33429. // Set up pipeline
  33430. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  33431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  33432. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  33433. if (this._highlightsGain == -1) {
  33434. this._disableEffect(this.HighlightsEnhancingEffect, null);
  33435. }
  33436. // Finish
  33437. scene.postProcessRenderPipelineManager.addPipeline(this);
  33438. if (cameras) {
  33439. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33440. }
  33441. }
  33442. // public methods (self explanatory)
  33443. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  33444. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  33445. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  33446. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  33447. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  33448. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  33449. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  33450. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  33451. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  33452. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  33453. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  33454. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  33455. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  33456. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  33457. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  33458. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  33459. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  33460. this._highlightsGain = amount;
  33461. };
  33462. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  33463. if (this._highlightsGain == -1) {
  33464. this._highlightsGain = 1.0;
  33465. }
  33466. this._highlightsThreshold = amount;
  33467. };
  33468. LensRenderingPipeline.prototype.disableHighlights = function () {
  33469. this._highlightsGain = -1;
  33470. };
  33471. /**
  33472. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  33473. */
  33474. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33475. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33476. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33477. this._chromaticAberrationPostProcess = undefined;
  33478. this._highlightsPostProcess = undefined;
  33479. this._depthOfFieldPostProcess = undefined;
  33480. this._grainTexture.dispose();
  33481. if (disableDepthRender)
  33482. this._scene.disableDepthRenderer();
  33483. };
  33484. // colors shifting and distortion
  33485. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  33486. var _this = this;
  33487. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  33488. [], // samplers
  33489. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33490. this._chromaticAberrationPostProcess.onApply = function (effect) {
  33491. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  33492. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33493. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33494. };
  33495. };
  33496. // highlights enhancing
  33497. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  33498. var _this = this;
  33499. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  33500. [], // samplers
  33501. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33502. this._highlightsPostProcess.onApply = function (effect) {
  33503. effect.setFloat('gain', _this._highlightsGain);
  33504. effect.setFloat('threshold', _this._highlightsThreshold);
  33505. effect.setBool('pentagon', _this._dofPentagon);
  33506. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  33507. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33508. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33509. };
  33510. };
  33511. // colors shifting and distortion
  33512. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  33513. var _this = this;
  33514. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  33515. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  33516. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  33517. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33518. this._depthOfFieldPostProcess.onApply = function (effect) {
  33519. effect.setTexture("depthSampler", _this._depthTexture);
  33520. effect.setTexture("grainSampler", _this._grainTexture);
  33521. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  33522. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  33523. effect.setFloat('grain_amount', _this._grainAmount);
  33524. effect.setBool('blur_noise', _this._blurNoise);
  33525. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  33526. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  33527. effect.setFloat('distortion', _this._distortion);
  33528. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  33529. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  33530. effect.setFloat('aperture', _this._dofAperture);
  33531. effect.setFloat('darken', _this._dofDarken);
  33532. effect.setFloat('edge_blur', _this._edgeBlur);
  33533. effect.setBool('highlights', (_this._highlightsGain != -1));
  33534. effect.setFloat('near', _this._scene.activeCamera.minZ);
  33535. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  33536. };
  33537. };
  33538. // creates a black and white random noise texture, 512x512
  33539. LensRenderingPipeline.prototype._createGrainTexture = function () {
  33540. var size = 512;
  33541. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33542. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33543. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33544. var context = this._grainTexture.getContext();
  33545. var rand = function (min, max) {
  33546. return Math.random() * (max - min) + min;
  33547. };
  33548. var value;
  33549. for (var x = 0; x < size; x++) {
  33550. for (var y = 0; y < size; y++) {
  33551. value = Math.floor(rand(0.42, 0.58) * 255);
  33552. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  33553. context.fillRect(x, y, 1, 1);
  33554. }
  33555. }
  33556. this._grainTexture.update(false);
  33557. };
  33558. return LensRenderingPipeline;
  33559. })(BABYLON.PostProcessRenderPipeline);
  33560. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  33561. })(BABYLON || (BABYLON = {}));
  33562. //
  33563. // This post-process allows the modification of rendered colors by using
  33564. // a 'look-up table' (LUT). This effect is also called Color Grading.
  33565. //
  33566. // The object needs to be provided an url to a texture containing the color
  33567. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  33568. // Use an image editing software to tweak the LUT to match your needs.
  33569. //
  33570. // For an example of a color LUT, see here:
  33571. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  33572. // For explanations on color grading, see here:
  33573. // http://udn.epicgames.com/Three/ColorGrading.html
  33574. //
  33575. var BABYLON;
  33576. (function (BABYLON) {
  33577. var ColorCorrectionPostProcess = (function (_super) {
  33578. __extends(ColorCorrectionPostProcess, _super);
  33579. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  33580. var _this = this;
  33581. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  33582. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  33583. this._colorTableTexture.anisotropicFilteringLevel = 1;
  33584. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33585. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33586. this.onApply = function (effect) {
  33587. effect.setTexture("colorTable", _this._colorTableTexture);
  33588. };
  33589. }
  33590. return ColorCorrectionPostProcess;
  33591. })(BABYLON.PostProcess);
  33592. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  33593. })(BABYLON || (BABYLON = {}));
  33594. var BABYLON;
  33595. (function (BABYLON) {
  33596. var AnaglyphFreeCamera = (function (_super) {
  33597. __extends(AnaglyphFreeCamera, _super);
  33598. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  33599. _super.call(this, name, position, scene);
  33600. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33601. }
  33602. return AnaglyphFreeCamera;
  33603. })(BABYLON.FreeCamera);
  33604. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  33605. var AnaglyphArcRotateCamera = (function (_super) {
  33606. __extends(AnaglyphArcRotateCamera, _super);
  33607. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  33608. _super.call(this, name, alpha, beta, radius, target, scene);
  33609. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33610. }
  33611. return AnaglyphArcRotateCamera;
  33612. })(BABYLON.ArcRotateCamera);
  33613. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  33614. var AnaglyphGamepadCamera = (function (_super) {
  33615. __extends(AnaglyphGamepadCamera, _super);
  33616. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  33617. _super.call(this, name, position, scene);
  33618. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  33619. }
  33620. return AnaglyphGamepadCamera;
  33621. })(BABYLON.GamepadCamera);
  33622. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  33623. var StereoscopicFreeCamera = (function (_super) {
  33624. __extends(StereoscopicFreeCamera, _super);
  33625. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33626. _super.call(this, name, position, scene);
  33627. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33628. }
  33629. return StereoscopicFreeCamera;
  33630. })(BABYLON.FreeCamera);
  33631. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  33632. var StereoscopicArcRotateCamera = (function (_super) {
  33633. __extends(StereoscopicArcRotateCamera, _super);
  33634. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  33635. _super.call(this, name, alpha, beta, radius, target, scene);
  33636. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33637. }
  33638. return StereoscopicArcRotateCamera;
  33639. })(BABYLON.ArcRotateCamera);
  33640. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  33641. var StereoscopicGamepadCamera = (function (_super) {
  33642. __extends(StereoscopicGamepadCamera, _super);
  33643. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  33644. _super.call(this, name, position, scene);
  33645. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  33646. }
  33647. return StereoscopicGamepadCamera;
  33648. })(BABYLON.GamepadCamera);
  33649. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  33650. })(BABYLON || (BABYLON = {}));
  33651. var BABYLON;
  33652. (function (BABYLON) {
  33653. var HDRRenderingPipeline = (function (_super) {
  33654. __extends(HDRRenderingPipeline, _super);
  33655. /**
  33656. * @constructor
  33657. * @param {string} name - The rendering pipeline name
  33658. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33659. * @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)
  33660. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  33661. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33662. */
  33663. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  33664. var _this = this;
  33665. if (originalPostProcess === void 0) { originalPostProcess = null; }
  33666. _super.call(this, scene.getEngine(), name);
  33667. /**
  33668. * Public members
  33669. */
  33670. // Gaussian Blur
  33671. /**
  33672. * Gaussian blur coefficient
  33673. * @type {number}
  33674. */
  33675. this.gaussCoeff = 0.3;
  33676. /**
  33677. * Gaussian blur mean
  33678. * @type {number}
  33679. */
  33680. this.gaussMean = 1.0;
  33681. /**
  33682. * Gaussian blur standard deviation
  33683. * @type {number}
  33684. */
  33685. this.gaussStandDev = 0.8;
  33686. // HDR
  33687. /**
  33688. * Exposure, controls the overall intensity of the pipeline
  33689. * @type {number}
  33690. */
  33691. this.exposure = 1.0;
  33692. /**
  33693. * Minimum luminance that the post-process can output. Luminance is >= 0
  33694. * @type {number}
  33695. */
  33696. this.minimumLuminance = 1.0;
  33697. /**
  33698. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33699. * @type {number}
  33700. */
  33701. this.maximumLuminance = 1e20;
  33702. /**
  33703. * Increase rate for luminance: eye adaptation speed to dark
  33704. * @type {number}
  33705. */
  33706. this.luminanceIncreaserate = 0.5;
  33707. /**
  33708. * Decrease rate for luminance: eye adaptation speed to bright
  33709. * @type {number}
  33710. */
  33711. this.luminanceDecreaseRate = 0.5;
  33712. // Bright pass
  33713. /**
  33714. * Minimum luminance needed to compute HDR
  33715. * @type {number}
  33716. */
  33717. this.brightThreshold = 0.8;
  33718. this._needUpdate = true;
  33719. this._scene = scene;
  33720. // Bright pass
  33721. this._createBrightPassPostProcess(scene, ratio);
  33722. // Down sample X4
  33723. this._createDownSampleX4PostProcess(scene, ratio);
  33724. // Create gaussian blur post-processes
  33725. this._createGaussianBlurPostProcess(scene, ratio);
  33726. // Texture adder
  33727. this._createTextureAdderPostProcess(scene, ratio);
  33728. // Luminance generator
  33729. this._createLuminanceGeneratorPostProcess(scene);
  33730. // HDR
  33731. this._createHDRPostProcess(scene, ratio);
  33732. // Pass postprocess
  33733. if (originalPostProcess === null) {
  33734. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33735. }
  33736. else {
  33737. this._originalPostProcess = originalPostProcess;
  33738. }
  33739. // Configure pipeline
  33740. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33741. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33743. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33744. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33746. var addDownSamplerPostProcess = function (id) {
  33747. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33748. };
  33749. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33750. addDownSamplerPostProcess(i);
  33751. }
  33752. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33753. // Finish
  33754. scene.postProcessRenderPipelineManager.addPipeline(this);
  33755. if (cameras !== null) {
  33756. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33757. }
  33758. this.update();
  33759. }
  33760. /**
  33761. * Tells the pipeline to update its post-processes
  33762. */
  33763. HDRRenderingPipeline.prototype.update = function () {
  33764. this._needUpdate = true;
  33765. };
  33766. /**
  33767. * Returns the current calculated luminance
  33768. */
  33769. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33770. return this._hdrCurrentLuminance;
  33771. };
  33772. /**
  33773. * Returns the currently drawn luminance
  33774. */
  33775. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33776. return this._hdrOutputLuminance;
  33777. };
  33778. /**
  33779. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33780. */
  33781. HDRRenderingPipeline.prototype.dispose = function () {
  33782. this._originalPostProcess = undefined;
  33783. this._brightPassPostProcess = undefined;
  33784. this._downSampleX4PostProcess = undefined;
  33785. this._guassianBlurHPostProcess = undefined;
  33786. this._guassianBlurVPostProcess = undefined;
  33787. this._textureAdderPostProcess = undefined;
  33788. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33789. this._downSamplePostProcesses[i] = undefined;
  33790. }
  33791. this._hdrPostProcess = undefined;
  33792. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33793. };
  33794. /**
  33795. * Creates the HDR post-process and computes the luminance adaptation
  33796. */
  33797. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33798. var _this = this;
  33799. var hdrLastLuminance = 0.0;
  33800. this._hdrOutputLuminance = -1.0;
  33801. this._hdrCurrentLuminance = 1.0;
  33802. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33803. this._hdrPostProcess.onApply = function (effect) {
  33804. if (_this._hdrOutputLuminance < 0.0) {
  33805. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33806. }
  33807. else {
  33808. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33809. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33810. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33811. }
  33812. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33813. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33814. }
  33815. else {
  33816. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33817. }
  33818. }
  33819. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33820. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33821. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33822. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33823. effect.setFloat("exposure", _this.exposure);
  33824. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33825. _this._needUpdate = false;
  33826. };
  33827. };
  33828. /**
  33829. * Texture Adder post-process
  33830. */
  33831. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33832. var _this = this;
  33833. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33834. this._textureAdderPostProcess.onApply = function (effect) {
  33835. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33836. };
  33837. };
  33838. /**
  33839. * Down sample X4 post-process
  33840. */
  33841. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33842. var _this = this;
  33843. var downSampleX4Offsets = new Array(32);
  33844. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33845. this._downSampleX4PostProcess.onApply = function (effect) {
  33846. if (_this._needUpdate) {
  33847. var id = 0;
  33848. for (var i = -2; i < 2; i++) {
  33849. for (var j = -2; j < 2; j++) {
  33850. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33851. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33852. id += 2;
  33853. }
  33854. }
  33855. }
  33856. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33857. };
  33858. };
  33859. /**
  33860. * Bright pass post-process
  33861. */
  33862. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33863. var _this = this;
  33864. var brightOffsets = new Array(8);
  33865. var brightPassCallback = function (effect) {
  33866. if (_this._needUpdate) {
  33867. var sU = (1.0 / _this._brightPassPostProcess.width);
  33868. var sV = (1.0 / _this._brightPassPostProcess.height);
  33869. brightOffsets[0] = -0.5 * sU;
  33870. brightOffsets[1] = 0.5 * sV;
  33871. brightOffsets[2] = 0.5 * sU;
  33872. brightOffsets[3] = 0.5 * sV;
  33873. brightOffsets[4] = -0.5 * sU;
  33874. brightOffsets[5] = -0.5 * sV;
  33875. brightOffsets[6] = 0.5 * sU;
  33876. brightOffsets[7] = -0.5 * sV;
  33877. }
  33878. effect.setArray2("dsOffsets", brightOffsets);
  33879. effect.setFloat("brightThreshold", _this.brightThreshold);
  33880. };
  33881. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33882. this._brightPassPostProcess.onApply = brightPassCallback;
  33883. };
  33884. /**
  33885. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33886. */
  33887. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33888. var _this = this;
  33889. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33890. var luminanceOffsets = new Array(8);
  33891. var downSampleOffsets = new Array(18);
  33892. var halfDestPixelSize;
  33893. this._downSamplePostProcesses = new Array(lumSteps);
  33894. // Utils for luminance
  33895. var luminanceUpdateSourceOffsets = function (width, height) {
  33896. var sU = (1.0 / width);
  33897. var sV = (1.0 / height);
  33898. luminanceOffsets[0] = -0.5 * sU;
  33899. luminanceOffsets[1] = 0.5 * sV;
  33900. luminanceOffsets[2] = 0.5 * sU;
  33901. luminanceOffsets[3] = 0.5 * sV;
  33902. luminanceOffsets[4] = -0.5 * sU;
  33903. luminanceOffsets[5] = -0.5 * sV;
  33904. luminanceOffsets[6] = 0.5 * sU;
  33905. luminanceOffsets[7] = -0.5 * sV;
  33906. };
  33907. var luminanceUpdateDestOffsets = function (width, height) {
  33908. var id = 0;
  33909. for (var x = -1; x < 2; x++) {
  33910. for (var y = -1; y < 2; y++) {
  33911. downSampleOffsets[id] = (x) / width;
  33912. downSampleOffsets[id + 1] = (y) / height;
  33913. id += 2;
  33914. }
  33915. }
  33916. };
  33917. // Luminance callback
  33918. var luminanceCallback = function (effect) {
  33919. if (_this._needUpdate) {
  33920. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33921. }
  33922. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33923. effect.setArray2("lumOffsets", luminanceOffsets);
  33924. };
  33925. // Down sample callbacks
  33926. var downSampleCallback = function (indice) {
  33927. var i = indice;
  33928. return function (effect) {
  33929. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33930. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33931. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33932. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33933. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33934. effect.setArray2("dsOffsets", downSampleOffsets);
  33935. };
  33936. };
  33937. var downSampleAfterRenderCallback = function (effect) {
  33938. // Unpack result
  33939. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33940. 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);
  33941. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33942. };
  33943. // Create luminance post-process
  33944. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33945. 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);
  33946. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33947. // Create down sample post-processes
  33948. for (var i = lumSteps - 2; i >= 0; i--) {
  33949. var length = Math.pow(3, i);
  33950. ratio = { width: length, height: length };
  33951. var defines = "#define DOWN_SAMPLE\n";
  33952. if (i === 0) {
  33953. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33954. }
  33955. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33956. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33957. if (i === 0) {
  33958. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33959. }
  33960. }
  33961. };
  33962. /**
  33963. * Gaussian blur post-processes. Horizontal and Vertical
  33964. */
  33965. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33966. var _this = this;
  33967. var blurOffsetsW = new Array(9);
  33968. var blurOffsetsH = new Array(9);
  33969. var blurWeights = new Array(9);
  33970. var uniforms = ["blurOffsets", "blurWeights"];
  33971. // Utils for gaussian blur
  33972. var calculateBlurOffsets = function (height) {
  33973. var lastOutputDimensions = {
  33974. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33975. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33976. };
  33977. for (var i = 0; i < 9; i++) {
  33978. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33979. if (height) {
  33980. blurOffsetsH[i] = value;
  33981. }
  33982. else {
  33983. blurOffsetsW[i] = value;
  33984. }
  33985. }
  33986. };
  33987. var calculateWeights = function () {
  33988. var x = 0.0;
  33989. for (var i = 0; i < 9; i++) {
  33990. x = (i - 4.0) / 4.0;
  33991. 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));
  33992. }
  33993. };
  33994. // Callback
  33995. var gaussianBlurCallback = function (height) {
  33996. return function (effect) {
  33997. if (_this._needUpdate) {
  33998. calculateWeights();
  33999. calculateBlurOffsets(height);
  34000. }
  34001. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  34002. effect.setArray("blurWeights", blurWeights);
  34003. };
  34004. };
  34005. // Create horizontal gaussian blur post-processes
  34006. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  34007. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34008. // Create vertical gaussian blur post-process
  34009. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34010. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34011. };
  34012. // Luminance generator
  34013. HDRRenderingPipeline.LUM_STEPS = 6;
  34014. return HDRRenderingPipeline;
  34015. })(BABYLON.PostProcessRenderPipeline);
  34016. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34017. })(BABYLON || (BABYLON = {}));
  34018. var BABYLON;
  34019. (function (BABYLON) {
  34020. var FaceAdjacencies = (function () {
  34021. function FaceAdjacencies() {
  34022. this.edges = new Array();
  34023. this.edgesConnectedCount = 0;
  34024. }
  34025. return FaceAdjacencies;
  34026. })();
  34027. var EdgesRenderer = (function () {
  34028. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34029. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34030. if (epsilon === void 0) { epsilon = 0.95; }
  34031. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34032. this._linesPositions = new Array();
  34033. this._linesNormals = new Array();
  34034. this._linesIndices = new Array();
  34035. this._buffers = new Array();
  34036. this._checkVerticesInsteadOfIndices = false;
  34037. this._source = source;
  34038. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34039. this._epsilon = epsilon;
  34040. this._prepareRessources();
  34041. this._generateEdgesLines();
  34042. }
  34043. EdgesRenderer.prototype._prepareRessources = function () {
  34044. if (this._lineShader) {
  34045. return;
  34046. }
  34047. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34048. attributes: ["position", "normal"],
  34049. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34050. });
  34051. this._lineShader.disableDepthWrite = true;
  34052. this._lineShader.backFaceCulling = false;
  34053. };
  34054. EdgesRenderer.prototype.dispose = function () {
  34055. this._vb0.dispose();
  34056. this._vb1.dispose();
  34057. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34058. this._lineShader.dispose();
  34059. };
  34060. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34061. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34062. return 0;
  34063. }
  34064. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34065. return 1;
  34066. }
  34067. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34068. return 2;
  34069. }
  34070. return -1;
  34071. };
  34072. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34073. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34074. return 0;
  34075. }
  34076. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34077. return 1;
  34078. }
  34079. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34080. return 2;
  34081. }
  34082. return -1;
  34083. };
  34084. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34085. var needToCreateLine;
  34086. if (edge === undefined) {
  34087. needToCreateLine = true;
  34088. }
  34089. else {
  34090. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34091. needToCreateLine = dotProduct < this._epsilon;
  34092. }
  34093. if (needToCreateLine) {
  34094. var offset = this._linesPositions.length / 3;
  34095. var normal = p0.subtract(p1);
  34096. normal.normalize();
  34097. // Positions
  34098. this._linesPositions.push(p0.x);
  34099. this._linesPositions.push(p0.y);
  34100. this._linesPositions.push(p0.z);
  34101. this._linesPositions.push(p0.x);
  34102. this._linesPositions.push(p0.y);
  34103. this._linesPositions.push(p0.z);
  34104. this._linesPositions.push(p1.x);
  34105. this._linesPositions.push(p1.y);
  34106. this._linesPositions.push(p1.z);
  34107. this._linesPositions.push(p1.x);
  34108. this._linesPositions.push(p1.y);
  34109. this._linesPositions.push(p1.z);
  34110. // Normals
  34111. this._linesNormals.push(p1.x);
  34112. this._linesNormals.push(p1.y);
  34113. this._linesNormals.push(p1.z);
  34114. this._linesNormals.push(-1);
  34115. this._linesNormals.push(p1.x);
  34116. this._linesNormals.push(p1.y);
  34117. this._linesNormals.push(p1.z);
  34118. this._linesNormals.push(1);
  34119. this._linesNormals.push(p0.x);
  34120. this._linesNormals.push(p0.y);
  34121. this._linesNormals.push(p0.z);
  34122. this._linesNormals.push(-1);
  34123. this._linesNormals.push(p0.x);
  34124. this._linesNormals.push(p0.y);
  34125. this._linesNormals.push(p0.z);
  34126. this._linesNormals.push(1);
  34127. // Indices
  34128. this._linesIndices.push(offset);
  34129. this._linesIndices.push(offset + 1);
  34130. this._linesIndices.push(offset + 2);
  34131. this._linesIndices.push(offset);
  34132. this._linesIndices.push(offset + 2);
  34133. this._linesIndices.push(offset + 3);
  34134. }
  34135. };
  34136. EdgesRenderer.prototype._generateEdgesLines = function () {
  34137. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34138. var indices = this._source.getIndices();
  34139. // First let's find adjacencies
  34140. var adjacencies = new Array();
  34141. var faceNormals = new Array();
  34142. var index;
  34143. var faceAdjacencies;
  34144. // Prepare faces
  34145. for (index = 0; index < indices.length; index += 3) {
  34146. faceAdjacencies = new FaceAdjacencies();
  34147. var p0Index = indices[index];
  34148. var p1Index = indices[index + 1];
  34149. var p2Index = indices[index + 2];
  34150. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34151. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34152. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34153. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34154. faceNormal.normalize();
  34155. faceNormals.push(faceNormal);
  34156. adjacencies.push(faceAdjacencies);
  34157. }
  34158. // Scan
  34159. for (index = 0; index < adjacencies.length; index++) {
  34160. faceAdjacencies = adjacencies[index];
  34161. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34162. var otherFaceAdjacencies = adjacencies[otherIndex];
  34163. if (faceAdjacencies.edgesConnectedCount === 3) {
  34164. break;
  34165. }
  34166. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34167. continue;
  34168. }
  34169. var otherP0 = indices[otherIndex * 3];
  34170. var otherP1 = indices[otherIndex * 3 + 1];
  34171. var otherP2 = indices[otherIndex * 3 + 2];
  34172. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34173. var otherEdgeIndex;
  34174. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34175. continue;
  34176. }
  34177. switch (edgeIndex) {
  34178. case 0:
  34179. if (this._checkVerticesInsteadOfIndices) {
  34180. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34181. }
  34182. else {
  34183. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34184. }
  34185. break;
  34186. case 1:
  34187. if (this._checkVerticesInsteadOfIndices) {
  34188. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34189. }
  34190. else {
  34191. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34192. }
  34193. break;
  34194. case 2:
  34195. if (this._checkVerticesInsteadOfIndices) {
  34196. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34197. }
  34198. else {
  34199. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34200. }
  34201. break;
  34202. }
  34203. if (otherEdgeIndex === -1) {
  34204. continue;
  34205. }
  34206. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34207. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34208. faceAdjacencies.edgesConnectedCount++;
  34209. otherFaceAdjacencies.edgesConnectedCount++;
  34210. if (faceAdjacencies.edgesConnectedCount === 3) {
  34211. break;
  34212. }
  34213. }
  34214. }
  34215. }
  34216. // Create lines
  34217. for (index = 0; index < adjacencies.length; index++) {
  34218. // 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
  34219. var current = adjacencies[index];
  34220. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34221. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34222. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34223. }
  34224. // Merge into a single mesh
  34225. var engine = this._source.getScene().getEngine();
  34226. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34227. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34228. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34229. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34230. this._ib = engine.createIndexBuffer(this._linesIndices);
  34231. this._indicesCount = this._linesIndices.length;
  34232. };
  34233. EdgesRenderer.prototype.render = function () {
  34234. if (!this._lineShader.isReady()) {
  34235. return;
  34236. }
  34237. var scene = this._source.getScene();
  34238. var engine = scene.getEngine();
  34239. this._lineShader._preBind();
  34240. // VBOs
  34241. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34242. scene.resetCachedMaterial();
  34243. this._lineShader.setColor4("color", this._source.edgesColor);
  34244. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34245. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34246. this._lineShader.bind(this._source.getWorldMatrix());
  34247. // Draw order
  34248. engine.draw(true, 0, this._indicesCount);
  34249. this._lineShader.unbind();
  34250. engine.setDepthWrite(true);
  34251. };
  34252. return EdgesRenderer;
  34253. })();
  34254. BABYLON.EdgesRenderer = EdgesRenderer;
  34255. })(BABYLON || (BABYLON = {}));
  34256. var BABYLON;
  34257. (function (BABYLON) {
  34258. (function (TonemappingOperator) {
  34259. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34260. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34261. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34262. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34263. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34264. var TonemappingOperator = BABYLON.TonemappingOperator;
  34265. ;
  34266. var TonemapPostProcess = (function (_super) {
  34267. __extends(TonemapPostProcess, _super);
  34268. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34269. var _this = this;
  34270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34271. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34272. this._operator = operator;
  34273. this._exposureAdjustment = exposureAdjustment;
  34274. var params = ["_ExposureAdjustment"];
  34275. var defines = "#define ";
  34276. if (operator === TonemappingOperator.Hable)
  34277. defines += "HABLE_TONEMAPPING";
  34278. else if (operator === TonemappingOperator.Reinhard)
  34279. defines += "REINHARD_TONEMAPPING";
  34280. else if (operator === TonemappingOperator.HejiDawson)
  34281. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34282. else if (operator === TonemappingOperator.Photographic)
  34283. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34284. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34285. this.onApply = function (effect) {
  34286. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34287. };
  34288. }
  34289. return TonemapPostProcess;
  34290. })(BABYLON.PostProcess);
  34291. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34292. })(BABYLON || (BABYLON = {}));
  34293. var BABYLON;
  34294. (function (BABYLON) {
  34295. var DefaultLoadingScreen = (function () {
  34296. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34297. var _this = this;
  34298. if (_loadingText === void 0) { _loadingText = ""; }
  34299. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34300. this._renderingCanvas = _renderingCanvas;
  34301. this._loadingText = _loadingText;
  34302. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34303. // Resize
  34304. this._resizeLoadingUI = function () {
  34305. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34306. _this._loadingDiv.style.position = "absolute";
  34307. _this._loadingDiv.style.left = canvasRect.left + "px";
  34308. _this._loadingDiv.style.top = canvasRect.top + "px";
  34309. _this._loadingDiv.style.width = canvasRect.width + "px";
  34310. _this._loadingDiv.style.height = canvasRect.height + "px";
  34311. };
  34312. }
  34313. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34314. var _this = this;
  34315. this._loadingDiv = document.createElement("div");
  34316. this._loadingDiv.style.opacity = "0";
  34317. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34318. // Loading text
  34319. this._loadingTextDiv = document.createElement("div");
  34320. this._loadingTextDiv.style.position = "absolute";
  34321. this._loadingTextDiv.style.left = "0";
  34322. this._loadingTextDiv.style.top = "50%";
  34323. this._loadingTextDiv.style.marginTop = "80px";
  34324. this._loadingTextDiv.style.width = "100%";
  34325. this._loadingTextDiv.style.height = "20px";
  34326. this._loadingTextDiv.style.fontFamily = "Arial";
  34327. this._loadingTextDiv.style.fontSize = "14px";
  34328. this._loadingTextDiv.style.color = "white";
  34329. this._loadingTextDiv.style.textAlign = "center";
  34330. this._loadingTextDiv.innerHTML = "Loading";
  34331. this._loadingDiv.appendChild(this._loadingTextDiv);
  34332. //set the predefined text
  34333. this._loadingTextDiv.innerHTML = this._loadingText;
  34334. // Loading img
  34335. var imgBack = new Image();
  34336. 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==";
  34337. imgBack.style.position = "absolute";
  34338. imgBack.style.left = "50%";
  34339. imgBack.style.top = "50%";
  34340. imgBack.style.marginLeft = "-50px";
  34341. imgBack.style.marginTop = "-50px";
  34342. imgBack.style.transition = "transform 1.0s ease";
  34343. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34344. var deg = 360;
  34345. var onTransitionEnd = function () {
  34346. deg += 360;
  34347. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34348. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34349. };
  34350. imgBack.addEventListener("transitionend", onTransitionEnd);
  34351. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34352. this._loadingDiv.appendChild(imgBack);
  34353. // front image
  34354. var imgFront = new Image();
  34355. 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=";
  34356. imgFront.style.position = "absolute";
  34357. imgFront.style.left = "50%";
  34358. imgFront.style.top = "50%";
  34359. imgFront.style.marginLeft = "-50px";
  34360. imgFront.style.marginTop = "-50px";
  34361. this._loadingDiv.appendChild(imgFront);
  34362. this._resizeLoadingUI();
  34363. window.addEventListener("resize", this._resizeLoadingUI);
  34364. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34365. document.body.appendChild(this._loadingDiv);
  34366. setTimeout(function () {
  34367. _this._loadingDiv.style.opacity = "1";
  34368. imgBack.style.transform = "rotateZ(360deg)";
  34369. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34370. }, 0);
  34371. };
  34372. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34373. var _this = this;
  34374. if (!this._loadingDiv) {
  34375. return;
  34376. }
  34377. var onTransitionEnd = function () {
  34378. if (!_this._loadingDiv) {
  34379. return;
  34380. }
  34381. document.body.removeChild(_this._loadingDiv);
  34382. window.removeEventListener("resize", _this._resizeLoadingUI);
  34383. _this._loadingDiv = null;
  34384. };
  34385. this._loadingDiv.style.opacity = "0";
  34386. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34387. };
  34388. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34389. set: function (text) {
  34390. this._loadingText = text;
  34391. if (this._loadingTextDiv) {
  34392. this._loadingTextDiv.innerHTML = this._loadingText;
  34393. }
  34394. },
  34395. enumerable: true,
  34396. configurable: true
  34397. });
  34398. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34399. get: function () {
  34400. return this._loadingDivBackgroundColor;
  34401. },
  34402. set: function (color) {
  34403. this._loadingDivBackgroundColor = color;
  34404. if (!this._loadingDiv) {
  34405. return;
  34406. }
  34407. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34408. },
  34409. enumerable: true,
  34410. configurable: true
  34411. });
  34412. return DefaultLoadingScreen;
  34413. })();
  34414. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34415. })(BABYLON || (BABYLON = {}));
  34416. var BABYLON;
  34417. (function (BABYLON) {
  34418. var maxSimultaneousLights = 4;
  34419. var PBRMaterialDefines = (function () {
  34420. function PBRMaterialDefines() {
  34421. this.ALBEDO = false;
  34422. this.CLIPPLANE = false;
  34423. this.ALPHATEST = false;
  34424. this.FOG = false;
  34425. this.NORMAL = false;
  34426. this.UV1 = false;
  34427. this.UV2 = false;
  34428. this.VERTEXCOLOR = false;
  34429. this.VERTEXALPHA = false;
  34430. this.BONES = false;
  34431. this.BONES4 = false;
  34432. this.BonesPerMesh = 0;
  34433. this.INSTANCES = false;
  34434. this.POINTSIZE = false;
  34435. this._keys = Object.keys(this);
  34436. }
  34437. PBRMaterialDefines.prototype.isEqual = function (other) {
  34438. for (var index = 0; index < this._keys.length; index++) {
  34439. var prop = this._keys[index];
  34440. if (this[prop] !== other[prop]) {
  34441. return false;
  34442. }
  34443. }
  34444. return true;
  34445. };
  34446. PBRMaterialDefines.prototype.cloneTo = function (other) {
  34447. for (var index = 0; index < this._keys.length; index++) {
  34448. var prop = this._keys[index];
  34449. other[prop] = this[prop];
  34450. }
  34451. };
  34452. PBRMaterialDefines.prototype.reset = function () {
  34453. for (var index = 0; index < this._keys.length; index++) {
  34454. var prop = this._keys[index];
  34455. if (prop === "BonesPerMesh") {
  34456. this[prop] = 0;
  34457. continue;
  34458. }
  34459. this[prop] = false;
  34460. }
  34461. };
  34462. PBRMaterialDefines.prototype.toString = function () {
  34463. var result = "";
  34464. for (var index = 0; index < this._keys.length; index++) {
  34465. var prop = this._keys[index];
  34466. if (prop === "BonesPerMesh" && this[prop] > 0) {
  34467. result += "#define BonesPerMesh " + this[prop] + "\n";
  34468. continue;
  34469. }
  34470. if (this[prop]) {
  34471. result += "#define " + prop + "\n";
  34472. }
  34473. }
  34474. return result;
  34475. };
  34476. return PBRMaterialDefines;
  34477. })();
  34478. var PBRMaterial = (function (_super) {
  34479. __extends(PBRMaterial, _super);
  34480. function PBRMaterial(name, scene) {
  34481. _super.call(this, name, scene);
  34482. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34483. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34484. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34485. this._scaledDiffuse = new BABYLON.Color3();
  34486. this._scaledSpecular = new BABYLON.Color3();
  34487. this._defines = new PBRMaterialDefines();
  34488. this._cachedDefines = new PBRMaterialDefines();
  34489. this._cachedDefines.BonesPerMesh = -1;
  34490. }
  34491. PBRMaterial.prototype.needAlphaBlending = function () {
  34492. return this.alpha < 1.0;
  34493. };
  34494. PBRMaterial.prototype.needAlphaTesting = function () {
  34495. return false;
  34496. };
  34497. PBRMaterial.prototype.getAlphaTestTexture = function () {
  34498. return null;
  34499. };
  34500. // Methods
  34501. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  34502. if (this.checkReadyOnlyOnce) {
  34503. if (this._wasPreviouslyReady) {
  34504. return true;
  34505. }
  34506. }
  34507. var scene = this.getScene();
  34508. if (!this.checkReadyOnEveryCall) {
  34509. if (this._renderId === scene.getRenderId()) {
  34510. return true;
  34511. }
  34512. }
  34513. var engine = scene.getEngine();
  34514. var needNormals = false;
  34515. var needUVs = false;
  34516. this._defines.reset();
  34517. // Textures
  34518. if (scene.texturesEnabled) {
  34519. }
  34520. // Effect
  34521. if (scene.clipPlane) {
  34522. this._defines.CLIPPLANE = true;
  34523. }
  34524. if (engine.getAlphaTesting()) {
  34525. this._defines.ALPHATEST = true;
  34526. }
  34527. // Point size
  34528. if (this.pointsCloud || scene.forcePointsCloud) {
  34529. this._defines.POINTSIZE = true;
  34530. }
  34531. // Fog
  34532. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34533. this._defines.FOG = true;
  34534. }
  34535. // Lights
  34536. // Attribs
  34537. if (mesh) {
  34538. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34539. this._defines.NORMAL = true;
  34540. }
  34541. if (needUVs) {
  34542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34543. this._defines.UV1 = true;
  34544. }
  34545. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34546. this._defines.UV2 = true;
  34547. }
  34548. }
  34549. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34550. this._defines.VERTEXCOLOR = true;
  34551. if (mesh.hasVertexAlpha) {
  34552. this._defines.VERTEXALPHA = true;
  34553. }
  34554. }
  34555. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34556. this._defines.BONES = true;
  34557. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  34558. this._defines.BONES4 = true;
  34559. }
  34560. // Instances
  34561. if (useInstances) {
  34562. this._defines.INSTANCES = true;
  34563. }
  34564. }
  34565. // Get correct effect
  34566. if (!this._defines.isEqual(this._cachedDefines)) {
  34567. this._defines.cloneTo(this._cachedDefines);
  34568. scene.resetCachedMaterial();
  34569. // Fallbacks
  34570. var fallbacks = new BABYLON.EffectFallbacks();
  34571. if (this._defines.FOG) {
  34572. fallbacks.addFallback(1, "FOG");
  34573. }
  34574. if (this._defines.BONES4) {
  34575. fallbacks.addFallback(0, "BONES4");
  34576. }
  34577. //Attributes
  34578. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34579. if (this._defines.NORMAL) {
  34580. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34581. }
  34582. if (this._defines.UV1) {
  34583. attribs.push(BABYLON.VertexBuffer.UVKind);
  34584. }
  34585. if (this._defines.UV2) {
  34586. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34587. }
  34588. if (this._defines.VERTEXCOLOR) {
  34589. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34590. }
  34591. if (this._defines.BONES) {
  34592. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34593. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34594. }
  34595. if (this._defines.INSTANCES) {
  34596. attribs.push("world0");
  34597. attribs.push("world1");
  34598. attribs.push("world2");
  34599. attribs.push("world3");
  34600. }
  34601. // Legacy browser patch
  34602. var join = this._defines.toString();
  34603. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  34604. "vFogInfos", "vFogColor", "pointSize",
  34605. "mBones",
  34606. "vClipPlane",
  34607. ], [], join, fallbacks, this.onCompiled, this.onError);
  34608. }
  34609. if (!this._effect.isReady()) {
  34610. return false;
  34611. }
  34612. this._renderId = scene.getRenderId();
  34613. this._wasPreviouslyReady = true;
  34614. return true;
  34615. };
  34616. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34617. this._effect.setMatrix("world", world);
  34618. };
  34619. PBRMaterial.prototype.bind = function (world, mesh) {
  34620. var scene = this.getScene();
  34621. // Matrices
  34622. this.bindOnlyWorldMatrix(world);
  34623. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34624. // Bones
  34625. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34626. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34627. }
  34628. if (scene.getCachedMaterial() !== this) {
  34629. // Clip plane
  34630. if (scene.clipPlane) {
  34631. var clipPlane = scene.clipPlane;
  34632. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34633. }
  34634. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  34635. }
  34636. // Point size
  34637. if (this.pointsCloud) {
  34638. this._effect.setFloat("pointSize", this.pointSize);
  34639. }
  34640. // Colors
  34641. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  34642. // View
  34643. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34644. this._effect.setMatrix("view", scene.getViewMatrix());
  34645. }
  34646. // Fog
  34647. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34648. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34649. this._effect.setColor3("vFogColor", scene.fogColor);
  34650. }
  34651. _super.prototype.bind.call(this, world, mesh);
  34652. };
  34653. PBRMaterial.prototype.getAnimatables = function () {
  34654. var results = [];
  34655. return results;
  34656. };
  34657. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  34658. _super.prototype.dispose.call(this, forceDisposeEffect);
  34659. };
  34660. PBRMaterial.prototype.clone = function (name) {
  34661. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  34662. // Base material
  34663. this.copyTo(newPBRMaterial);
  34664. // PBRMaterial material
  34665. newPBRMaterial.albedoColor = this.albedoColor.clone();
  34666. return newPBRMaterial;
  34667. };
  34668. return PBRMaterial;
  34669. })(BABYLON.Material);
  34670. BABYLON.PBRMaterial = PBRMaterial;
  34671. })(BABYLON || (BABYLON = {}));
  34672. var BABYLON;
  34673. (function (BABYLON) {
  34674. var ReflectionProbe = (function () {
  34675. //http://localhost:61437/Playground/index%20-%20debug.html#KA93U#7
  34676. function ReflectionProbe(name, size, scene, generateMipMaps) {
  34677. var _this = this;
  34678. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34679. this.name = name;
  34680. this._viewMatrix = BABYLON.Matrix.Identity();
  34681. this._target = BABYLON.Vector3.Zero();
  34682. this._add = BABYLON.Vector3.Zero();
  34683. this.position = BABYLON.Vector3.Zero();
  34684. this._scene = scene;
  34685. this._scene.reflectionProbes.push(this);
  34686. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  34687. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  34688. switch (faceIndex) {
  34689. case 0:
  34690. _this._add.copyFromFloats(1, 0, 0);
  34691. break;
  34692. case 1:
  34693. _this._add.copyFromFloats(-1, 0, 0);
  34694. break;
  34695. case 2:
  34696. _this._add.copyFromFloats(0, -1, 0);
  34697. break;
  34698. case 3:
  34699. _this._add.copyFromFloats(0, 1, 0);
  34700. break;
  34701. case 4:
  34702. _this._add.copyFromFloats(0, 0, 1);
  34703. break;
  34704. case 5:
  34705. _this._add.copyFromFloats(0, 0, -1);
  34706. break;
  34707. }
  34708. if (_this._attachedMesh) {
  34709. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  34710. }
  34711. _this.position.addToRef(_this._add, _this._target);
  34712. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  34713. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  34714. };
  34715. this._renderTargetTexture.onAfterUnbind = function () {
  34716. scene.updateTransformMatrix(true);
  34717. };
  34718. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  34719. }
  34720. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  34721. get: function () {
  34722. return this._renderTargetTexture.refreshRate;
  34723. },
  34724. set: function (value) {
  34725. this._renderTargetTexture.refreshRate = value;
  34726. },
  34727. enumerable: true,
  34728. configurable: true
  34729. });
  34730. ReflectionProbe.prototype.getScene = function () {
  34731. return this._scene;
  34732. };
  34733. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  34734. get: function () {
  34735. return this._renderTargetTexture;
  34736. },
  34737. enumerable: true,
  34738. configurable: true
  34739. });
  34740. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  34741. get: function () {
  34742. return this._renderTargetTexture.renderList;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  34748. this._attachedMesh = mesh;
  34749. };
  34750. ReflectionProbe.prototype.dispose = function () {
  34751. var index = this._scene.reflectionProbes.indexOf(this);
  34752. if (index !== -1) {
  34753. // Remove from the scene if found
  34754. this._scene.reflectionProbes.splice(index, 1);
  34755. }
  34756. };
  34757. return ReflectionProbe;
  34758. })();
  34759. BABYLON.ReflectionProbe = ReflectionProbe;
  34760. })(BABYLON || (BABYLON = {}));
  34761. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\n#ifdef ROUGHNESS\r\nuniform float roughness;\r\n#endif\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\t\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = glossiness * specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\t\tbias = roughness;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n vec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\tfloat lightmapIllum = clamp(dot(lightmapColor, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n\r\n\tif (lightmapIllum > vLightmapInfos.z)\r\n\t{\r\n\t\tcolor.rgb += lightmapColor;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t}\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec3 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  34762. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert();var u=new i(o.x/n*2-1,-(o.y/r*2-1),o.z),l=i.TransformCoordinates(u,h),m=u.x*h.m[3]+u.y*h.m[7]+u.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(m,1)&&(l=l.scale(1/m)),l},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r=i.Zero();return i.RotationFromAxisToRef(t,o,n,r),r},i.RotationFromAxisToRef=function(o,n,r,s){var e,a,h,u=i.Normalize(o),l=i.Normalize(r),m=f.X,x=f.Y,y=0,c=0,p=0,z=0,M=0,w=0,d=0,I=-1,D=0,S=0;t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?w=1:t.Tools.WithinEpsilon(l.x,0,t.Engine.Epsilon)?z=1:(d=l.z/l.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),a=new i(z,M,w),a.normalize(),h=i.Cross(l,a),h.normalize(),e=i.Cross(u,a),e.normalize(),i.Dot(l,e)<0&&(I=1),S=i.Dot(u,a),S=Math.min(1,Math.max(-1,S)),p=Math.acos(S)*I,i.Dot(a,m)<0&&(p=Math.PI+p,a=a.scaleInPlace(-1),h=h.scaleInPlace(-1),D++);var v,g;z=0,M=0,w=0,I=-1,t.Tools.WithinEpsilon(l.z,0,t.Engine.Epsilon)?z=1:(d=a.z/a.x,z=-d*Math.sqrt(1/(1+d*d)),w=Math.sqrt(1/(1+d*d))),v=new i(z,M,w),v.normalize(),g=i.Cross(v,a),g.normalize(),e=i.Cross(l,v),e.normalize(),i.Dot(a,e)<0&&(I=1),S=i.Dot(l,v),S=Math.min(1,Math.max(-1,S)),c=Math.acos(S)*I,i.Dot(g,x)<0&&(c=Math.PI+c,g=g.scaleInPlace(-1),v=v.scaleInPlace(-1),D++),I=-1,e=i.Cross(m,a),e.normalize(),i.Dot(e,x)<0&&(I=1),S=i.Dot(a,m),S=Math.min(1,Math.max(-1,S)),y=-Math.acos(S)*I,0>S&&2>D&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return i.normalize(),n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=i.Zero();return i.RotationAxisToRef(t,o,n),n},i.RotationAxisToRef=function(t,i,o){var n=Math.sin(-i),r=Math.cos(-i),s=1-r;t.normalize(),o.m[0]=t.x*t.x*s+r,o.m[1]=t.x*t.y*s-t.z*n,o.m[2]=t.x*t.z*s+t.y*n,o.m[3]=0,o.m[4]=t.y*t.x*s+t.z*n,o.m[5]=t.y*t.y*s+r,o.m[6]=t.y*t.z*s-t.x*n,o.m[7]=0,o.m[8]=t.z*t.x*s-t.y*n,o.m[9]=t.z*t.y*s+t.x*n,o.m[10]=t.z*t.z*s+r,o.m[11]=0,o.m[15]=1},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i,o){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=o||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._raw||this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  34763. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  34764. module.exports = BABYLON;
  34765. };