babylon.max.js 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992
  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 ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. return Color4;
  270. })();
  271. BABYLON.Color4 = Color4;
  272. var Vector2 = (function () {
  273. function Vector2(x, y) {
  274. this.x = x;
  275. this.y = y;
  276. }
  277. Vector2.prototype.toString = function () {
  278. return "{X: " + this.x + " Y:" + this.y + "}";
  279. };
  280. // Operators
  281. Vector2.prototype.toArray = function (array, index) {
  282. if (index === void 0) { index = 0; }
  283. array[index] = this.x;
  284. array[index + 1] = this.y;
  285. return this;
  286. };
  287. Vector2.prototype.asArray = function () {
  288. var result = [];
  289. this.toArray(result, 0);
  290. return result;
  291. };
  292. Vector2.prototype.copyFrom = function (source) {
  293. this.x = source.x;
  294. this.y = source.y;
  295. return this;
  296. };
  297. Vector2.prototype.copyFromFloats = function (x, y) {
  298. this.x = x;
  299. this.y = y;
  300. return this;
  301. };
  302. Vector2.prototype.add = function (otherVector) {
  303. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  304. };
  305. Vector2.prototype.addVector3 = function (otherVector) {
  306. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  307. };
  308. Vector2.prototype.subtract = function (otherVector) {
  309. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  310. };
  311. Vector2.prototype.subtractInPlace = function (otherVector) {
  312. this.x -= otherVector.x;
  313. this.y -= otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.multiplyInPlace = function (otherVector) {
  317. this.x *= otherVector.x;
  318. this.y *= otherVector.y;
  319. return this;
  320. };
  321. Vector2.prototype.multiply = function (otherVector) {
  322. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  323. };
  324. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  325. result.x = this.x * otherVector.x;
  326. result.y = this.y * otherVector.y;
  327. return this;
  328. };
  329. Vector2.prototype.multiplyByFloats = function (x, y) {
  330. return new Vector2(this.x * x, this.y * y);
  331. };
  332. Vector2.prototype.divide = function (otherVector) {
  333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  334. };
  335. Vector2.prototype.divideToRef = function (otherVector, result) {
  336. result.x = this.x / otherVector.x;
  337. result.y = this.y / otherVector.y;
  338. return this;
  339. };
  340. Vector2.prototype.negate = function () {
  341. return new Vector2(-this.x, -this.y);
  342. };
  343. Vector2.prototype.scaleInPlace = function (scale) {
  344. this.x *= scale;
  345. this.y *= scale;
  346. return this;
  347. };
  348. Vector2.prototype.scale = function (scale) {
  349. return new Vector2(this.x * scale, this.y * scale);
  350. };
  351. Vector2.prototype.equals = function (otherVector) {
  352. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  353. };
  354. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  355. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  356. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  357. };
  358. // Properties
  359. Vector2.prototype.length = function () {
  360. return Math.sqrt(this.x * this.x + this.y * this.y);
  361. };
  362. Vector2.prototype.lengthSquared = function () {
  363. return (this.x * this.x + this.y * this.y);
  364. };
  365. // Methods
  366. Vector2.prototype.normalize = function () {
  367. var len = this.length();
  368. if (len === 0)
  369. return this;
  370. var num = 1.0 / len;
  371. this.x *= num;
  372. this.y *= num;
  373. return this;
  374. };
  375. Vector2.prototype.clone = function () {
  376. return new Vector2(this.x, this.y);
  377. };
  378. // Statics
  379. Vector2.Zero = function () {
  380. return new Vector2(0, 0);
  381. };
  382. Vector2.FromArray = function (array, offset) {
  383. if (offset === void 0) { offset = 0; }
  384. return new Vector2(array[offset], array[offset + 1]);
  385. };
  386. Vector2.FromArrayToRef = function (array, offset, result) {
  387. result.x = array[offset];
  388. result.y = array[offset + 1];
  389. };
  390. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  391. var squared = amount * amount;
  392. var cubed = amount * squared;
  393. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  394. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  395. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  396. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  397. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  398. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  399. return new Vector2(x, y);
  400. };
  401. Vector2.Clamp = function (value, min, max) {
  402. var x = value.x;
  403. x = (x > max.x) ? max.x : x;
  404. x = (x < min.x) ? min.x : x;
  405. var y = value.y;
  406. y = (y > max.y) ? max.y : y;
  407. y = (y < min.y) ? min.y : y;
  408. return new Vector2(x, y);
  409. };
  410. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  411. var squared = amount * amount;
  412. var cubed = amount * squared;
  413. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  414. var part2 = (-2.0 * cubed) + (3.0 * squared);
  415. var part3 = (cubed - (2.0 * squared)) + amount;
  416. var part4 = cubed - squared;
  417. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  418. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  419. return new Vector2(x, y);
  420. };
  421. Vector2.Lerp = function (start, end, amount) {
  422. var x = start.x + ((end.x - start.x) * amount);
  423. var y = start.y + ((end.y - start.y) * amount);
  424. return new Vector2(x, y);
  425. };
  426. Vector2.Dot = function (left, right) {
  427. return left.x * right.x + left.y * right.y;
  428. };
  429. Vector2.Normalize = function (vector) {
  430. var newVector = vector.clone();
  431. newVector.normalize();
  432. return newVector;
  433. };
  434. Vector2.Minimize = function (left, right) {
  435. var x = (left.x < right.x) ? left.x : right.x;
  436. var y = (left.y < right.y) ? left.y : right.y;
  437. return new Vector2(x, y);
  438. };
  439. Vector2.Maximize = function (left, right) {
  440. var x = (left.x > right.x) ? left.x : right.x;
  441. var y = (left.y > right.y) ? left.y : right.y;
  442. return new Vector2(x, y);
  443. };
  444. Vector2.Transform = function (vector, transformation) {
  445. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  446. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  447. return new Vector2(x, y);
  448. };
  449. Vector2.Distance = function (value1, value2) {
  450. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  451. };
  452. Vector2.DistanceSquared = function (value1, value2) {
  453. var x = value1.x - value2.x;
  454. var y = value1.y - value2.y;
  455. return (x * x) + (y * y);
  456. };
  457. return Vector2;
  458. })();
  459. BABYLON.Vector2 = Vector2;
  460. var Vector3 = (function () {
  461. function Vector3(x, y, z) {
  462. this.x = x;
  463. this.y = y;
  464. this.z = z;
  465. }
  466. Vector3.prototype.toString = function () {
  467. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  468. };
  469. // Operators
  470. Vector3.prototype.asArray = function () {
  471. var result = [];
  472. this.toArray(result, 0);
  473. return result;
  474. };
  475. Vector3.prototype.toArray = function (array, index) {
  476. if (index === void 0) { index = 0; }
  477. array[index] = this.x;
  478. array[index + 1] = this.y;
  479. array[index + 2] = this.z;
  480. return this;
  481. };
  482. Vector3.prototype.toQuaternion = function () {
  483. var result = new Quaternion(0, 0, 0, 1);
  484. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  485. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  486. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  487. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  488. var cosy = Math.cos(this.y * 0.5);
  489. var siny = Math.sin(this.y * 0.5);
  490. result.x = coszMinusx * siny;
  491. result.y = -sinzMinusx * siny;
  492. result.z = sinxPlusz * cosy;
  493. result.w = cosxPlusz * cosy;
  494. return result;
  495. };
  496. Vector3.prototype.addInPlace = function (otherVector) {
  497. this.x += otherVector.x;
  498. this.y += otherVector.y;
  499. this.z += otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.add = function (otherVector) {
  503. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  504. };
  505. Vector3.prototype.addToRef = function (otherVector, result) {
  506. result.x = this.x + otherVector.x;
  507. result.y = this.y + otherVector.y;
  508. result.z = this.z + otherVector.z;
  509. return this;
  510. };
  511. Vector3.prototype.subtractInPlace = function (otherVector) {
  512. this.x -= otherVector.x;
  513. this.y -= otherVector.y;
  514. this.z -= otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.subtract = function (otherVector) {
  518. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  519. };
  520. Vector3.prototype.subtractToRef = function (otherVector, result) {
  521. result.x = this.x - otherVector.x;
  522. result.y = this.y - otherVector.y;
  523. result.z = this.z - otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  527. return new Vector3(this.x - x, this.y - y, this.z - z);
  528. };
  529. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  530. result.x = this.x - x;
  531. result.y = this.y - y;
  532. result.z = this.z - z;
  533. return this;
  534. };
  535. Vector3.prototype.negate = function () {
  536. return new Vector3(-this.x, -this.y, -this.z);
  537. };
  538. Vector3.prototype.scaleInPlace = function (scale) {
  539. this.x *= scale;
  540. this.y *= scale;
  541. this.z *= scale;
  542. return this;
  543. };
  544. Vector3.prototype.scale = function (scale) {
  545. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  546. };
  547. Vector3.prototype.scaleToRef = function (scale, result) {
  548. result.x = this.x * scale;
  549. result.y = this.y * scale;
  550. result.z = this.z * scale;
  551. };
  552. Vector3.prototype.equals = function (otherVector) {
  553. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  554. };
  555. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  556. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  557. 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);
  558. };
  559. Vector3.prototype.equalsToFloats = function (x, y, z) {
  560. return this.x === x && this.y === y && this.z === z;
  561. };
  562. Vector3.prototype.multiplyInPlace = function (otherVector) {
  563. this.x *= otherVector.x;
  564. this.y *= otherVector.y;
  565. this.z *= otherVector.z;
  566. return this;
  567. };
  568. Vector3.prototype.multiply = function (otherVector) {
  569. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  570. };
  571. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  572. result.x = this.x * otherVector.x;
  573. result.y = this.y * otherVector.y;
  574. result.z = this.z * otherVector.z;
  575. return this;
  576. };
  577. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  578. return new Vector3(this.x * x, this.y * y, this.z * z);
  579. };
  580. Vector3.prototype.divide = function (otherVector) {
  581. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  582. };
  583. Vector3.prototype.divideToRef = function (otherVector, result) {
  584. result.x = this.x / otherVector.x;
  585. result.y = this.y / otherVector.y;
  586. result.z = this.z / otherVector.z;
  587. return this;
  588. };
  589. Vector3.prototype.MinimizeInPlace = function (other) {
  590. if (other.x < this.x)
  591. this.x = other.x;
  592. if (other.y < this.y)
  593. this.y = other.y;
  594. if (other.z < this.z)
  595. this.z = other.z;
  596. return this;
  597. };
  598. Vector3.prototype.MaximizeInPlace = function (other) {
  599. if (other.x > this.x)
  600. this.x = other.x;
  601. if (other.y > this.y)
  602. this.y = other.y;
  603. if (other.z > this.z)
  604. this.z = other.z;
  605. return this;
  606. };
  607. // Properties
  608. Vector3.prototype.length = function () {
  609. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  610. };
  611. Vector3.prototype.lengthSquared = function () {
  612. return (this.x * this.x + this.y * this.y + this.z * this.z);
  613. };
  614. // Methods
  615. Vector3.prototype.normalize = function () {
  616. var len = this.length();
  617. if (len === 0 || len === 1.0)
  618. return this;
  619. var num = 1.0 / len;
  620. this.x *= num;
  621. this.y *= num;
  622. this.z *= num;
  623. return this;
  624. };
  625. Vector3.prototype.clone = function () {
  626. return new Vector3(this.x, this.y, this.z);
  627. };
  628. Vector3.prototype.copyFrom = function (source) {
  629. this.x = source.x;
  630. this.y = source.y;
  631. this.z = source.z;
  632. return this;
  633. };
  634. Vector3.prototype.copyFromFloats = function (x, y, z) {
  635. this.x = x;
  636. this.y = y;
  637. this.z = z;
  638. return this;
  639. };
  640. // Statics
  641. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  642. var d0 = Vector3.Dot(vector0, axis) - size;
  643. var d1 = Vector3.Dot(vector1, axis) - size;
  644. var s = d0 / (d0 - d1);
  645. return s;
  646. };
  647. Vector3.FromArray = function (array, offset) {
  648. if (!offset) {
  649. offset = 0;
  650. }
  651. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  652. };
  653. Vector3.FromFloatArray = function (array, offset) {
  654. if (!offset) {
  655. offset = 0;
  656. }
  657. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  658. };
  659. Vector3.FromArrayToRef = function (array, offset, result) {
  660. result.x = array[offset];
  661. result.y = array[offset + 1];
  662. result.z = array[offset + 2];
  663. };
  664. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  665. result.x = array[offset];
  666. result.y = array[offset + 1];
  667. result.z = array[offset + 2];
  668. };
  669. Vector3.FromFloatsToRef = function (x, y, z, result) {
  670. result.x = x;
  671. result.y = y;
  672. result.z = z;
  673. };
  674. Vector3.Zero = function () {
  675. return new Vector3(0, 0, 0);
  676. };
  677. Vector3.Up = function () {
  678. return new Vector3(0, 1.0, 0);
  679. };
  680. Vector3.TransformCoordinates = function (vector, transformation) {
  681. var result = Vector3.Zero();
  682. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  683. return result;
  684. };
  685. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  686. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  687. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  688. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  689. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  690. result.x = x / w;
  691. result.y = y / w;
  692. result.z = z / w;
  693. };
  694. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  695. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  696. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  697. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  698. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  699. result.x = rx / rw;
  700. result.y = ry / rw;
  701. result.z = rz / rw;
  702. };
  703. Vector3.TransformNormal = function (vector, transformation) {
  704. var result = Vector3.Zero();
  705. Vector3.TransformNormalToRef(vector, transformation, result);
  706. return result;
  707. };
  708. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  709. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  710. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  711. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  712. };
  713. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  714. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  715. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  716. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  717. };
  718. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  719. var squared = amount * amount;
  720. var cubed = amount * squared;
  721. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  722. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  723. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  724. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  725. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  726. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  727. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  728. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  729. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Clamp = function (value, min, max) {
  733. var x = value.x;
  734. x = (x > max.x) ? max.x : x;
  735. x = (x < min.x) ? min.x : x;
  736. var y = value.y;
  737. y = (y > max.y) ? max.y : y;
  738. y = (y < min.y) ? min.y : y;
  739. var z = value.z;
  740. z = (z > max.z) ? max.z : z;
  741. z = (z < min.z) ? min.z : z;
  742. return new Vector3(x, y, z);
  743. };
  744. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  745. var squared = amount * amount;
  746. var cubed = amount * squared;
  747. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  748. var part2 = (-2.0 * cubed) + (3.0 * squared);
  749. var part3 = (cubed - (2.0 * squared)) + amount;
  750. var part4 = cubed - squared;
  751. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  752. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  753. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  754. return new Vector3(x, y, z);
  755. };
  756. Vector3.Lerp = function (start, end, amount) {
  757. var x = start.x + ((end.x - start.x) * amount);
  758. var y = start.y + ((end.y - start.y) * amount);
  759. var z = start.z + ((end.z - start.z) * amount);
  760. return new Vector3(x, y, z);
  761. };
  762. Vector3.Dot = function (left, right) {
  763. return (left.x * right.x + left.y * right.y + left.z * right.z);
  764. };
  765. Vector3.Cross = function (left, right) {
  766. var result = Vector3.Zero();
  767. Vector3.CrossToRef(left, right, result);
  768. return result;
  769. };
  770. Vector3.CrossToRef = function (left, right, result) {
  771. result.x = left.y * right.z - left.z * right.y;
  772. result.y = left.z * right.x - left.x * right.z;
  773. result.z = left.x * right.y - left.y * right.x;
  774. };
  775. Vector3.Normalize = function (vector) {
  776. var result = Vector3.Zero();
  777. Vector3.NormalizeToRef(vector, result);
  778. return result;
  779. };
  780. Vector3.NormalizeToRef = function (vector, result) {
  781. result.copyFrom(vector);
  782. result.normalize();
  783. };
  784. Vector3.Project = function (vector, world, transform, viewport) {
  785. var cw = viewport.width;
  786. var ch = viewport.height;
  787. var cx = viewport.x;
  788. var cy = viewport.y;
  789. 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);
  790. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  791. return Vector3.TransformCoordinates(vector, finalMatrix);
  792. };
  793. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  794. var matrix = world.multiply(transform);
  795. matrix.invert();
  796. source.x = source.x / viewportWidth * 2 - 1;
  797. source.y = -(source.y / viewportHeight * 2 - 1);
  798. var vector = Vector3.TransformCoordinates(source, matrix);
  799. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  800. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  801. vector = vector.scale(1.0 / num);
  802. }
  803. return vector;
  804. };
  805. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  806. var matrix = world.multiply(view).multiply(projection);
  807. matrix.invert();
  808. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  809. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  810. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  811. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  812. vector = vector.scale(1.0 / num);
  813. }
  814. return vector;
  815. };
  816. Vector3.Minimize = function (left, right) {
  817. var min = left.clone();
  818. min.MinimizeInPlace(right);
  819. return min;
  820. };
  821. Vector3.Maximize = function (left, right) {
  822. var max = left.clone();
  823. max.MaximizeInPlace(right);
  824. return max;
  825. };
  826. Vector3.Distance = function (value1, value2) {
  827. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  828. };
  829. Vector3.DistanceSquared = function (value1, value2) {
  830. var x = value1.x - value2.x;
  831. var y = value1.y - value2.y;
  832. var z = value1.z - value2.z;
  833. return (x * x) + (y * y) + (z * z);
  834. };
  835. Vector3.Center = function (value1, value2) {
  836. var center = value1.add(value2);
  837. center.scaleInPlace(0.5);
  838. return center;
  839. };
  840. /**
  841. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  843. * to something in order to rotate it from its local system to the given target system.
  844. */
  845. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  846. var rotation = Vector3.Zero();
  847. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  848. return rotation;
  849. };
  850. /**
  851. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  852. */
  853. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  854. var u = Vector3.Normalize(axis1);
  855. var w = Vector3.Normalize(axis3);
  856. // world axis
  857. var X = Axis.X;
  858. var Y = Axis.Y;
  859. // equation unknowns and vars
  860. var yaw = 0.0;
  861. var pitch = 0.0;
  862. var roll = 0.0;
  863. var x = 0.0;
  864. var y = 0.0;
  865. var z = 0.0;
  866. var t = 0.0;
  867. var sign = -1.0;
  868. var nbRevert = 0;
  869. var cross;
  870. var dot = 0.0;
  871. // step 1 : rotation around w
  872. // Rv3(u) = u1, and u1 belongs to plane xOz
  873. // Rv3(w) = w1 = w invariant
  874. var u1;
  875. var v1;
  876. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  877. z = 1.0;
  878. }
  879. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  880. x = 1.0;
  881. }
  882. else {
  883. t = w.z / w.x;
  884. x = -t * Math.sqrt(1 / (1 + t * t));
  885. z = Math.sqrt(1 / (1 + t * t));
  886. }
  887. u1 = new Vector3(x, y, z);
  888. u1.normalize();
  889. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  890. v1.normalize();
  891. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  892. cross.normalize();
  893. if (Vector3.Dot(w, cross) < 0) {
  894. sign = 1.0;
  895. }
  896. dot = Vector3.Dot(u, u1);
  897. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  898. roll = Math.acos(dot) * sign;
  899. if (Vector3.Dot(u1, X) < 0) {
  900. roll = Math.PI + roll;
  901. u1 = u1.scaleInPlace(-1);
  902. v1 = v1.scaleInPlace(-1);
  903. nbRevert++;
  904. }
  905. // step 2 : rotate around u1
  906. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  907. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  908. var w2;
  909. var v2;
  910. x = 0.0;
  911. y = 0.0;
  912. z = 0.0;
  913. sign = -1;
  914. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  915. x = 1.0;
  916. }
  917. else {
  918. t = u1.z / u1.x;
  919. x = -t * Math.sqrt(1 / (1 + t * t));
  920. z = Math.sqrt(1 / (1 + t * t));
  921. }
  922. w2 = new Vector3(x, y, z);
  923. w2.normalize();
  924. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  925. v2.normalize();
  926. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  927. cross.normalize();
  928. if (Vector3.Dot(u1, cross) < 0) {
  929. sign = 1.0;
  930. }
  931. dot = Vector3.Dot(w, w2);
  932. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  933. pitch = Math.acos(dot) * sign;
  934. if (Vector3.Dot(v2, Y) < 0) {
  935. pitch = Math.PI + pitch;
  936. v2 = v2.scaleInPlace(-1);
  937. w2 = w2.scaleInPlace(-1);
  938. nbRevert++;
  939. }
  940. // step 3 : rotate around v2
  941. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  942. sign = -1;
  943. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(cross, Y) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u1, X);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  951. if (dot < 0 && nbRevert < 2) {
  952. yaw = Math.PI + yaw;
  953. }
  954. ref.x = pitch;
  955. ref.y = yaw;
  956. ref.z = roll;
  957. };
  958. return Vector3;
  959. })();
  960. BABYLON.Vector3 = Vector3;
  961. //Vector4 class created for EulerAngle class conversion to Quaternion
  962. var Vector4 = (function () {
  963. function Vector4(x, y, z, w) {
  964. this.x = x;
  965. this.y = y;
  966. this.z = z;
  967. this.w = w;
  968. }
  969. Vector4.prototype.toString = function () {
  970. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  971. };
  972. // Operators
  973. Vector4.prototype.asArray = function () {
  974. var result = [];
  975. this.toArray(result, 0);
  976. return result;
  977. };
  978. Vector4.prototype.toArray = function (array, index) {
  979. if (index === undefined) {
  980. index = 0;
  981. }
  982. array[index] = this.x;
  983. array[index + 1] = this.y;
  984. array[index + 2] = this.z;
  985. array[index + 3] = this.w;
  986. return this;
  987. };
  988. Vector4.prototype.addInPlace = function (otherVector) {
  989. this.x += otherVector.x;
  990. this.y += otherVector.y;
  991. this.z += otherVector.z;
  992. this.w += otherVector.w;
  993. return this;
  994. };
  995. Vector4.prototype.add = function (otherVector) {
  996. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  997. };
  998. Vector4.prototype.addToRef = function (otherVector, result) {
  999. result.x = this.x + otherVector.x;
  1000. result.y = this.y + otherVector.y;
  1001. result.z = this.z + otherVector.z;
  1002. result.w = this.w + otherVector.w;
  1003. return this;
  1004. };
  1005. Vector4.prototype.subtractInPlace = function (otherVector) {
  1006. this.x -= otherVector.x;
  1007. this.y -= otherVector.y;
  1008. this.z -= otherVector.z;
  1009. this.w -= otherVector.w;
  1010. return this;
  1011. };
  1012. Vector4.prototype.subtract = function (otherVector) {
  1013. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1014. };
  1015. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1016. result.x = this.x - otherVector.x;
  1017. result.y = this.y - otherVector.y;
  1018. result.z = this.z - otherVector.z;
  1019. result.w = this.w - otherVector.w;
  1020. return this;
  1021. };
  1022. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1023. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1024. };
  1025. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1026. result.x = this.x - x;
  1027. result.y = this.y - y;
  1028. result.z = this.z - z;
  1029. result.w = this.w - w;
  1030. return this;
  1031. };
  1032. Vector4.prototype.negate = function () {
  1033. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1034. };
  1035. Vector4.prototype.scaleInPlace = function (scale) {
  1036. this.x *= scale;
  1037. this.y *= scale;
  1038. this.z *= scale;
  1039. this.w *= scale;
  1040. return this;
  1041. };
  1042. Vector4.prototype.scale = function (scale) {
  1043. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1044. };
  1045. Vector4.prototype.scaleToRef = function (scale, result) {
  1046. result.x = this.x * scale;
  1047. result.y = this.y * scale;
  1048. result.z = this.z * scale;
  1049. result.w = this.w * scale;
  1050. };
  1051. Vector4.prototype.equals = function (otherVector) {
  1052. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1053. };
  1054. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1055. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1056. return otherVector
  1057. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1058. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1059. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1060. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1061. };
  1062. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1063. return this.x === x && this.y === y && this.z === z && this.w === w;
  1064. };
  1065. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1066. this.x *= otherVector.x;
  1067. this.y *= otherVector.y;
  1068. this.z *= otherVector.z;
  1069. this.w *= otherVector.w;
  1070. return this;
  1071. };
  1072. Vector4.prototype.multiply = function (otherVector) {
  1073. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1074. };
  1075. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1076. result.x = this.x * otherVector.x;
  1077. result.y = this.y * otherVector.y;
  1078. result.z = this.z * otherVector.z;
  1079. result.w = this.w * otherVector.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1083. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1084. };
  1085. Vector4.prototype.divide = function (otherVector) {
  1086. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1087. };
  1088. Vector4.prototype.divideToRef = function (otherVector, result) {
  1089. result.x = this.x / otherVector.x;
  1090. result.y = this.y / otherVector.y;
  1091. result.z = this.z / otherVector.z;
  1092. result.w = this.w / otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.MinimizeInPlace = function (other) {
  1096. if (other.x < this.x)
  1097. this.x = other.x;
  1098. if (other.y < this.y)
  1099. this.y = other.y;
  1100. if (other.z < this.z)
  1101. this.z = other.z;
  1102. if (other.w < this.w)
  1103. this.w = other.w;
  1104. return this;
  1105. };
  1106. Vector4.prototype.MaximizeInPlace = function (other) {
  1107. if (other.x > this.x)
  1108. this.x = other.x;
  1109. if (other.y > this.y)
  1110. this.y = other.y;
  1111. if (other.z > this.z)
  1112. this.z = other.z;
  1113. if (other.w > this.w)
  1114. this.w = other.w;
  1115. return this;
  1116. };
  1117. // Properties
  1118. Vector4.prototype.length = function () {
  1119. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1120. };
  1121. Vector4.prototype.lengthSquared = function () {
  1122. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1123. };
  1124. // Methods
  1125. Vector4.prototype.normalize = function () {
  1126. var len = this.length();
  1127. if (len === 0)
  1128. return this;
  1129. var num = 1.0 / len;
  1130. this.x *= num;
  1131. this.y *= num;
  1132. this.z *= num;
  1133. this.w *= num;
  1134. return this;
  1135. };
  1136. Vector4.prototype.clone = function () {
  1137. return new Vector4(this.x, this.y, this.z, this.w);
  1138. };
  1139. Vector4.prototype.copyFrom = function (source) {
  1140. this.x = source.x;
  1141. this.y = source.y;
  1142. this.z = source.z;
  1143. this.w = source.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1147. this.x = x;
  1148. this.y = y;
  1149. this.z = z;
  1150. this.w = w;
  1151. return this;
  1152. };
  1153. // Statics
  1154. Vector4.FromArray = function (array, offset) {
  1155. if (!offset) {
  1156. offset = 0;
  1157. }
  1158. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1159. };
  1160. Vector4.FromArrayToRef = function (array, offset, result) {
  1161. result.x = array[offset];
  1162. result.y = array[offset + 1];
  1163. result.z = array[offset + 2];
  1164. result.w = array[offset + 3];
  1165. };
  1166. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1167. result.x = array[offset];
  1168. result.y = array[offset + 1];
  1169. result.z = array[offset + 2];
  1170. result.w = array[offset + 3];
  1171. };
  1172. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1173. result.x = x;
  1174. result.y = y;
  1175. result.z = z;
  1176. result.w = w;
  1177. };
  1178. Vector4.Zero = function () {
  1179. return new Vector4(0, 0, 0, 0);
  1180. };
  1181. Vector4.Normalize = function (vector) {
  1182. var result = Vector4.Zero();
  1183. Vector4.NormalizeToRef(vector, result);
  1184. return result;
  1185. };
  1186. Vector4.NormalizeToRef = function (vector, result) {
  1187. result.copyFrom(vector);
  1188. result.normalize();
  1189. };
  1190. Vector4.Minimize = function (left, right) {
  1191. var min = left.clone();
  1192. min.MinimizeInPlace(right);
  1193. return min;
  1194. };
  1195. Vector4.Maximize = function (left, right) {
  1196. var max = left.clone();
  1197. max.MaximizeInPlace(right);
  1198. return max;
  1199. };
  1200. Vector4.Distance = function (value1, value2) {
  1201. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1202. };
  1203. Vector4.DistanceSquared = function (value1, value2) {
  1204. var x = value1.x - value2.x;
  1205. var y = value1.y - value2.y;
  1206. var z = value1.z - value2.z;
  1207. var w = value1.w - value2.w;
  1208. return (x * x) + (y * y) + (z * z) + (w * w);
  1209. };
  1210. Vector4.Center = function (value1, value2) {
  1211. var center = value1.add(value2);
  1212. center.scaleInPlace(0.5);
  1213. return center;
  1214. };
  1215. return Vector4;
  1216. })();
  1217. BABYLON.Vector4 = Vector4;
  1218. var Quaternion = (function () {
  1219. function Quaternion(x, y, z, w) {
  1220. if (x === void 0) { x = 0; }
  1221. if (y === void 0) { y = 0; }
  1222. if (z === void 0) { z = 0; }
  1223. if (w === void 0) { w = 1; }
  1224. this.x = x;
  1225. this.y = y;
  1226. this.z = z;
  1227. this.w = w;
  1228. }
  1229. Quaternion.prototype.toString = function () {
  1230. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1231. };
  1232. Quaternion.prototype.asArray = function () {
  1233. return [this.x, this.y, this.z, this.w];
  1234. };
  1235. Quaternion.prototype.equals = function (otherQuaternion) {
  1236. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1237. };
  1238. Quaternion.prototype.clone = function () {
  1239. return new Quaternion(this.x, this.y, this.z, this.w);
  1240. };
  1241. Quaternion.prototype.copyFrom = function (other) {
  1242. this.x = other.x;
  1243. this.y = other.y;
  1244. this.z = other.z;
  1245. this.w = other.w;
  1246. return this;
  1247. };
  1248. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1249. this.x = x;
  1250. this.y = y;
  1251. this.z = z;
  1252. this.w = w;
  1253. return this;
  1254. };
  1255. Quaternion.prototype.add = function (other) {
  1256. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1257. };
  1258. Quaternion.prototype.subtract = function (other) {
  1259. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1260. };
  1261. Quaternion.prototype.scale = function (value) {
  1262. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1263. };
  1264. Quaternion.prototype.multiply = function (q1) {
  1265. var result = new Quaternion(0, 0, 0, 1.0);
  1266. this.multiplyToRef(q1, result);
  1267. return result;
  1268. };
  1269. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1270. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1271. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1272. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1273. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1274. result.copyFromFloats(x, y, z, w);
  1275. return this;
  1276. };
  1277. Quaternion.prototype.multiplyInPlace = function (q1) {
  1278. this.multiplyToRef(q1, this);
  1279. return this;
  1280. };
  1281. Quaternion.prototype.length = function () {
  1282. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1283. };
  1284. Quaternion.prototype.normalize = function () {
  1285. var length = 1.0 / this.length();
  1286. this.x *= length;
  1287. this.y *= length;
  1288. this.z *= length;
  1289. this.w *= length;
  1290. return this;
  1291. };
  1292. Quaternion.prototype.toEulerAngles = function () {
  1293. var result = Vector3.Zero();
  1294. this.toEulerAnglesToRef(result);
  1295. return result;
  1296. };
  1297. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1298. //result is an EulerAngles in the in the z-x-z convention
  1299. var qx = this.x;
  1300. var qy = this.y;
  1301. var qz = this.z;
  1302. var qw = this.w;
  1303. var qxy = qx * qy;
  1304. var qxz = qx * qz;
  1305. var qwy = qw * qy;
  1306. var qwz = qw * qz;
  1307. var qwx = qw * qx;
  1308. var qyz = qy * qz;
  1309. var sqx = qx * qx;
  1310. var sqy = qy * qy;
  1311. var determinant = sqx + sqy;
  1312. if (determinant !== 0.000 && determinant !== 1.000) {
  1313. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1314. result.y = Math.acos(1 - 2 * determinant);
  1315. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1316. }
  1317. else {
  1318. if (determinant === 0.0) {
  1319. result.x = 0.0;
  1320. result.y = 0.0;
  1321. 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)
  1322. }
  1323. else {
  1324. 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)
  1325. result.y = Math.PI;
  1326. result.z = 0.0;
  1327. }
  1328. }
  1329. return this;
  1330. };
  1331. Quaternion.prototype.toRotationMatrix = function (result) {
  1332. var xx = this.x * this.x;
  1333. var yy = this.y * this.y;
  1334. var zz = this.z * this.z;
  1335. var xy = this.x * this.y;
  1336. var zw = this.z * this.w;
  1337. var zx = this.z * this.x;
  1338. var yw = this.y * this.w;
  1339. var yz = this.y * this.z;
  1340. var xw = this.x * this.w;
  1341. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1342. result.m[1] = 2.0 * (xy + zw);
  1343. result.m[2] = 2.0 * (zx - yw);
  1344. result.m[3] = 0;
  1345. result.m[4] = 2.0 * (xy - zw);
  1346. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1347. result.m[6] = 2.0 * (yz + xw);
  1348. result.m[7] = 0;
  1349. result.m[8] = 2.0 * (zx + yw);
  1350. result.m[9] = 2.0 * (yz - xw);
  1351. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1352. result.m[11] = 0;
  1353. result.m[12] = 0;
  1354. result.m[13] = 0;
  1355. result.m[14] = 0;
  1356. result.m[15] = 1.0;
  1357. return this;
  1358. };
  1359. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1360. Quaternion.FromRotationMatrixToRef(matrix, this);
  1361. return this;
  1362. };
  1363. // Statics
  1364. Quaternion.FromRotationMatrix = function (matrix) {
  1365. var result = new Quaternion();
  1366. Quaternion.FromRotationMatrixToRef(matrix, result);
  1367. return result;
  1368. };
  1369. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1370. var data = matrix.m;
  1371. var m11 = data[0], m12 = data[4], m13 = data[8];
  1372. var m21 = data[1], m22 = data[5], m23 = data[9];
  1373. var m31 = data[2], m32 = data[6], m33 = data[10];
  1374. var trace = m11 + m22 + m33;
  1375. var s;
  1376. if (trace > 0) {
  1377. s = 0.5 / Math.sqrt(trace + 1.0);
  1378. result.w = 0.25 / s;
  1379. result.x = (m32 - m23) * s;
  1380. result.y = (m13 - m31) * s;
  1381. result.z = (m21 - m12) * s;
  1382. }
  1383. else if (m11 > m22 && m11 > m33) {
  1384. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1385. result.w = (m32 - m23) / s;
  1386. result.x = 0.25 * s;
  1387. result.y = (m12 + m21) / s;
  1388. result.z = (m13 + m31) / s;
  1389. }
  1390. else if (m22 > m33) {
  1391. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1392. result.w = (m13 - m31) / s;
  1393. result.x = (m12 + m21) / s;
  1394. result.y = 0.25 * s;
  1395. result.z = (m23 + m32) / s;
  1396. }
  1397. else {
  1398. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1399. result.w = (m21 - m12) / s;
  1400. result.x = (m13 + m31) / s;
  1401. result.y = (m23 + m32) / s;
  1402. result.z = 0.25 * s;
  1403. }
  1404. };
  1405. Quaternion.Inverse = function (q) {
  1406. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1407. };
  1408. Quaternion.Identity = function () {
  1409. return new Quaternion(0, 0, 0, 1);
  1410. };
  1411. Quaternion.RotationAxis = function (axis, angle) {
  1412. var result = new Quaternion();
  1413. var sin = Math.sin(angle / 2);
  1414. axis.normalize();
  1415. result.w = Math.cos(angle / 2);
  1416. result.x = axis.x * sin;
  1417. result.y = axis.y * sin;
  1418. result.z = axis.z * sin;
  1419. return result;
  1420. };
  1421. Quaternion.FromArray = function (array, offset) {
  1422. if (!offset) {
  1423. offset = 0;
  1424. }
  1425. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1426. };
  1427. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1428. var result = new Quaternion();
  1429. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1430. return result;
  1431. };
  1432. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1433. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1434. var halfRoll = roll * 0.5;
  1435. var halfPitch = pitch * 0.5;
  1436. var halfYaw = yaw * 0.5;
  1437. var sinRoll = Math.sin(halfRoll);
  1438. var cosRoll = Math.cos(halfRoll);
  1439. var sinPitch = Math.sin(halfPitch);
  1440. var cosPitch = Math.cos(halfPitch);
  1441. var sinYaw = Math.sin(halfYaw);
  1442. var cosYaw = Math.cos(halfYaw);
  1443. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1444. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1445. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1446. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1447. };
  1448. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1449. var result = new Quaternion();
  1450. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1451. return result;
  1452. };
  1453. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1454. // Produces a quaternion from Euler angles in the z-x-z orientation
  1455. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1456. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1457. var halfBeta = beta * 0.5;
  1458. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1459. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1460. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1461. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1462. };
  1463. Quaternion.Slerp = function (left, right, amount) {
  1464. var num2;
  1465. var num3;
  1466. var num = amount;
  1467. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1468. var flag = false;
  1469. if (num4 < 0) {
  1470. flag = true;
  1471. num4 = -num4;
  1472. }
  1473. if (num4 > 0.999999) {
  1474. num3 = 1 - num;
  1475. num2 = flag ? -num : num;
  1476. }
  1477. else {
  1478. var num5 = Math.acos(num4);
  1479. var num6 = (1.0 / Math.sin(num5));
  1480. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1481. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1482. }
  1483. 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));
  1484. };
  1485. return Quaternion;
  1486. })();
  1487. BABYLON.Quaternion = Quaternion;
  1488. var Matrix = (function () {
  1489. function Matrix() {
  1490. this.m = new Float32Array(16);
  1491. }
  1492. // Properties
  1493. Matrix.prototype.isIdentity = function () {
  1494. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1495. return false;
  1496. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1497. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1498. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1499. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1500. return false;
  1501. return true;
  1502. };
  1503. Matrix.prototype.determinant = function () {
  1504. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1505. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1506. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1507. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1508. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1509. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1510. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1511. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1512. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1513. };
  1514. // Methods
  1515. Matrix.prototype.toArray = function () {
  1516. return this.m;
  1517. };
  1518. Matrix.prototype.asArray = function () {
  1519. return this.toArray();
  1520. };
  1521. Matrix.prototype.invert = function () {
  1522. this.invertToRef(this);
  1523. return this;
  1524. };
  1525. Matrix.prototype.reset = function () {
  1526. for (var index = 0; index < 16; index++) {
  1527. this.m[index] = 0;
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.add = function (other) {
  1532. var result = new Matrix();
  1533. this.addToRef(other, result);
  1534. return result;
  1535. };
  1536. Matrix.prototype.addToRef = function (other, result) {
  1537. for (var index = 0; index < 16; index++) {
  1538. result.m[index] = this.m[index] + other.m[index];
  1539. }
  1540. return this;
  1541. };
  1542. Matrix.prototype.addToSelf = function (other) {
  1543. for (var index = 0; index < 16; index++) {
  1544. this.m[index] += other.m[index];
  1545. }
  1546. return this;
  1547. };
  1548. Matrix.prototype.invertToRef = function (other) {
  1549. var l1 = this.m[0];
  1550. var l2 = this.m[1];
  1551. var l3 = this.m[2];
  1552. var l4 = this.m[3];
  1553. var l5 = this.m[4];
  1554. var l6 = this.m[5];
  1555. var l7 = this.m[6];
  1556. var l8 = this.m[7];
  1557. var l9 = this.m[8];
  1558. var l10 = this.m[9];
  1559. var l11 = this.m[10];
  1560. var l12 = this.m[11];
  1561. var l13 = this.m[12];
  1562. var l14 = this.m[13];
  1563. var l15 = this.m[14];
  1564. var l16 = this.m[15];
  1565. var l17 = (l11 * l16) - (l12 * l15);
  1566. var l18 = (l10 * l16) - (l12 * l14);
  1567. var l19 = (l10 * l15) - (l11 * l14);
  1568. var l20 = (l9 * l16) - (l12 * l13);
  1569. var l21 = (l9 * l15) - (l11 * l13);
  1570. var l22 = (l9 * l14) - (l10 * l13);
  1571. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1572. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1573. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1574. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1575. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1576. var l28 = (l7 * l16) - (l8 * l15);
  1577. var l29 = (l6 * l16) - (l8 * l14);
  1578. var l30 = (l6 * l15) - (l7 * l14);
  1579. var l31 = (l5 * l16) - (l8 * l13);
  1580. var l32 = (l5 * l15) - (l7 * l13);
  1581. var l33 = (l5 * l14) - (l6 * l13);
  1582. var l34 = (l7 * l12) - (l8 * l11);
  1583. var l35 = (l6 * l12) - (l8 * l10);
  1584. var l36 = (l6 * l11) - (l7 * l10);
  1585. var l37 = (l5 * l12) - (l8 * l9);
  1586. var l38 = (l5 * l11) - (l7 * l9);
  1587. var l39 = (l5 * l10) - (l6 * l9);
  1588. other.m[0] = l23 * l27;
  1589. other.m[4] = l24 * l27;
  1590. other.m[8] = l25 * l27;
  1591. other.m[12] = l26 * l27;
  1592. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1593. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1594. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1595. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1596. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1597. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1598. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1599. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1600. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1601. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1602. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1603. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1604. return this;
  1605. };
  1606. Matrix.prototype.setTranslation = function (vector3) {
  1607. this.m[12] = vector3.x;
  1608. this.m[13] = vector3.y;
  1609. this.m[14] = vector3.z;
  1610. return this;
  1611. };
  1612. Matrix.prototype.multiply = function (other) {
  1613. var result = new Matrix();
  1614. this.multiplyToRef(other, result);
  1615. return result;
  1616. };
  1617. Matrix.prototype.copyFrom = function (other) {
  1618. for (var index = 0; index < 16; index++) {
  1619. this.m[index] = other.m[index];
  1620. }
  1621. return this;
  1622. };
  1623. Matrix.prototype.copyToArray = function (array, offset) {
  1624. if (offset === void 0) { offset = 0; }
  1625. for (var index = 0; index < 16; index++) {
  1626. array[offset + index] = this.m[index];
  1627. }
  1628. return this;
  1629. };
  1630. Matrix.prototype.multiplyToRef = function (other, result) {
  1631. this.multiplyToArray(other, result.m, 0);
  1632. return this;
  1633. };
  1634. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1635. var tm0 = this.m[0];
  1636. var tm1 = this.m[1];
  1637. var tm2 = this.m[2];
  1638. var tm3 = this.m[3];
  1639. var tm4 = this.m[4];
  1640. var tm5 = this.m[5];
  1641. var tm6 = this.m[6];
  1642. var tm7 = this.m[7];
  1643. var tm8 = this.m[8];
  1644. var tm9 = this.m[9];
  1645. var tm10 = this.m[10];
  1646. var tm11 = this.m[11];
  1647. var tm12 = this.m[12];
  1648. var tm13 = this.m[13];
  1649. var tm14 = this.m[14];
  1650. var tm15 = this.m[15];
  1651. var om0 = other.m[0];
  1652. var om1 = other.m[1];
  1653. var om2 = other.m[2];
  1654. var om3 = other.m[3];
  1655. var om4 = other.m[4];
  1656. var om5 = other.m[5];
  1657. var om6 = other.m[6];
  1658. var om7 = other.m[7];
  1659. var om8 = other.m[8];
  1660. var om9 = other.m[9];
  1661. var om10 = other.m[10];
  1662. var om11 = other.m[11];
  1663. var om12 = other.m[12];
  1664. var om13 = other.m[13];
  1665. var om14 = other.m[14];
  1666. var om15 = other.m[15];
  1667. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1668. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1669. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1670. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1671. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1672. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1673. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1674. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1675. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1676. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1677. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1678. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1679. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1680. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1681. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1682. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1683. return this;
  1684. };
  1685. Matrix.prototype.equals = function (value) {
  1686. return value &&
  1687. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1688. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1689. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1690. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1691. };
  1692. Matrix.prototype.clone = function () {
  1693. 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]);
  1694. };
  1695. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1696. translation.x = this.m[12];
  1697. translation.y = this.m[13];
  1698. translation.z = this.m[14];
  1699. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1700. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1701. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1702. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1703. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1704. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1705. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1706. rotation.x = 0;
  1707. rotation.y = 0;
  1708. rotation.z = 0;
  1709. rotation.w = 1;
  1710. return false;
  1711. }
  1712. 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);
  1713. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1714. return true;
  1715. };
  1716. // Statics
  1717. Matrix.FromArray = function (array, offset) {
  1718. var result = new Matrix();
  1719. if (!offset) {
  1720. offset = 0;
  1721. }
  1722. Matrix.FromArrayToRef(array, offset, result);
  1723. return result;
  1724. };
  1725. Matrix.FromArrayToRef = function (array, offset, result) {
  1726. for (var index = 0; index < 16; index++) {
  1727. result.m[index] = array[index + offset];
  1728. }
  1729. };
  1730. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1731. for (var index = 0; index < 16; index++) {
  1732. result.m[index] = array[index + offset] * scale;
  1733. }
  1734. };
  1735. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1736. result.m[0] = initialM11;
  1737. result.m[1] = initialM12;
  1738. result.m[2] = initialM13;
  1739. result.m[3] = initialM14;
  1740. result.m[4] = initialM21;
  1741. result.m[5] = initialM22;
  1742. result.m[6] = initialM23;
  1743. result.m[7] = initialM24;
  1744. result.m[8] = initialM31;
  1745. result.m[9] = initialM32;
  1746. result.m[10] = initialM33;
  1747. result.m[11] = initialM34;
  1748. result.m[12] = initialM41;
  1749. result.m[13] = initialM42;
  1750. result.m[14] = initialM43;
  1751. result.m[15] = initialM44;
  1752. };
  1753. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1754. var result = new Matrix();
  1755. result.m[0] = initialM11;
  1756. result.m[1] = initialM12;
  1757. result.m[2] = initialM13;
  1758. result.m[3] = initialM14;
  1759. result.m[4] = initialM21;
  1760. result.m[5] = initialM22;
  1761. result.m[6] = initialM23;
  1762. result.m[7] = initialM24;
  1763. result.m[8] = initialM31;
  1764. result.m[9] = initialM32;
  1765. result.m[10] = initialM33;
  1766. result.m[11] = initialM34;
  1767. result.m[12] = initialM41;
  1768. result.m[13] = initialM42;
  1769. result.m[14] = initialM43;
  1770. result.m[15] = initialM44;
  1771. return result;
  1772. };
  1773. Matrix.Compose = function (scale, rotation, translation) {
  1774. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1775. var rotationMatrix = Matrix.Identity();
  1776. rotation.toRotationMatrix(rotationMatrix);
  1777. result = result.multiply(rotationMatrix);
  1778. result.setTranslation(translation);
  1779. return result;
  1780. };
  1781. Matrix.Identity = function () {
  1782. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1783. };
  1784. Matrix.IdentityToRef = function (result) {
  1785. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1786. };
  1787. Matrix.Zero = function () {
  1788. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1789. };
  1790. Matrix.RotationX = function (angle) {
  1791. var result = new Matrix();
  1792. Matrix.RotationXToRef(angle, result);
  1793. return result;
  1794. };
  1795. Matrix.Invert = function (source) {
  1796. var result = new Matrix();
  1797. source.invertToRef(result);
  1798. return result;
  1799. };
  1800. Matrix.RotationXToRef = function (angle, result) {
  1801. var s = Math.sin(angle);
  1802. var c = Math.cos(angle);
  1803. result.m[0] = 1.0;
  1804. result.m[15] = 1.0;
  1805. result.m[5] = c;
  1806. result.m[10] = c;
  1807. result.m[9] = -s;
  1808. result.m[6] = s;
  1809. result.m[1] = 0;
  1810. result.m[2] = 0;
  1811. result.m[3] = 0;
  1812. result.m[4] = 0;
  1813. result.m[7] = 0;
  1814. result.m[8] = 0;
  1815. result.m[11] = 0;
  1816. result.m[12] = 0;
  1817. result.m[13] = 0;
  1818. result.m[14] = 0;
  1819. };
  1820. Matrix.RotationY = function (angle) {
  1821. var result = new Matrix();
  1822. Matrix.RotationYToRef(angle, result);
  1823. return result;
  1824. };
  1825. Matrix.RotationYToRef = function (angle, result) {
  1826. var s = Math.sin(angle);
  1827. var c = Math.cos(angle);
  1828. result.m[5] = 1.0;
  1829. result.m[15] = 1.0;
  1830. result.m[0] = c;
  1831. result.m[2] = -s;
  1832. result.m[8] = s;
  1833. result.m[10] = c;
  1834. result.m[1] = 0;
  1835. result.m[3] = 0;
  1836. result.m[4] = 0;
  1837. result.m[6] = 0;
  1838. result.m[7] = 0;
  1839. result.m[9] = 0;
  1840. result.m[11] = 0;
  1841. result.m[12] = 0;
  1842. result.m[13] = 0;
  1843. result.m[14] = 0;
  1844. };
  1845. Matrix.RotationZ = function (angle) {
  1846. var result = new Matrix();
  1847. Matrix.RotationZToRef(angle, result);
  1848. return result;
  1849. };
  1850. Matrix.RotationZToRef = function (angle, result) {
  1851. var s = Math.sin(angle);
  1852. var c = Math.cos(angle);
  1853. result.m[10] = 1.0;
  1854. result.m[15] = 1.0;
  1855. result.m[0] = c;
  1856. result.m[1] = s;
  1857. result.m[4] = -s;
  1858. result.m[5] = c;
  1859. result.m[2] = 0;
  1860. result.m[3] = 0;
  1861. result.m[6] = 0;
  1862. result.m[7] = 0;
  1863. result.m[8] = 0;
  1864. result.m[9] = 0;
  1865. result.m[11] = 0;
  1866. result.m[12] = 0;
  1867. result.m[13] = 0;
  1868. result.m[14] = 0;
  1869. };
  1870. Matrix.RotationAxis = function (axis, angle) {
  1871. var result = Matrix.Zero();
  1872. Matrix.RotationAxisToRef(axis, angle, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1876. var s = Math.sin(-angle);
  1877. var c = Math.cos(-angle);
  1878. var c1 = 1 - c;
  1879. axis.normalize();
  1880. result.m[0] = (axis.x * axis.x) * c1 + c;
  1881. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1882. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1883. result.m[3] = 0.0;
  1884. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1885. result.m[5] = (axis.y * axis.y) * c1 + c;
  1886. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1887. result.m[7] = 0.0;
  1888. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1889. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1890. result.m[10] = (axis.z * axis.z) * c1 + c;
  1891. result.m[11] = 0.0;
  1892. result.m[15] = 1.0;
  1893. };
  1894. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1895. var result = new Matrix();
  1896. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1897. return result;
  1898. };
  1899. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1900. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1901. this._tempQuaternion.toRotationMatrix(result);
  1902. };
  1903. Matrix.Scaling = function (x, y, z) {
  1904. var result = Matrix.Zero();
  1905. Matrix.ScalingToRef(x, y, z, result);
  1906. return result;
  1907. };
  1908. Matrix.ScalingToRef = function (x, y, z, result) {
  1909. result.m[0] = x;
  1910. result.m[1] = 0;
  1911. result.m[2] = 0;
  1912. result.m[3] = 0;
  1913. result.m[4] = 0;
  1914. result.m[5] = y;
  1915. result.m[6] = 0;
  1916. result.m[7] = 0;
  1917. result.m[8] = 0;
  1918. result.m[9] = 0;
  1919. result.m[10] = z;
  1920. result.m[11] = 0;
  1921. result.m[12] = 0;
  1922. result.m[13] = 0;
  1923. result.m[14] = 0;
  1924. result.m[15] = 1.0;
  1925. };
  1926. Matrix.Translation = function (x, y, z) {
  1927. var result = Matrix.Identity();
  1928. Matrix.TranslationToRef(x, y, z, result);
  1929. return result;
  1930. };
  1931. Matrix.TranslationToRef = function (x, y, z, result) {
  1932. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1933. };
  1934. Matrix.LookAtLH = function (eye, target, up) {
  1935. var result = Matrix.Zero();
  1936. Matrix.LookAtLHToRef(eye, target, up, result);
  1937. return result;
  1938. };
  1939. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1940. // Z axis
  1941. target.subtractToRef(eye, this._zAxis);
  1942. this._zAxis.normalize();
  1943. // X axis
  1944. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1945. if (this._xAxis.lengthSquared() === 0) {
  1946. this._xAxis.x = 1.0;
  1947. }
  1948. else {
  1949. this._xAxis.normalize();
  1950. }
  1951. // Y axis
  1952. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1953. this._yAxis.normalize();
  1954. // Eye angles
  1955. var ex = -Vector3.Dot(this._xAxis, eye);
  1956. var ey = -Vector3.Dot(this._yAxis, eye);
  1957. var ez = -Vector3.Dot(this._zAxis, eye);
  1958. 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);
  1959. };
  1960. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1961. var matrix = Matrix.Zero();
  1962. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1963. return matrix;
  1964. };
  1965. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1966. var hw = 2.0 / width;
  1967. var hh = 2.0 / height;
  1968. var id = 1.0 / (zfar - znear);
  1969. var nid = znear / (znear - zfar);
  1970. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1971. };
  1972. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1973. var matrix = Matrix.Zero();
  1974. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1975. return matrix;
  1976. };
  1977. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1978. result.m[0] = 2.0 / (right - left);
  1979. result.m[1] = result.m[2] = result.m[3] = 0;
  1980. result.m[5] = 2.0 / (top - bottom);
  1981. result.m[4] = result.m[6] = result.m[7] = 0;
  1982. result.m[10] = -1.0 / (znear - zfar);
  1983. result.m[8] = result.m[9] = result.m[11] = 0;
  1984. result.m[12] = (left + right) / (left - right);
  1985. result.m[13] = (top + bottom) / (bottom - top);
  1986. result.m[14] = znear / (znear - zfar);
  1987. result.m[15] = 1.0;
  1988. };
  1989. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. matrix.m[0] = (2.0 * znear) / width;
  1992. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1993. matrix.m[5] = (2.0 * znear) / height;
  1994. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1995. matrix.m[10] = -zfar / (znear - zfar);
  1996. matrix.m[8] = matrix.m[9] = 0.0;
  1997. matrix.m[11] = 1.0;
  1998. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1999. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2000. return matrix;
  2001. };
  2002. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2003. var matrix = Matrix.Zero();
  2004. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2005. return matrix;
  2006. };
  2007. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2008. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2009. var tan = 1.0 / (Math.tan(fov * 0.5));
  2010. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2011. if (v_fixed) {
  2012. result.m[0] = tan / aspect;
  2013. }
  2014. else {
  2015. result.m[0] = tan;
  2016. }
  2017. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2018. if (v_fixed) {
  2019. result.m[5] = tan;
  2020. }
  2021. else {
  2022. result.m[5] = tan * aspect;
  2023. }
  2024. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2025. result.m[8] = result.m[9] = 0.0;
  2026. result.m[10] = -zfar / (znear - zfar);
  2027. result.m[11] = 1.0;
  2028. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2029. result.m[14] = (znear * zfar) / (znear - zfar);
  2030. };
  2031. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2032. var cw = viewport.width;
  2033. var ch = viewport.height;
  2034. var cx = viewport.x;
  2035. var cy = viewport.y;
  2036. 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);
  2037. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2038. };
  2039. Matrix.GetAsMatrix2x2 = function (matrix) {
  2040. return new Float32Array([
  2041. matrix.m[0], matrix.m[1],
  2042. matrix.m[4], matrix.m[5]
  2043. ]);
  2044. };
  2045. Matrix.GetAsMatrix3x3 = function (matrix) {
  2046. return new Float32Array([
  2047. matrix.m[0], matrix.m[1], matrix.m[2],
  2048. matrix.m[4], matrix.m[5], matrix.m[6],
  2049. matrix.m[8], matrix.m[9], matrix.m[10]
  2050. ]);
  2051. };
  2052. Matrix.Transpose = function (matrix) {
  2053. var result = new Matrix();
  2054. result.m[0] = matrix.m[0];
  2055. result.m[1] = matrix.m[4];
  2056. result.m[2] = matrix.m[8];
  2057. result.m[3] = matrix.m[12];
  2058. result.m[4] = matrix.m[1];
  2059. result.m[5] = matrix.m[5];
  2060. result.m[6] = matrix.m[9];
  2061. result.m[7] = matrix.m[13];
  2062. result.m[8] = matrix.m[2];
  2063. result.m[9] = matrix.m[6];
  2064. result.m[10] = matrix.m[10];
  2065. result.m[11] = matrix.m[14];
  2066. result.m[12] = matrix.m[3];
  2067. result.m[13] = matrix.m[7];
  2068. result.m[14] = matrix.m[11];
  2069. result.m[15] = matrix.m[15];
  2070. return result;
  2071. };
  2072. Matrix.Reflection = function (plane) {
  2073. var matrix = new Matrix();
  2074. Matrix.ReflectionToRef(plane, matrix);
  2075. return matrix;
  2076. };
  2077. Matrix.ReflectionToRef = function (plane, result) {
  2078. plane.normalize();
  2079. var x = plane.normal.x;
  2080. var y = plane.normal.y;
  2081. var z = plane.normal.z;
  2082. var temp = -2 * x;
  2083. var temp2 = -2 * y;
  2084. var temp3 = -2 * z;
  2085. result.m[0] = (temp * x) + 1;
  2086. result.m[1] = temp2 * x;
  2087. result.m[2] = temp3 * x;
  2088. result.m[3] = 0.0;
  2089. result.m[4] = temp * y;
  2090. result.m[5] = (temp2 * y) + 1;
  2091. result.m[6] = temp3 * y;
  2092. result.m[7] = 0.0;
  2093. result.m[8] = temp * z;
  2094. result.m[9] = temp2 * z;
  2095. result.m[10] = (temp3 * z) + 1;
  2096. result.m[11] = 0.0;
  2097. result.m[12] = temp * plane.d;
  2098. result.m[13] = temp2 * plane.d;
  2099. result.m[14] = temp3 * plane.d;
  2100. result.m[15] = 1.0;
  2101. };
  2102. Matrix._tempQuaternion = new Quaternion();
  2103. Matrix._xAxis = Vector3.Zero();
  2104. Matrix._yAxis = Vector3.Zero();
  2105. Matrix._zAxis = Vector3.Zero();
  2106. return Matrix;
  2107. })();
  2108. BABYLON.Matrix = Matrix;
  2109. var Plane = (function () {
  2110. function Plane(a, b, c, d) {
  2111. this.normal = new Vector3(a, b, c);
  2112. this.d = d;
  2113. }
  2114. Plane.prototype.asArray = function () {
  2115. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2116. };
  2117. // Methods
  2118. Plane.prototype.clone = function () {
  2119. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2120. };
  2121. Plane.prototype.normalize = function () {
  2122. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2123. var magnitude = 0;
  2124. if (norm !== 0) {
  2125. magnitude = 1.0 / norm;
  2126. }
  2127. this.normal.x *= magnitude;
  2128. this.normal.y *= magnitude;
  2129. this.normal.z *= magnitude;
  2130. this.d *= magnitude;
  2131. return this;
  2132. };
  2133. Plane.prototype.transform = function (transformation) {
  2134. var transposedMatrix = Matrix.Transpose(transformation);
  2135. var x = this.normal.x;
  2136. var y = this.normal.y;
  2137. var z = this.normal.z;
  2138. var d = this.d;
  2139. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2140. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2141. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2142. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2143. return new Plane(normalX, normalY, normalZ, finalD);
  2144. };
  2145. Plane.prototype.dotCoordinate = function (point) {
  2146. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2147. };
  2148. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2149. var x1 = point2.x - point1.x;
  2150. var y1 = point2.y - point1.y;
  2151. var z1 = point2.z - point1.z;
  2152. var x2 = point3.x - point1.x;
  2153. var y2 = point3.y - point1.y;
  2154. var z2 = point3.z - point1.z;
  2155. var yz = (y1 * z2) - (z1 * y2);
  2156. var xz = (z1 * x2) - (x1 * z2);
  2157. var xy = (x1 * y2) - (y1 * x2);
  2158. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2159. var invPyth;
  2160. if (pyth !== 0) {
  2161. invPyth = 1.0 / pyth;
  2162. }
  2163. else {
  2164. invPyth = 0;
  2165. }
  2166. this.normal.x = yz * invPyth;
  2167. this.normal.y = xz * invPyth;
  2168. this.normal.z = xy * invPyth;
  2169. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2170. return this;
  2171. };
  2172. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2173. var dot = Vector3.Dot(this.normal, direction);
  2174. return (dot <= epsilon);
  2175. };
  2176. Plane.prototype.signedDistanceTo = function (point) {
  2177. return Vector3.Dot(point, this.normal) + this.d;
  2178. };
  2179. // Statics
  2180. Plane.FromArray = function (array) {
  2181. return new Plane(array[0], array[1], array[2], array[3]);
  2182. };
  2183. Plane.FromPoints = function (point1, point2, point3) {
  2184. var result = new Plane(0, 0, 0, 0);
  2185. result.copyFromPoints(point1, point2, point3);
  2186. return result;
  2187. };
  2188. Plane.FromPositionAndNormal = function (origin, normal) {
  2189. var result = new Plane(0, 0, 0, 0);
  2190. normal.normalize();
  2191. result.normal = normal;
  2192. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2193. return result;
  2194. };
  2195. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2196. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2197. return Vector3.Dot(point, normal) + d;
  2198. };
  2199. return Plane;
  2200. })();
  2201. BABYLON.Plane = Plane;
  2202. var Viewport = (function () {
  2203. function Viewport(x, y, width, height) {
  2204. this.x = x;
  2205. this.y = y;
  2206. this.width = width;
  2207. this.height = height;
  2208. }
  2209. Viewport.prototype.toGlobal = function (engine) {
  2210. var width = engine.getRenderWidth();
  2211. var height = engine.getRenderHeight();
  2212. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2213. };
  2214. return Viewport;
  2215. })();
  2216. BABYLON.Viewport = Viewport;
  2217. var Frustum = (function () {
  2218. function Frustum() {
  2219. }
  2220. Frustum.GetPlanes = function (transform) {
  2221. var frustumPlanes = [];
  2222. for (var index = 0; index < 6; index++) {
  2223. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2224. }
  2225. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2226. return frustumPlanes;
  2227. };
  2228. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2229. // Near
  2230. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2231. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2232. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2233. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2234. frustumPlanes[0].normalize();
  2235. // Far
  2236. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2237. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2238. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2239. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2240. frustumPlanes[1].normalize();
  2241. // Left
  2242. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2243. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2244. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2245. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2246. frustumPlanes[2].normalize();
  2247. // Right
  2248. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2249. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2250. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2251. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2252. frustumPlanes[3].normalize();
  2253. // Top
  2254. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2255. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2256. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2257. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2258. frustumPlanes[4].normalize();
  2259. // Bottom
  2260. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2261. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2262. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2263. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2264. frustumPlanes[5].normalize();
  2265. };
  2266. return Frustum;
  2267. })();
  2268. BABYLON.Frustum = Frustum;
  2269. var Ray = (function () {
  2270. function Ray(origin, direction, length) {
  2271. if (length === void 0) { length = Number.MAX_VALUE; }
  2272. this.origin = origin;
  2273. this.direction = direction;
  2274. this.length = length;
  2275. }
  2276. // Methods
  2277. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2278. var d = 0.0;
  2279. var maxValue = Number.MAX_VALUE;
  2280. var inv;
  2281. var min;
  2282. var max;
  2283. var temp;
  2284. if (Math.abs(this.direction.x) < 0.0000001) {
  2285. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2286. return false;
  2287. }
  2288. }
  2289. else {
  2290. inv = 1.0 / this.direction.x;
  2291. min = (minimum.x - this.origin.x) * inv;
  2292. max = (maximum.x - this.origin.x) * inv;
  2293. if (max === -Infinity) {
  2294. max = Infinity;
  2295. }
  2296. if (min > max) {
  2297. temp = min;
  2298. min = max;
  2299. max = temp;
  2300. }
  2301. d = Math.max(min, d);
  2302. maxValue = Math.min(max, maxValue);
  2303. if (d > maxValue) {
  2304. return false;
  2305. }
  2306. }
  2307. if (Math.abs(this.direction.y) < 0.0000001) {
  2308. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2309. return false;
  2310. }
  2311. }
  2312. else {
  2313. inv = 1.0 / this.direction.y;
  2314. min = (minimum.y - this.origin.y) * inv;
  2315. max = (maximum.y - this.origin.y) * inv;
  2316. if (max === -Infinity) {
  2317. max = Infinity;
  2318. }
  2319. if (min > max) {
  2320. temp = min;
  2321. min = max;
  2322. max = temp;
  2323. }
  2324. d = Math.max(min, d);
  2325. maxValue = Math.min(max, maxValue);
  2326. if (d > maxValue) {
  2327. return false;
  2328. }
  2329. }
  2330. if (Math.abs(this.direction.z) < 0.0000001) {
  2331. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2332. return false;
  2333. }
  2334. }
  2335. else {
  2336. inv = 1.0 / this.direction.z;
  2337. min = (minimum.z - this.origin.z) * inv;
  2338. max = (maximum.z - this.origin.z) * inv;
  2339. if (max === -Infinity) {
  2340. max = Infinity;
  2341. }
  2342. if (min > max) {
  2343. temp = min;
  2344. min = max;
  2345. max = temp;
  2346. }
  2347. d = Math.max(min, d);
  2348. maxValue = Math.min(max, maxValue);
  2349. if (d > maxValue) {
  2350. return false;
  2351. }
  2352. }
  2353. return true;
  2354. };
  2355. Ray.prototype.intersectsBox = function (box) {
  2356. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2357. };
  2358. Ray.prototype.intersectsSphere = function (sphere) {
  2359. var x = sphere.center.x - this.origin.x;
  2360. var y = sphere.center.y - this.origin.y;
  2361. var z = sphere.center.z - this.origin.z;
  2362. var pyth = (x * x) + (y * y) + (z * z);
  2363. var rr = sphere.radius * sphere.radius;
  2364. if (pyth <= rr) {
  2365. return true;
  2366. }
  2367. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2368. if (dot < 0.0) {
  2369. return false;
  2370. }
  2371. var temp = pyth - (dot * dot);
  2372. return temp <= rr;
  2373. };
  2374. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2375. if (!this._edge1) {
  2376. this._edge1 = Vector3.Zero();
  2377. this._edge2 = Vector3.Zero();
  2378. this._pvec = Vector3.Zero();
  2379. this._tvec = Vector3.Zero();
  2380. this._qvec = Vector3.Zero();
  2381. }
  2382. vertex1.subtractToRef(vertex0, this._edge1);
  2383. vertex2.subtractToRef(vertex0, this._edge2);
  2384. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2385. var det = Vector3.Dot(this._edge1, this._pvec);
  2386. if (det === 0) {
  2387. return null;
  2388. }
  2389. var invdet = 1 / det;
  2390. this.origin.subtractToRef(vertex0, this._tvec);
  2391. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2392. if (bu < 0 || bu > 1.0) {
  2393. return null;
  2394. }
  2395. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2396. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2397. if (bv < 0 || bu + bv > 1.0) {
  2398. return null;
  2399. }
  2400. //check if the distance is longer than the predefined length.
  2401. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2402. if (distance > this.length) {
  2403. return null;
  2404. }
  2405. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2406. };
  2407. // Statics
  2408. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2409. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2410. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2411. var direction = end.subtract(start);
  2412. direction.normalize();
  2413. return new Ray(start, direction);
  2414. };
  2415. /**
  2416. * 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
  2417. * transformed to the given world matrix.
  2418. * @param origin The origin point
  2419. * @param end The end point
  2420. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2421. */
  2422. Ray.CreateNewFromTo = function (origin, end, world) {
  2423. if (world === void 0) { world = Matrix.Identity(); }
  2424. var direction = end.subtract(origin);
  2425. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2426. direction.normalize();
  2427. return Ray.Transform(new Ray(origin, direction, length), world);
  2428. };
  2429. Ray.Transform = function (ray, matrix) {
  2430. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2431. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2432. return new Ray(newOrigin, newDirection, ray.length);
  2433. };
  2434. return Ray;
  2435. })();
  2436. BABYLON.Ray = Ray;
  2437. (function (Space) {
  2438. Space[Space["LOCAL"] = 0] = "LOCAL";
  2439. Space[Space["WORLD"] = 1] = "WORLD";
  2440. })(BABYLON.Space || (BABYLON.Space = {}));
  2441. var Space = BABYLON.Space;
  2442. var Axis = (function () {
  2443. function Axis() {
  2444. }
  2445. Axis.X = new Vector3(1, 0, 0);
  2446. Axis.Y = new Vector3(0, 1, 0);
  2447. Axis.Z = new Vector3(0, 0, 1);
  2448. return Axis;
  2449. })();
  2450. BABYLON.Axis = Axis;
  2451. ;
  2452. var BezierCurve = (function () {
  2453. function BezierCurve() {
  2454. }
  2455. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2456. // Extract X (which is equal to time here)
  2457. var f0 = 1 - 3 * x2 + 3 * x1;
  2458. var f1 = 3 * x2 - 6 * x1;
  2459. var f2 = 3 * x1;
  2460. var refinedT = t;
  2461. for (var i = 0; i < 5; i++) {
  2462. var refinedT2 = refinedT * refinedT;
  2463. var refinedT3 = refinedT2 * refinedT;
  2464. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2465. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2466. refinedT -= (x - t) * slope;
  2467. refinedT = Math.min(1, Math.max(0, refinedT));
  2468. }
  2469. // Resolve cubic bezier for the given x
  2470. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2471. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2472. Math.pow(refinedT, 3);
  2473. };
  2474. return BezierCurve;
  2475. })();
  2476. BABYLON.BezierCurve = BezierCurve;
  2477. (function (Orientation) {
  2478. Orientation[Orientation["CW"] = 0] = "CW";
  2479. Orientation[Orientation["CCW"] = 1] = "CCW";
  2480. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2481. var Orientation = BABYLON.Orientation;
  2482. var Angle = (function () {
  2483. function Angle(radians) {
  2484. var _this = this;
  2485. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2486. this.radians = function () { return _this._radians; };
  2487. this._radians = radians;
  2488. if (this._radians < 0)
  2489. this._radians += (2 * Math.PI);
  2490. }
  2491. Angle.BetweenTwoPoints = function (a, b) {
  2492. var delta = b.subtract(a);
  2493. var theta = Math.atan2(delta.y, delta.x);
  2494. return new Angle(theta);
  2495. };
  2496. Angle.FromRadians = function (radians) {
  2497. return new Angle(radians);
  2498. };
  2499. Angle.FromDegrees = function (degrees) {
  2500. return new Angle(degrees * Math.PI / 180);
  2501. };
  2502. return Angle;
  2503. })();
  2504. BABYLON.Angle = Angle;
  2505. var Arc2 = (function () {
  2506. function Arc2(startPoint, midPoint, endPoint) {
  2507. this.startPoint = startPoint;
  2508. this.midPoint = midPoint;
  2509. this.endPoint = endPoint;
  2510. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2511. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2512. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2513. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2514. 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);
  2515. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2516. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2517. var a1 = this.startAngle.degrees();
  2518. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2519. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2520. // angles correction
  2521. if (a2 - a1 > +180.0)
  2522. a2 -= 360.0;
  2523. if (a2 - a1 < -180.0)
  2524. a2 += 360.0;
  2525. if (a3 - a2 > +180.0)
  2526. a3 -= 360.0;
  2527. if (a3 - a2 < -180.0)
  2528. a3 += 360.0;
  2529. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2530. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2531. }
  2532. return Arc2;
  2533. })();
  2534. BABYLON.Arc2 = Arc2;
  2535. var PathCursor = (function () {
  2536. function PathCursor(path) {
  2537. this.path = path;
  2538. this._onchange = new Array();
  2539. this.value = 0;
  2540. this.animations = new Array();
  2541. }
  2542. PathCursor.prototype.getPoint = function () {
  2543. var point = this.path.getPointAtLengthPosition(this.value);
  2544. return new Vector3(point.x, 0, point.y);
  2545. };
  2546. PathCursor.prototype.moveAhead = function (step) {
  2547. if (step === void 0) { step = 0.002; }
  2548. this.move(step);
  2549. return this;
  2550. };
  2551. PathCursor.prototype.moveBack = function (step) {
  2552. if (step === void 0) { step = 0.002; }
  2553. this.move(-step);
  2554. return this;
  2555. };
  2556. PathCursor.prototype.move = function (step) {
  2557. if (Math.abs(step) > 1) {
  2558. throw "step size should be less than 1.";
  2559. }
  2560. this.value += step;
  2561. this.ensureLimits();
  2562. this.raiseOnChange();
  2563. return this;
  2564. };
  2565. PathCursor.prototype.ensureLimits = function () {
  2566. while (this.value > 1) {
  2567. this.value -= 1;
  2568. }
  2569. while (this.value < 0) {
  2570. this.value += 1;
  2571. }
  2572. return this;
  2573. };
  2574. // used by animation engine
  2575. PathCursor.prototype.markAsDirty = function (propertyName) {
  2576. this.ensureLimits();
  2577. this.raiseOnChange();
  2578. return this;
  2579. };
  2580. PathCursor.prototype.raiseOnChange = function () {
  2581. var _this = this;
  2582. this._onchange.forEach(function (f) { return f(_this); });
  2583. return this;
  2584. };
  2585. PathCursor.prototype.onchange = function (f) {
  2586. this._onchange.push(f);
  2587. return this;
  2588. };
  2589. return PathCursor;
  2590. })();
  2591. BABYLON.PathCursor = PathCursor;
  2592. var Path2 = (function () {
  2593. function Path2(x, y) {
  2594. this._points = new Array();
  2595. this._length = 0;
  2596. this.closed = false;
  2597. this._points.push(new Vector2(x, y));
  2598. }
  2599. Path2.prototype.addLineTo = function (x, y) {
  2600. if (closed) {
  2601. BABYLON.Tools.Error("cannot add lines to closed paths");
  2602. return this;
  2603. }
  2604. var newPoint = new Vector2(x, y);
  2605. var previousPoint = this._points[this._points.length - 1];
  2606. this._points.push(newPoint);
  2607. this._length += newPoint.subtract(previousPoint).length();
  2608. return this;
  2609. };
  2610. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2611. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2612. if (closed) {
  2613. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2614. return this;
  2615. }
  2616. var startPoint = this._points[this._points.length - 1];
  2617. var midPoint = new Vector2(midX, midY);
  2618. var endPoint = new Vector2(endX, endY);
  2619. var arc = new Arc2(startPoint, midPoint, endPoint);
  2620. var increment = arc.angle.radians() / numberOfSegments;
  2621. if (arc.orientation === Orientation.CW)
  2622. increment *= -1;
  2623. var currentAngle = arc.startAngle.radians() + increment;
  2624. for (var i = 0; i < numberOfSegments; i++) {
  2625. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2626. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2627. this.addLineTo(x, y);
  2628. currentAngle += increment;
  2629. }
  2630. return this;
  2631. };
  2632. Path2.prototype.close = function () {
  2633. this.closed = true;
  2634. return this;
  2635. };
  2636. Path2.prototype.length = function () {
  2637. var result = this._length;
  2638. if (!this.closed) {
  2639. var lastPoint = this._points[this._points.length - 1];
  2640. var firstPoint = this._points[0];
  2641. result += (firstPoint.subtract(lastPoint).length());
  2642. }
  2643. return result;
  2644. };
  2645. Path2.prototype.getPoints = function () {
  2646. return this._points;
  2647. };
  2648. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2649. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2650. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2651. return Vector2.Zero();
  2652. }
  2653. var lengthPosition = normalizedLengthPosition * this.length();
  2654. var previousOffset = 0;
  2655. for (var i = 0; i < this._points.length; i++) {
  2656. var j = (i + 1) % this._points.length;
  2657. var a = this._points[i];
  2658. var b = this._points[j];
  2659. var bToA = b.subtract(a);
  2660. var nextOffset = (bToA.length() + previousOffset);
  2661. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2662. var dir = bToA.normalize();
  2663. var localOffset = lengthPosition - previousOffset;
  2664. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2665. }
  2666. previousOffset = nextOffset;
  2667. }
  2668. BABYLON.Tools.Error("internal error");
  2669. return Vector2.Zero();
  2670. };
  2671. Path2.StartingAt = function (x, y) {
  2672. return new Path2(x, y);
  2673. };
  2674. return Path2;
  2675. })();
  2676. BABYLON.Path2 = Path2;
  2677. var Path3D = (function () {
  2678. /**
  2679. * new Path3D(path, normal, raw)
  2680. * path : an array of Vector3, the curve axis of the Path3D
  2681. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2682. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2683. */
  2684. function Path3D(path, firstNormal, raw) {
  2685. this.path = path;
  2686. this._curve = new Array();
  2687. this._distances = new Array();
  2688. this._tangents = new Array();
  2689. this._normals = new Array();
  2690. this._binormals = new Array();
  2691. for (var p = 0; p < path.length; p++) {
  2692. this._curve[p] = path[p].clone(); // hard copy
  2693. }
  2694. this._raw = raw || false;
  2695. this._compute(firstNormal);
  2696. }
  2697. Path3D.prototype.getCurve = function () {
  2698. return this._curve;
  2699. };
  2700. Path3D.prototype.getTangents = function () {
  2701. return this._tangents;
  2702. };
  2703. Path3D.prototype.getNormals = function () {
  2704. return this._normals;
  2705. };
  2706. Path3D.prototype.getBinormals = function () {
  2707. return this._binormals;
  2708. };
  2709. Path3D.prototype.getDistances = function () {
  2710. return this._distances;
  2711. };
  2712. Path3D.prototype.update = function (path, firstNormal) {
  2713. for (var p = 0; p < path.length; p++) {
  2714. this._curve[p].x = path[p].x;
  2715. this._curve[p].y = path[p].y;
  2716. this._curve[p].z = path[p].z;
  2717. }
  2718. this._compute(firstNormal);
  2719. return this;
  2720. };
  2721. // private function compute() : computes tangents, normals and binormals
  2722. Path3D.prototype._compute = function (firstNormal) {
  2723. var l = this._curve.length;
  2724. // first and last tangents
  2725. this._tangents[0] = this._getFirstNonNullVector(0);
  2726. if (!this._raw) {
  2727. this._tangents[0].normalize();
  2728. }
  2729. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2730. if (!this._raw) {
  2731. this._tangents[l - 1].normalize();
  2732. }
  2733. // normals and binormals at first point : arbitrary vector with _normalVector()
  2734. var tg0 = this._tangents[0];
  2735. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2736. this._normals[0] = pp0;
  2737. if (!this._raw) {
  2738. this._normals[0].normalize();
  2739. }
  2740. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2741. if (!this._raw) {
  2742. this._binormals[0].normalize();
  2743. }
  2744. this._distances[0] = 0;
  2745. // normals and binormals : next points
  2746. var prev; // previous vector (segment)
  2747. var cur; // current vector (segment)
  2748. var curTang; // current tangent
  2749. // previous normal
  2750. var prevBinor; // previous binormal
  2751. for (var i = 1; i < l; i++) {
  2752. // tangents
  2753. prev = this._getLastNonNullVector(i);
  2754. if (i < l - 1) {
  2755. cur = this._getFirstNonNullVector(i);
  2756. this._tangents[i] = prev.add(cur);
  2757. this._tangents[i].normalize();
  2758. }
  2759. this._distances[i] = this._distances[i - 1] + prev.length();
  2760. // normals and binormals
  2761. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2762. curTang = this._tangents[i];
  2763. prevBinor = this._binormals[i - 1];
  2764. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2765. if (!this._raw) {
  2766. this._normals[i].normalize();
  2767. }
  2768. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2769. if (!this._raw) {
  2770. this._binormals[i].normalize();
  2771. }
  2772. }
  2773. };
  2774. // private function getFirstNonNullVector(index)
  2775. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2776. Path3D.prototype._getFirstNonNullVector = function (index) {
  2777. var i = 1;
  2778. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2779. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2780. i++;
  2781. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2782. }
  2783. return nNVector;
  2784. };
  2785. // private function getLastNonNullVector(index)
  2786. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2787. Path3D.prototype._getLastNonNullVector = function (index) {
  2788. var i = 1;
  2789. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2790. while (nLVector.length() === 0 && index > i + 1) {
  2791. i++;
  2792. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2793. }
  2794. return nLVector;
  2795. };
  2796. // private function normalVector(v0, vt, va) :
  2797. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2798. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2799. Path3D.prototype._normalVector = function (v0, vt, va) {
  2800. var normal0;
  2801. if (va === undefined || va === null) {
  2802. var point;
  2803. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2804. point = new Vector3(0, -1, 0);
  2805. }
  2806. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2807. point = new Vector3(1, 0, 0);
  2808. }
  2809. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2810. point = new Vector3(0, 0, 1);
  2811. }
  2812. normal0 = Vector3.Cross(vt, point);
  2813. }
  2814. else {
  2815. normal0 = Vector3.Cross(vt, va);
  2816. Vector3.CrossToRef(normal0, vt, normal0);
  2817. }
  2818. normal0.normalize();
  2819. return normal0;
  2820. };
  2821. return Path3D;
  2822. })();
  2823. BABYLON.Path3D = Path3D;
  2824. var Curve3 = (function () {
  2825. function Curve3(points) {
  2826. this._length = 0;
  2827. this._points = points;
  2828. this._length = this._computeLength(points);
  2829. }
  2830. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2831. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2832. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2833. var bez = new Array();
  2834. var equation = function (t, val0, val1, val2) {
  2835. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2836. return res;
  2837. };
  2838. for (var i = 0; i <= nbPoints; i++) {
  2839. 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)));
  2840. }
  2841. return new Curve3(bez);
  2842. };
  2843. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2844. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2845. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2846. var bez = new Array();
  2847. var equation = function (t, val0, val1, val2, val3) {
  2848. 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;
  2849. return res;
  2850. };
  2851. for (var i = 0; i <= nbPoints; i++) {
  2852. 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)));
  2853. }
  2854. return new Curve3(bez);
  2855. };
  2856. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2857. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2858. var hermite = new Array();
  2859. var step = 1 / nbPoints;
  2860. for (var i = 0; i <= nbPoints; i++) {
  2861. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2862. }
  2863. return new Curve3(hermite);
  2864. };
  2865. Curve3.prototype.getPoints = function () {
  2866. return this._points;
  2867. };
  2868. Curve3.prototype.length = function () {
  2869. return this._length;
  2870. };
  2871. Curve3.prototype.continue = function (curve) {
  2872. var lastPoint = this._points[this._points.length - 1];
  2873. var continuedPoints = this._points.slice();
  2874. var curvePoints = curve.getPoints();
  2875. for (var i = 1; i < curvePoints.length; i++) {
  2876. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2877. }
  2878. var continuedCurve = new Curve3(continuedPoints);
  2879. return continuedCurve;
  2880. };
  2881. Curve3.prototype._computeLength = function (path) {
  2882. var l = 0;
  2883. for (var i = 1; i < path.length; i++) {
  2884. l += (path[i].subtract(path[i - 1])).length();
  2885. }
  2886. return l;
  2887. };
  2888. return Curve3;
  2889. })();
  2890. BABYLON.Curve3 = Curve3;
  2891. // Vertex formats
  2892. var PositionNormalVertex = (function () {
  2893. function PositionNormalVertex(position, normal) {
  2894. if (position === void 0) { position = Vector3.Zero(); }
  2895. if (normal === void 0) { normal = Vector3.Up(); }
  2896. this.position = position;
  2897. this.normal = normal;
  2898. }
  2899. PositionNormalVertex.prototype.clone = function () {
  2900. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2901. };
  2902. return PositionNormalVertex;
  2903. })();
  2904. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2905. var PositionNormalTextureVertex = (function () {
  2906. function PositionNormalTextureVertex(position, normal, uv) {
  2907. if (position === void 0) { position = Vector3.Zero(); }
  2908. if (normal === void 0) { normal = Vector3.Up(); }
  2909. if (uv === void 0) { uv = Vector2.Zero(); }
  2910. this.position = position;
  2911. this.normal = normal;
  2912. this.uv = uv;
  2913. }
  2914. PositionNormalTextureVertex.prototype.clone = function () {
  2915. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2916. };
  2917. return PositionNormalTextureVertex;
  2918. })();
  2919. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2920. })(BABYLON || (BABYLON = {}));
  2921. var BABYLON;
  2922. (function (BABYLON) {
  2923. var Database = (function () {
  2924. function Database(urlToScene, callbackManifestChecked) {
  2925. // Handling various flavors of prefixed version of IndexedDB
  2926. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2927. this.callbackManifestChecked = callbackManifestChecked;
  2928. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2929. this.db = null;
  2930. this.enableSceneOffline = false;
  2931. this.enableTexturesOffline = false;
  2932. this.manifestVersionFound = 0;
  2933. this.mustUpdateRessources = false;
  2934. this.hasReachedQuota = false;
  2935. if (!Database.IDBStorageEnabled) {
  2936. this.callbackManifestChecked(true);
  2937. }
  2938. else {
  2939. this.checkManifestFile();
  2940. }
  2941. }
  2942. Database.prototype.checkManifestFile = function () {
  2943. var _this = this;
  2944. function noManifestFile() {
  2945. that.enableSceneOffline = false;
  2946. that.enableTexturesOffline = false;
  2947. that.callbackManifestChecked(false);
  2948. }
  2949. var that = this;
  2950. var manifestURL = this.currentSceneUrl + ".manifest";
  2951. var xhr = new XMLHttpRequest();
  2952. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2953. xhr.open("GET", manifestURLTimeStamped, true);
  2954. xhr.addEventListener("load", function () {
  2955. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2956. try {
  2957. var manifestFile = JSON.parse(xhr.response);
  2958. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2959. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2960. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2961. _this.manifestVersionFound = manifestFile.version;
  2962. }
  2963. if (_this.callbackManifestChecked) {
  2964. _this.callbackManifestChecked(true);
  2965. }
  2966. }
  2967. catch (ex) {
  2968. noManifestFile();
  2969. }
  2970. }
  2971. else {
  2972. noManifestFile();
  2973. }
  2974. }, false);
  2975. xhr.addEventListener("error", function (event) {
  2976. noManifestFile();
  2977. }, false);
  2978. try {
  2979. xhr.send();
  2980. }
  2981. catch (ex) {
  2982. BABYLON.Tools.Error("Error on XHR send request.");
  2983. that.callbackManifestChecked(false);
  2984. }
  2985. };
  2986. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2987. var _this = this;
  2988. function handleError() {
  2989. that.isSupported = false;
  2990. if (errorCallback)
  2991. errorCallback();
  2992. }
  2993. var that = this;
  2994. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2995. // Your browser doesn't support IndexedDB
  2996. this.isSupported = false;
  2997. if (errorCallback)
  2998. errorCallback();
  2999. }
  3000. else {
  3001. // If the DB hasn't been opened or created yet
  3002. if (!this.db) {
  3003. this.hasReachedQuota = false;
  3004. this.isSupported = true;
  3005. var request = this.idbFactory.open("babylonjs", 1);
  3006. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3007. request.onerror = function (event) {
  3008. handleError();
  3009. };
  3010. // executes when a version change transaction cannot complete due to other active transactions
  3011. request.onblocked = function (event) {
  3012. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3013. handleError();
  3014. };
  3015. // DB has been opened successfully
  3016. request.onsuccess = function (event) {
  3017. _this.db = request.result;
  3018. successCallback();
  3019. };
  3020. // Initialization of the DB. Creating Scenes & Textures stores
  3021. request.onupgradeneeded = function (event) {
  3022. _this.db = (event.target).result;
  3023. try {
  3024. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3025. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3026. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3027. }
  3028. catch (ex) {
  3029. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3030. handleError();
  3031. }
  3032. };
  3033. }
  3034. else {
  3035. if (successCallback)
  3036. successCallback();
  3037. }
  3038. }
  3039. };
  3040. Database.prototype.loadImageFromDB = function (url, image) {
  3041. var _this = this;
  3042. var completeURL = Database.ReturnFullUrlLocation(url);
  3043. var saveAndLoadImage = function () {
  3044. if (!_this.hasReachedQuota && _this.db !== null) {
  3045. // the texture is not yet in the DB, let's try to save it
  3046. _this._saveImageIntoDBAsync(completeURL, image);
  3047. }
  3048. else {
  3049. image.src = url;
  3050. }
  3051. };
  3052. if (!this.mustUpdateRessources) {
  3053. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3054. }
  3055. else {
  3056. saveAndLoadImage();
  3057. }
  3058. };
  3059. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3060. if (this.isSupported && this.db !== null) {
  3061. var texture;
  3062. var transaction = this.db.transaction(["textures"]);
  3063. transaction.onabort = function (event) {
  3064. image.src = url;
  3065. };
  3066. transaction.oncomplete = function (event) {
  3067. var blobTextureURL;
  3068. if (texture) {
  3069. var URL = window.URL || window.webkitURL;
  3070. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3071. image.onerror = function () {
  3072. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3073. image.src = url;
  3074. };
  3075. image.src = blobTextureURL;
  3076. }
  3077. else {
  3078. notInDBCallback();
  3079. }
  3080. };
  3081. var getRequest = transaction.objectStore("textures").get(url);
  3082. getRequest.onsuccess = function (event) {
  3083. texture = (event.target).result;
  3084. };
  3085. getRequest.onerror = function (event) {
  3086. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3087. image.src = url;
  3088. };
  3089. }
  3090. else {
  3091. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3092. image.src = url;
  3093. }
  3094. };
  3095. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3096. var _this = this;
  3097. if (this.isSupported) {
  3098. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3099. var generateBlobUrl = function () {
  3100. var blobTextureURL;
  3101. if (blob) {
  3102. var URL = window.URL || window.webkitURL;
  3103. try {
  3104. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3105. }
  3106. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3107. catch (ex) {
  3108. blobTextureURL = URL.createObjectURL(blob);
  3109. }
  3110. }
  3111. image.src = blobTextureURL;
  3112. };
  3113. if (Database.IsUASupportingBlobStorage) {
  3114. var xhr = new XMLHttpRequest(), blob;
  3115. xhr.open("GET", url, true);
  3116. xhr.responseType = "blob";
  3117. xhr.addEventListener("load", function () {
  3118. if (xhr.status === 200) {
  3119. // Blob as response (XHR2)
  3120. blob = xhr.response;
  3121. var transaction = _this.db.transaction(["textures"], "readwrite");
  3122. // the transaction could abort because of a QuotaExceededError error
  3123. transaction.onabort = function (event) {
  3124. try {
  3125. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3126. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3127. this.hasReachedQuota = true;
  3128. }
  3129. }
  3130. catch (ex) { }
  3131. generateBlobUrl();
  3132. };
  3133. transaction.oncomplete = function (event) {
  3134. generateBlobUrl();
  3135. };
  3136. var newTexture = { textureUrl: url, data: blob };
  3137. try {
  3138. // Put the blob into the dabase
  3139. var addRequest = transaction.objectStore("textures").put(newTexture);
  3140. addRequest.onsuccess = function (event) {
  3141. };
  3142. addRequest.onerror = function (event) {
  3143. generateBlobUrl();
  3144. };
  3145. }
  3146. catch (ex) {
  3147. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3148. if (ex.code === 25) {
  3149. Database.IsUASupportingBlobStorage = false;
  3150. }
  3151. image.src = url;
  3152. }
  3153. }
  3154. else {
  3155. image.src = url;
  3156. }
  3157. }, false);
  3158. xhr.addEventListener("error", function (event) {
  3159. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3160. image.src = url;
  3161. }, false);
  3162. xhr.send();
  3163. }
  3164. else {
  3165. image.src = url;
  3166. }
  3167. }
  3168. else {
  3169. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3170. image.src = url;
  3171. }
  3172. };
  3173. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3174. var _this = this;
  3175. var updateVersion = function (event) {
  3176. // the version is not yet in the DB or we need to update it
  3177. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3178. };
  3179. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3180. };
  3181. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3182. var _this = this;
  3183. if (this.isSupported) {
  3184. var version;
  3185. try {
  3186. var transaction = this.db.transaction(["versions"]);
  3187. transaction.oncomplete = function (event) {
  3188. if (version) {
  3189. // If the version in the JSON file is > than the version in DB
  3190. if (_this.manifestVersionFound > version.data) {
  3191. _this.mustUpdateRessources = true;
  3192. updateInDBCallback();
  3193. }
  3194. else {
  3195. callback(version.data);
  3196. }
  3197. }
  3198. else {
  3199. _this.mustUpdateRessources = true;
  3200. updateInDBCallback();
  3201. }
  3202. };
  3203. transaction.onabort = function (event) {
  3204. callback(-1);
  3205. };
  3206. var getRequest = transaction.objectStore("versions").get(url);
  3207. getRequest.onsuccess = function (event) {
  3208. version = (event.target).result;
  3209. };
  3210. getRequest.onerror = function (event) {
  3211. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3212. callback(-1);
  3213. };
  3214. }
  3215. catch (ex) {
  3216. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3217. callback(-1);
  3218. }
  3219. }
  3220. else {
  3221. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3222. callback(-1);
  3223. }
  3224. };
  3225. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3226. var _this = this;
  3227. if (this.isSupported && !this.hasReachedQuota) {
  3228. try {
  3229. // Open a transaction to the database
  3230. var transaction = this.db.transaction(["versions"], "readwrite");
  3231. // the transaction could abort because of a QuotaExceededError error
  3232. transaction.onabort = function (event) {
  3233. try {
  3234. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3235. _this.hasReachedQuota = true;
  3236. }
  3237. }
  3238. catch (ex) { }
  3239. callback(-1);
  3240. };
  3241. transaction.oncomplete = function (event) {
  3242. callback(_this.manifestVersionFound);
  3243. };
  3244. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3245. // Put the scene into the database
  3246. var addRequest = transaction.objectStore("versions").put(newVersion);
  3247. addRequest.onsuccess = function (event) {
  3248. };
  3249. addRequest.onerror = function (event) {
  3250. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3251. };
  3252. }
  3253. catch (ex) {
  3254. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3255. callback(-1);
  3256. }
  3257. }
  3258. else {
  3259. callback(-1);
  3260. }
  3261. };
  3262. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3263. var _this = this;
  3264. var completeUrl = Database.ReturnFullUrlLocation(url);
  3265. var saveAndLoadFile = function (event) {
  3266. // the scene is not yet in the DB, let's try to save it
  3267. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3268. };
  3269. this._checkVersionFromDB(completeUrl, function (version) {
  3270. if (version !== -1) {
  3271. if (!_this.mustUpdateRessources) {
  3272. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3273. }
  3274. else {
  3275. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3276. }
  3277. }
  3278. else {
  3279. errorCallback();
  3280. }
  3281. });
  3282. };
  3283. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3284. if (this.isSupported) {
  3285. var targetStore;
  3286. if (url.indexOf(".babylon") !== -1) {
  3287. targetStore = "scenes";
  3288. }
  3289. else {
  3290. targetStore = "textures";
  3291. }
  3292. var file;
  3293. var transaction = this.db.transaction([targetStore]);
  3294. transaction.oncomplete = function (event) {
  3295. if (file) {
  3296. callback(file.data);
  3297. }
  3298. else {
  3299. notInDBCallback();
  3300. }
  3301. };
  3302. transaction.onabort = function (event) {
  3303. notInDBCallback();
  3304. };
  3305. var getRequest = transaction.objectStore(targetStore).get(url);
  3306. getRequest.onsuccess = function (event) {
  3307. file = (event.target).result;
  3308. };
  3309. getRequest.onerror = function (event) {
  3310. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3311. notInDBCallback();
  3312. };
  3313. }
  3314. else {
  3315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3316. callback();
  3317. }
  3318. };
  3319. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3320. var _this = this;
  3321. if (this.isSupported) {
  3322. var targetStore;
  3323. if (url.indexOf(".babylon") !== -1) {
  3324. targetStore = "scenes";
  3325. }
  3326. else {
  3327. targetStore = "textures";
  3328. }
  3329. // Create XHR
  3330. var xhr = new XMLHttpRequest(), fileData;
  3331. xhr.open("GET", url, true);
  3332. if (useArrayBuffer) {
  3333. xhr.responseType = "arraybuffer";
  3334. }
  3335. xhr.onprogress = progressCallback;
  3336. xhr.addEventListener("load", function () {
  3337. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3338. // Blob as response (XHR2)
  3339. //fileData = xhr.responseText;
  3340. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3341. if (!_this.hasReachedQuota) {
  3342. // Open a transaction to the database
  3343. var transaction = _this.db.transaction([targetStore], "readwrite");
  3344. // the transaction could abort because of a QuotaExceededError error
  3345. transaction.onabort = function (event) {
  3346. try {
  3347. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3348. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3349. this.hasReachedQuota = true;
  3350. }
  3351. }
  3352. catch (ex) { }
  3353. callback(fileData);
  3354. };
  3355. transaction.oncomplete = function (event) {
  3356. callback(fileData);
  3357. };
  3358. var newFile;
  3359. if (targetStore === "scenes") {
  3360. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3361. }
  3362. else {
  3363. newFile = { textureUrl: url, data: fileData };
  3364. }
  3365. try {
  3366. // Put the scene into the database
  3367. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3368. addRequest.onsuccess = function (event) {
  3369. };
  3370. addRequest.onerror = function (event) {
  3371. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3372. };
  3373. }
  3374. catch (ex) {
  3375. callback(fileData);
  3376. }
  3377. }
  3378. else {
  3379. callback(fileData);
  3380. }
  3381. }
  3382. else {
  3383. callback();
  3384. }
  3385. }, false);
  3386. xhr.addEventListener("error", function (event) {
  3387. BABYLON.Tools.Error("error on XHR request.");
  3388. callback();
  3389. }, false);
  3390. xhr.send();
  3391. }
  3392. else {
  3393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3394. callback();
  3395. }
  3396. };
  3397. Database.IsUASupportingBlobStorage = true;
  3398. Database.IDBStorageEnabled = true;
  3399. Database.parseURL = function (url) {
  3400. var a = document.createElement('a');
  3401. a.href = url;
  3402. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3403. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3404. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3405. return absLocation;
  3406. };
  3407. Database.ReturnFullUrlLocation = function (url) {
  3408. if (url.indexOf("http:/") === -1) {
  3409. return (Database.parseURL(window.location.href) + url);
  3410. }
  3411. else {
  3412. return url;
  3413. }
  3414. };
  3415. return Database;
  3416. })();
  3417. BABYLON.Database = Database;
  3418. })(BABYLON || (BABYLON = {}));
  3419. var BABYLON;
  3420. (function (BABYLON) {
  3421. var Internals;
  3422. (function (Internals) {
  3423. /*
  3424. * Based on jsTGALoader - Javascript loader for TGA file
  3425. * By Vincent Thibault
  3426. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3427. */
  3428. var TGATools = (function () {
  3429. function TGATools() {
  3430. }
  3431. TGATools.GetTGAHeader = function (data) {
  3432. var offset = 0;
  3433. var header = {
  3434. id_length: data[offset++],
  3435. colormap_type: data[offset++],
  3436. image_type: data[offset++],
  3437. colormap_index: data[offset++] | data[offset++] << 8,
  3438. colormap_length: data[offset++] | data[offset++] << 8,
  3439. colormap_size: data[offset++],
  3440. origin: [
  3441. data[offset++] | data[offset++] << 8,
  3442. data[offset++] | data[offset++] << 8
  3443. ],
  3444. width: data[offset++] | data[offset++] << 8,
  3445. height: data[offset++] | data[offset++] << 8,
  3446. pixel_size: data[offset++],
  3447. flags: data[offset++]
  3448. };
  3449. return header;
  3450. };
  3451. TGATools.UploadContent = function (gl, data) {
  3452. // Not enough data to contain header ?
  3453. if (data.length < 19) {
  3454. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3455. return;
  3456. }
  3457. // Read Header
  3458. var offset = 18;
  3459. var header = TGATools.GetTGAHeader(data);
  3460. // Assume it's a valid Targa file.
  3461. if (header.id_length + offset > data.length) {
  3462. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3463. return;
  3464. }
  3465. // Skip not needed data
  3466. offset += header.id_length;
  3467. var use_rle = false;
  3468. var use_pal = false;
  3469. var use_rgb = false;
  3470. var use_grey = false;
  3471. // Get some informations.
  3472. switch (header.image_type) {
  3473. case TGATools._TYPE_RLE_INDEXED:
  3474. use_rle = true;
  3475. case TGATools._TYPE_INDEXED:
  3476. use_pal = true;
  3477. break;
  3478. case TGATools._TYPE_RLE_RGB:
  3479. use_rle = true;
  3480. case TGATools._TYPE_RGB:
  3481. use_rgb = true;
  3482. break;
  3483. case TGATools._TYPE_RLE_GREY:
  3484. use_rle = true;
  3485. case TGATools._TYPE_GREY:
  3486. use_grey = true;
  3487. break;
  3488. }
  3489. var pixel_data;
  3490. var numAlphaBits = header.flags & 0xf;
  3491. var pixel_size = header.pixel_size >> 3;
  3492. var pixel_total = header.width * header.height * pixel_size;
  3493. // Read palettes
  3494. var palettes;
  3495. if (use_pal) {
  3496. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3497. }
  3498. // Read LRE
  3499. if (use_rle) {
  3500. pixel_data = new Uint8Array(pixel_total);
  3501. var c, count, i;
  3502. var localOffset = 0;
  3503. var pixels = new Uint8Array(pixel_size);
  3504. while (offset < pixel_total && localOffset < pixel_total) {
  3505. c = data[offset++];
  3506. count = (c & 0x7f) + 1;
  3507. // RLE pixels
  3508. if (c & 0x80) {
  3509. // Bind pixel tmp array
  3510. for (i = 0; i < pixel_size; ++i) {
  3511. pixels[i] = data[offset++];
  3512. }
  3513. // Copy pixel array
  3514. for (i = 0; i < count; ++i) {
  3515. pixel_data.set(pixels, localOffset + i * pixel_size);
  3516. }
  3517. localOffset += pixel_size * count;
  3518. }
  3519. else {
  3520. count *= pixel_size;
  3521. for (i = 0; i < count; ++i) {
  3522. pixel_data[localOffset + i] = data[offset++];
  3523. }
  3524. localOffset += count;
  3525. }
  3526. }
  3527. }
  3528. else {
  3529. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3530. }
  3531. // Load to texture
  3532. var x_start, y_start, x_step, y_step, y_end, x_end;
  3533. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3534. default:
  3535. case TGATools._ORIGIN_UL:
  3536. x_start = 0;
  3537. x_step = 1;
  3538. x_end = header.width;
  3539. y_start = 0;
  3540. y_step = 1;
  3541. y_end = header.height;
  3542. break;
  3543. case TGATools._ORIGIN_BL:
  3544. x_start = 0;
  3545. x_step = 1;
  3546. x_end = header.width;
  3547. y_start = header.height - 1;
  3548. y_step = -1;
  3549. y_end = -1;
  3550. break;
  3551. case TGATools._ORIGIN_UR:
  3552. x_start = header.width - 1;
  3553. x_step = -1;
  3554. x_end = -1;
  3555. y_start = 0;
  3556. y_step = 1;
  3557. y_end = header.height;
  3558. break;
  3559. case TGATools._ORIGIN_BR:
  3560. x_start = header.width - 1;
  3561. x_step = -1;
  3562. x_end = -1;
  3563. y_start = header.height - 1;
  3564. y_step = -1;
  3565. y_end = -1;
  3566. break;
  3567. }
  3568. // Load the specify method
  3569. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3570. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3571. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3572. };
  3573. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3574. var image = pixel_data, colormap = palettes;
  3575. var width = header.width, height = header.height;
  3576. var color, i = 0, x, y;
  3577. var imageData = new Uint8Array(width * height * 4);
  3578. for (y = y_start; y !== y_end; y += y_step) {
  3579. for (x = x_start; x !== x_end; x += x_step, i++) {
  3580. color = image[i];
  3581. imageData[(x + width * y) * 4 + 3] = 255;
  3582. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3583. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3584. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3585. }
  3586. }
  3587. return imageData;
  3588. };
  3589. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3590. var image = pixel_data;
  3591. var width = header.width, height = header.height;
  3592. var color, i = 0, x, y;
  3593. var imageData = new Uint8Array(width * height * 4);
  3594. for (y = y_start; y !== y_end; y += y_step) {
  3595. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3596. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3597. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3598. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3599. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3600. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3601. }
  3602. }
  3603. return imageData;
  3604. };
  3605. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3606. var image = pixel_data;
  3607. var width = header.width, height = header.height;
  3608. var i = 0, x, y;
  3609. var imageData = new Uint8Array(width * height * 4);
  3610. for (y = y_start; y !== y_end; y += y_step) {
  3611. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3612. imageData[(x + width * y) * 4 + 3] = 255;
  3613. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3614. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3615. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3616. }
  3617. }
  3618. return imageData;
  3619. };
  3620. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3621. var image = pixel_data;
  3622. var width = header.width, height = header.height;
  3623. var i = 0, x, y;
  3624. var imageData = new Uint8Array(width * height * 4);
  3625. for (y = y_start; y !== y_end; y += y_step) {
  3626. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3627. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3628. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3629. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3630. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3631. }
  3632. }
  3633. return imageData;
  3634. };
  3635. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3636. var image = pixel_data;
  3637. var width = header.width, height = header.height;
  3638. var color, i = 0, x, y;
  3639. var imageData = new Uint8Array(width * height * 4);
  3640. for (y = y_start; y !== y_end; y += y_step) {
  3641. for (x = x_start; x !== x_end; x += x_step, i++) {
  3642. color = image[i];
  3643. imageData[(x + width * y) * 4 + 0] = color;
  3644. imageData[(x + width * y) * 4 + 1] = color;
  3645. imageData[(x + width * y) * 4 + 2] = color;
  3646. imageData[(x + width * y) * 4 + 3] = 255;
  3647. }
  3648. }
  3649. return imageData;
  3650. };
  3651. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3652. var image = pixel_data;
  3653. var width = header.width, height = header.height;
  3654. var i = 0, x, y;
  3655. var imageData = new Uint8Array(width * height * 4);
  3656. for (y = y_start; y !== y_end; y += y_step) {
  3657. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3658. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3659. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3660. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3661. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3662. }
  3663. }
  3664. return imageData;
  3665. };
  3666. TGATools._TYPE_NO_DATA = 0;
  3667. TGATools._TYPE_INDEXED = 1;
  3668. TGATools._TYPE_RGB = 2;
  3669. TGATools._TYPE_GREY = 3;
  3670. TGATools._TYPE_RLE_INDEXED = 9;
  3671. TGATools._TYPE_RLE_RGB = 10;
  3672. TGATools._TYPE_RLE_GREY = 11;
  3673. TGATools._ORIGIN_MASK = 0x30;
  3674. TGATools._ORIGIN_SHIFT = 0x04;
  3675. TGATools._ORIGIN_BL = 0x00;
  3676. TGATools._ORIGIN_BR = 0x01;
  3677. TGATools._ORIGIN_UL = 0x02;
  3678. TGATools._ORIGIN_UR = 0x03;
  3679. return TGATools;
  3680. })();
  3681. Internals.TGATools = TGATools;
  3682. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3683. })(BABYLON || (BABYLON = {}));
  3684. var BABYLON;
  3685. (function (BABYLON) {
  3686. var SmartArray = (function () {
  3687. function SmartArray(capacity) {
  3688. this.length = 0;
  3689. this._duplicateId = 0;
  3690. this.data = new Array(capacity);
  3691. this._id = SmartArray._GlobalId++;
  3692. }
  3693. SmartArray.prototype.push = function (value) {
  3694. this.data[this.length++] = value;
  3695. if (this.length > this.data.length) {
  3696. this.data.length *= 2;
  3697. }
  3698. if (!value.__smartArrayFlags) {
  3699. value.__smartArrayFlags = {};
  3700. }
  3701. value.__smartArrayFlags[this._id] = this._duplicateId;
  3702. };
  3703. SmartArray.prototype.pushNoDuplicate = function (value) {
  3704. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3705. return;
  3706. }
  3707. this.push(value);
  3708. };
  3709. SmartArray.prototype.sort = function (compareFn) {
  3710. this.data.sort(compareFn);
  3711. };
  3712. SmartArray.prototype.reset = function () {
  3713. this.length = 0;
  3714. this._duplicateId++;
  3715. };
  3716. SmartArray.prototype.concat = function (array) {
  3717. if (array.length === 0) {
  3718. return;
  3719. }
  3720. if (this.length + array.length > this.data.length) {
  3721. this.data.length = (this.length + array.length) * 2;
  3722. }
  3723. for (var index = 0; index < array.length; index++) {
  3724. this.data[this.length++] = (array.data || array)[index];
  3725. }
  3726. };
  3727. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3728. if (array.length === 0) {
  3729. return;
  3730. }
  3731. if (this.length + array.length > this.data.length) {
  3732. this.data.length = (this.length + array.length) * 2;
  3733. }
  3734. for (var index = 0; index < array.length; index++) {
  3735. var item = (array.data || array)[index];
  3736. this.pushNoDuplicate(item);
  3737. }
  3738. };
  3739. SmartArray.prototype.indexOf = function (value) {
  3740. var position = this.data.indexOf(value);
  3741. if (position >= this.length) {
  3742. return -1;
  3743. }
  3744. return position;
  3745. };
  3746. // Statics
  3747. SmartArray._GlobalId = 0;
  3748. return SmartArray;
  3749. })();
  3750. BABYLON.SmartArray = SmartArray;
  3751. })(BABYLON || (BABYLON = {}));
  3752. var BABYLON;
  3753. (function (BABYLON) {
  3754. var SmartCollection = (function () {
  3755. function SmartCollection(capacity) {
  3756. if (capacity === void 0) { capacity = 10; }
  3757. this.count = 0;
  3758. this._initialCapacity = capacity;
  3759. this.items = {};
  3760. this._keys = new Array(this._initialCapacity);
  3761. }
  3762. SmartCollection.prototype.add = function (key, item) {
  3763. if (this.items[key] != undefined) {
  3764. return -1;
  3765. }
  3766. this.items[key] = item;
  3767. //literal keys are always strings, but we keep source type of key in _keys array
  3768. this._keys[this.count++] = key;
  3769. if (this.count > this._keys.length) {
  3770. this._keys.length *= 2;
  3771. }
  3772. return this.count;
  3773. };
  3774. SmartCollection.prototype.remove = function (key) {
  3775. if (this.items[key] == undefined) {
  3776. return -1;
  3777. }
  3778. return this.removeItemOfIndex(this.indexOf(key));
  3779. };
  3780. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3781. if (index < this.count && index > -1) {
  3782. delete this.items[this._keys[index]];
  3783. //here, shifting by hand is better optimised than .splice
  3784. while (index < this.count) {
  3785. this._keys[index] = this._keys[index + 1];
  3786. index++;
  3787. }
  3788. }
  3789. else {
  3790. return -1;
  3791. }
  3792. return --this.count;
  3793. };
  3794. SmartCollection.prototype.indexOf = function (key) {
  3795. for (var i = 0; i !== this.count; i++) {
  3796. if (this._keys[i] === key) {
  3797. return i;
  3798. }
  3799. }
  3800. return -1;
  3801. };
  3802. SmartCollection.prototype.item = function (key) {
  3803. return this.items[key];
  3804. };
  3805. SmartCollection.prototype.getAllKeys = function () {
  3806. if (this.count > 0) {
  3807. var keys = new Array(this.count);
  3808. for (var i = 0; i < this.count; i++) {
  3809. keys[i] = this._keys[i];
  3810. }
  3811. return keys;
  3812. }
  3813. else {
  3814. return undefined;
  3815. }
  3816. };
  3817. SmartCollection.prototype.getKeyByIndex = function (index) {
  3818. if (index < this.count && index > -1) {
  3819. return this._keys[index];
  3820. }
  3821. else {
  3822. return undefined;
  3823. }
  3824. };
  3825. SmartCollection.prototype.getItemByIndex = function (index) {
  3826. if (index < this.count && index > -1) {
  3827. return this.items[this._keys[index]];
  3828. }
  3829. else {
  3830. return undefined;
  3831. }
  3832. };
  3833. SmartCollection.prototype.empty = function () {
  3834. if (this.count > 0) {
  3835. this.count = 0;
  3836. this.items = {};
  3837. this._keys = new Array(this._initialCapacity);
  3838. }
  3839. };
  3840. SmartCollection.prototype.forEach = function (block) {
  3841. var key;
  3842. for (key in this.items) {
  3843. if (this.items.hasOwnProperty(key)) {
  3844. block(this.items[key]);
  3845. }
  3846. }
  3847. };
  3848. return SmartCollection;
  3849. })();
  3850. BABYLON.SmartCollection = SmartCollection;
  3851. })(BABYLON || (BABYLON = {}));
  3852. var BABYLON;
  3853. (function (BABYLON) {
  3854. // Screenshots
  3855. var screenshotCanvas;
  3856. var cloneValue = function (source, destinationObject) {
  3857. if (!source)
  3858. return null;
  3859. if (source instanceof BABYLON.Mesh) {
  3860. return null;
  3861. }
  3862. if (source instanceof BABYLON.SubMesh) {
  3863. return source.clone(destinationObject);
  3864. }
  3865. else if (source.clone) {
  3866. return source.clone();
  3867. }
  3868. return null;
  3869. };
  3870. var Tools = (function () {
  3871. function Tools() {
  3872. }
  3873. Tools.ToHex = function (i) {
  3874. var str = i.toString(16);
  3875. if (i <= 15) {
  3876. return ("0" + str).toUpperCase();
  3877. }
  3878. return str.toUpperCase();
  3879. };
  3880. Tools.SetImmediate = function (action) {
  3881. if (window.setImmediate) {
  3882. window.setImmediate(action);
  3883. }
  3884. else {
  3885. setTimeout(action, 1);
  3886. }
  3887. };
  3888. Tools.IsExponentOfTwo = function (value) {
  3889. var count = 1;
  3890. do {
  3891. count *= 2;
  3892. } while (count < value);
  3893. return count === value;
  3894. };
  3895. Tools.GetExponentOfTwo = function (value, max) {
  3896. var count = 1;
  3897. do {
  3898. count *= 2;
  3899. } while (count < value);
  3900. if (count > max)
  3901. count = max;
  3902. return count;
  3903. };
  3904. Tools.GetFilename = function (path) {
  3905. var index = path.lastIndexOf("/");
  3906. if (index < 0)
  3907. return path;
  3908. return path.substring(index + 1);
  3909. };
  3910. Tools.GetDOMTextContent = function (element) {
  3911. var result = "";
  3912. var child = element.firstChild;
  3913. while (child) {
  3914. if (child.nodeType === 3) {
  3915. result += child.textContent;
  3916. }
  3917. child = child.nextSibling;
  3918. }
  3919. return result;
  3920. };
  3921. Tools.ToDegrees = function (angle) {
  3922. return angle * 180 / Math.PI;
  3923. };
  3924. Tools.ToRadians = function (angle) {
  3925. return angle * Math.PI / 180;
  3926. };
  3927. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  3928. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  3929. var output = "";
  3930. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  3931. var i = 0;
  3932. var bytes = new Uint8Array(buffer);
  3933. while (i < bytes.length) {
  3934. chr1 = bytes[i++];
  3935. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  3936. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  3937. enc1 = chr1 >> 2;
  3938. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  3939. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  3940. enc4 = chr3 & 63;
  3941. if (isNaN(chr2)) {
  3942. enc3 = enc4 = 64;
  3943. }
  3944. else if (isNaN(chr3)) {
  3945. enc4 = 64;
  3946. }
  3947. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  3948. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  3949. }
  3950. return "data:image/png;base64," + output;
  3951. };
  3952. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3953. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3954. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3955. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3956. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3957. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3958. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3959. }
  3960. return {
  3961. minimum: minimum,
  3962. maximum: maximum
  3963. };
  3964. };
  3965. Tools.ExtractMinAndMax = function (positions, start, count) {
  3966. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3967. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3968. for (var index = start; index < start + count; index++) {
  3969. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3970. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3971. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3972. }
  3973. return {
  3974. minimum: minimum,
  3975. maximum: maximum
  3976. };
  3977. };
  3978. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3979. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3980. return undefined;
  3981. return Array.isArray(obj) ? obj : [obj];
  3982. };
  3983. // Misc.
  3984. Tools.GetPointerPrefix = function () {
  3985. var eventPrefix = "pointer";
  3986. // Check if hand.js is referenced or if the browser natively supports pointer events
  3987. if (!navigator.pointerEnabled) {
  3988. eventPrefix = "mouse";
  3989. }
  3990. return eventPrefix;
  3991. };
  3992. Tools.QueueNewFrame = function (func) {
  3993. if (window.requestAnimationFrame)
  3994. window.requestAnimationFrame(func);
  3995. else if (window.msRequestAnimationFrame)
  3996. window.msRequestAnimationFrame(func);
  3997. else if (window.webkitRequestAnimationFrame)
  3998. window.webkitRequestAnimationFrame(func);
  3999. else if (window.mozRequestAnimationFrame)
  4000. window.mozRequestAnimationFrame(func);
  4001. else if (window.oRequestAnimationFrame)
  4002. window.oRequestAnimationFrame(func);
  4003. else {
  4004. window.setTimeout(func, 16);
  4005. }
  4006. };
  4007. Tools.RequestFullscreen = function (element) {
  4008. if (element.requestFullscreen)
  4009. element.requestFullscreen();
  4010. else if (element.msRequestFullscreen)
  4011. element.msRequestFullscreen();
  4012. else if (element.webkitRequestFullscreen)
  4013. element.webkitRequestFullscreen();
  4014. else if (element.mozRequestFullScreen)
  4015. element.mozRequestFullScreen();
  4016. };
  4017. Tools.ExitFullscreen = function () {
  4018. if (document.exitFullscreen) {
  4019. document.exitFullscreen();
  4020. }
  4021. else if (document.mozCancelFullScreen) {
  4022. document.mozCancelFullScreen();
  4023. }
  4024. else if (document.webkitCancelFullScreen) {
  4025. document.webkitCancelFullScreen();
  4026. }
  4027. else if (document.msCancelFullScreen) {
  4028. document.msCancelFullScreen();
  4029. }
  4030. };
  4031. // External files
  4032. Tools.CleanUrl = function (url) {
  4033. url = url.replace(/#/mg, "%23");
  4034. return url;
  4035. };
  4036. Tools.LoadImage = function (url, onload, onerror, database) {
  4037. if (url instanceof ArrayBuffer) {
  4038. url = Tools.EncodeArrayBufferTobase64(url);
  4039. }
  4040. url = Tools.CleanUrl(url);
  4041. var img = new Image();
  4042. if (url.substr(0, 5) !== "data:") {
  4043. if (Tools.CorsBehavior) {
  4044. switch (typeof (Tools.CorsBehavior)) {
  4045. case "function":
  4046. var result = Tools.CorsBehavior(url);
  4047. if (result) {
  4048. img.crossOrigin = result;
  4049. }
  4050. break;
  4051. case "string":
  4052. default:
  4053. img.crossOrigin = Tools.CorsBehavior;
  4054. break;
  4055. }
  4056. }
  4057. }
  4058. img.onload = function () {
  4059. onload(img);
  4060. };
  4061. img.onerror = function (err) {
  4062. Tools.Error("Error while trying to load texture: " + url);
  4063. 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";
  4064. onload(img);
  4065. };
  4066. var noIndexedDB = function () {
  4067. img.src = url;
  4068. };
  4069. var loadFromIndexedDB = function () {
  4070. database.loadImageFromDB(url, img);
  4071. };
  4072. //ANY database to do!
  4073. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4074. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4075. }
  4076. else {
  4077. if (url.indexOf("file:") === -1) {
  4078. noIndexedDB();
  4079. }
  4080. else {
  4081. try {
  4082. var textureName = url.substring(5);
  4083. var blobURL;
  4084. try {
  4085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4086. }
  4087. catch (ex) {
  4088. // Chrome doesn't support oneTimeOnly parameter
  4089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4090. }
  4091. img.src = blobURL;
  4092. }
  4093. catch (e) {
  4094. img.src = null;
  4095. }
  4096. }
  4097. }
  4098. return img;
  4099. };
  4100. //ANY
  4101. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4102. url = Tools.CleanUrl(url);
  4103. var noIndexedDB = function () {
  4104. var request = new XMLHttpRequest();
  4105. var loadUrl = Tools.BaseUrl + url;
  4106. request.open('GET', loadUrl, true);
  4107. if (useArrayBuffer) {
  4108. request.responseType = "arraybuffer";
  4109. }
  4110. request.onprogress = progressCallBack;
  4111. request.onreadystatechange = function () {
  4112. if (request.readyState === 4) {
  4113. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4114. callback(!useArrayBuffer ? request.responseText : request.response);
  4115. }
  4116. else {
  4117. if (onError) {
  4118. onError();
  4119. }
  4120. else {
  4121. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4122. }
  4123. }
  4124. }
  4125. };
  4126. request.send(null);
  4127. };
  4128. var loadFromIndexedDB = function () {
  4129. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4130. };
  4131. if (url.indexOf("file:") !== -1) {
  4132. var fileName = url.substring(5);
  4133. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4134. }
  4135. else {
  4136. // Caching all files
  4137. if (database && database.enableSceneOffline) {
  4138. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4139. }
  4140. else {
  4141. noIndexedDB();
  4142. }
  4143. }
  4144. };
  4145. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4146. var reader = new FileReader();
  4147. reader.onload = function (e) {
  4148. //target doesn't have result from ts 1.3
  4149. callback(e.target['result']);
  4150. };
  4151. reader.onprogress = progressCallback;
  4152. reader.readAsDataURL(fileToLoad);
  4153. };
  4154. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4155. var reader = new FileReader();
  4156. reader.onerror = function (e) {
  4157. Tools.Log("Error while reading file: " + fileToLoad.name);
  4158. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4159. };
  4160. reader.onload = function (e) {
  4161. //target doesn't have result from ts 1.3
  4162. callback(e.target['result']);
  4163. };
  4164. reader.onprogress = progressCallBack;
  4165. if (!useArrayBuffer) {
  4166. // Asynchronous read
  4167. reader.readAsText(fileToLoad);
  4168. }
  4169. else {
  4170. reader.readAsArrayBuffer(fileToLoad);
  4171. }
  4172. };
  4173. //returns a downloadable url to a file content.
  4174. Tools.FileAsURL = function (content) {
  4175. var fileBlob = new Blob([content]);
  4176. var url = window.URL || window.webkitURL;
  4177. var link = url.createObjectURL(fileBlob);
  4178. return link;
  4179. };
  4180. // Misc.
  4181. Tools.Clamp = function (value, min, max) {
  4182. if (min === void 0) { min = 0; }
  4183. if (max === void 0) { max = 1; }
  4184. return Math.min(max, Math.max(min, value));
  4185. };
  4186. // Returns -1 when value is a negative number and
  4187. // +1 when value is a positive number.
  4188. Tools.Sign = function (value) {
  4189. value = +value; // convert to a number
  4190. if (value === 0 || isNaN(value))
  4191. return value;
  4192. return value > 0 ? 1 : -1;
  4193. };
  4194. Tools.Format = function (value, decimals) {
  4195. if (decimals === void 0) { decimals = 2; }
  4196. return value.toFixed(decimals);
  4197. };
  4198. Tools.CheckExtends = function (v, min, max) {
  4199. if (v.x < min.x)
  4200. min.x = v.x;
  4201. if (v.y < min.y)
  4202. min.y = v.y;
  4203. if (v.z < min.z)
  4204. min.z = v.z;
  4205. if (v.x > max.x)
  4206. max.x = v.x;
  4207. if (v.y > max.y)
  4208. max.y = v.y;
  4209. if (v.z > max.z)
  4210. max.z = v.z;
  4211. };
  4212. Tools.WithinEpsilon = function (a, b, epsilon) {
  4213. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4214. var num = a - b;
  4215. return -epsilon <= num && num <= epsilon;
  4216. };
  4217. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4218. for (var prop in source) {
  4219. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4220. continue;
  4221. }
  4222. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4223. continue;
  4224. }
  4225. var sourceValue = source[prop];
  4226. var typeOfSourceValue = typeof sourceValue;
  4227. if (typeOfSourceValue === "function") {
  4228. continue;
  4229. }
  4230. if (typeOfSourceValue === "object") {
  4231. if (sourceValue instanceof Array) {
  4232. destination[prop] = [];
  4233. if (sourceValue.length > 0) {
  4234. if (typeof sourceValue[0] == "object") {
  4235. for (var index = 0; index < sourceValue.length; index++) {
  4236. var clonedValue = cloneValue(sourceValue[index], destination);
  4237. if (destination[prop].indexOf(clonedValue) === -1) {
  4238. destination[prop].push(clonedValue);
  4239. }
  4240. }
  4241. }
  4242. else {
  4243. destination[prop] = sourceValue.slice(0);
  4244. }
  4245. }
  4246. }
  4247. else {
  4248. destination[prop] = cloneValue(sourceValue, destination);
  4249. }
  4250. }
  4251. else {
  4252. destination[prop] = sourceValue;
  4253. }
  4254. }
  4255. };
  4256. Tools.IsEmpty = function (obj) {
  4257. for (var i in obj) {
  4258. return false;
  4259. }
  4260. return true;
  4261. };
  4262. Tools.RegisterTopRootEvents = function (events) {
  4263. for (var index = 0; index < events.length; index++) {
  4264. var event = events[index];
  4265. window.addEventListener(event.name, event.handler, false);
  4266. try {
  4267. if (window.parent) {
  4268. window.parent.addEventListener(event.name, event.handler, false);
  4269. }
  4270. }
  4271. catch (e) {
  4272. }
  4273. }
  4274. };
  4275. Tools.UnregisterTopRootEvents = function (events) {
  4276. for (var index = 0; index < events.length; index++) {
  4277. var event = events[index];
  4278. window.removeEventListener(event.name, event.handler);
  4279. try {
  4280. if (window.parent) {
  4281. window.parent.removeEventListener(event.name, event.handler);
  4282. }
  4283. }
  4284. catch (e) {
  4285. }
  4286. }
  4287. };
  4288. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4289. // Read the contents of the framebuffer
  4290. var numberOfChannelsByLine = width * 4;
  4291. var halfHeight = height / 2;
  4292. //Reading datas from WebGL
  4293. var data = engine.readPixels(0, 0, width, height);
  4294. //To flip image on Y axis.
  4295. for (var i = 0; i < halfHeight; i++) {
  4296. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4297. var currentCell = j + i * numberOfChannelsByLine;
  4298. var targetLine = height - i - 1;
  4299. var targetCell = j + targetLine * numberOfChannelsByLine;
  4300. var temp = data[currentCell];
  4301. data[currentCell] = data[targetCell];
  4302. data[targetCell] = temp;
  4303. }
  4304. }
  4305. // Create a 2D canvas to store the result
  4306. if (!screenshotCanvas) {
  4307. screenshotCanvas = document.createElement('canvas');
  4308. }
  4309. screenshotCanvas.width = width;
  4310. screenshotCanvas.height = height;
  4311. var context = screenshotCanvas.getContext('2d');
  4312. // Copy the pixels to a 2D canvas
  4313. var imageData = context.createImageData(width, height);
  4314. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4315. var castData = imageData.data;
  4316. castData.set(data);
  4317. context.putImageData(imageData, 0, 0);
  4318. var base64Image = screenshotCanvas.toDataURL();
  4319. if (successCallback) {
  4320. successCallback(base64Image);
  4321. }
  4322. else {
  4323. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4324. if (("download" in document.createElement("a"))) {
  4325. var a = window.document.createElement("a");
  4326. a.href = base64Image;
  4327. var date = new Date();
  4328. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4329. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4330. window.document.body.appendChild(a);
  4331. a.addEventListener("click", function () {
  4332. a.parentElement.removeChild(a);
  4333. });
  4334. a.click();
  4335. }
  4336. else {
  4337. var newWindow = window.open("");
  4338. var img = newWindow.document.createElement("img");
  4339. img.src = base64Image;
  4340. newWindow.document.body.appendChild(img);
  4341. }
  4342. }
  4343. };
  4344. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4345. var width;
  4346. var height;
  4347. //If a precision value is specified
  4348. if (size.precision) {
  4349. width = Math.round(engine.getRenderWidth() * size.precision);
  4350. height = Math.round(width / engine.getAspectRatio(camera));
  4351. size = { width: width, height: height };
  4352. }
  4353. else if (size.width && size.height) {
  4354. width = size.width;
  4355. height = size.height;
  4356. }
  4357. else if (size.width && !size.height) {
  4358. width = size.width;
  4359. height = Math.round(width / engine.getAspectRatio(camera));
  4360. size = { width: width, height: height };
  4361. }
  4362. else if (size.height && !size.width) {
  4363. height = size.height;
  4364. width = Math.round(height * engine.getAspectRatio(camera));
  4365. size = { width: width, height: height };
  4366. }
  4367. else if (!isNaN(size)) {
  4368. height = size;
  4369. width = size;
  4370. }
  4371. else {
  4372. Tools.Error("Invalid 'size' parameter !");
  4373. return;
  4374. }
  4375. var scene = camera.getScene();
  4376. var previousCamera = null;
  4377. if (scene.activeCamera !== camera) {
  4378. previousCamera = scene.activeCamera;
  4379. scene.activeCamera = camera;
  4380. }
  4381. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4382. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4383. texture.renderList = scene.meshes;
  4384. texture.onAfterRender = function () {
  4385. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4386. };
  4387. scene.incrementRenderId();
  4388. texture.render(true);
  4389. texture.dispose();
  4390. if (previousCamera) {
  4391. scene.activeCamera = previousCamera;
  4392. }
  4393. };
  4394. // XHR response validator for local file scenario
  4395. Tools.ValidateXHRData = function (xhr, dataType) {
  4396. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4397. if (dataType === void 0) { dataType = 7; }
  4398. try {
  4399. if (dataType & 1) {
  4400. if (xhr.responseText && xhr.responseText.length > 0) {
  4401. return true;
  4402. }
  4403. else if (dataType === 1) {
  4404. return false;
  4405. }
  4406. }
  4407. if (dataType & 2) {
  4408. // Check header width and height since there is no "TGA" magic number
  4409. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4410. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4411. return true;
  4412. }
  4413. else if (dataType === 2) {
  4414. return false;
  4415. }
  4416. }
  4417. if (dataType & 4) {
  4418. // Check for the "DDS" magic number
  4419. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4420. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4421. return true;
  4422. }
  4423. else {
  4424. return false;
  4425. }
  4426. }
  4427. }
  4428. catch (e) {
  4429. }
  4430. return false;
  4431. };
  4432. Object.defineProperty(Tools, "NoneLogLevel", {
  4433. get: function () {
  4434. return Tools._NoneLogLevel;
  4435. },
  4436. enumerable: true,
  4437. configurable: true
  4438. });
  4439. Object.defineProperty(Tools, "MessageLogLevel", {
  4440. get: function () {
  4441. return Tools._MessageLogLevel;
  4442. },
  4443. enumerable: true,
  4444. configurable: true
  4445. });
  4446. Object.defineProperty(Tools, "WarningLogLevel", {
  4447. get: function () {
  4448. return Tools._WarningLogLevel;
  4449. },
  4450. enumerable: true,
  4451. configurable: true
  4452. });
  4453. Object.defineProperty(Tools, "ErrorLogLevel", {
  4454. get: function () {
  4455. return Tools._ErrorLogLevel;
  4456. },
  4457. enumerable: true,
  4458. configurable: true
  4459. });
  4460. Object.defineProperty(Tools, "AllLogLevel", {
  4461. get: function () {
  4462. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4463. },
  4464. enumerable: true,
  4465. configurable: true
  4466. });
  4467. Tools._AddLogEntry = function (entry) {
  4468. Tools._LogCache = entry + Tools._LogCache;
  4469. if (Tools.OnNewCacheEntry) {
  4470. Tools.OnNewCacheEntry(entry);
  4471. }
  4472. };
  4473. Tools._FormatMessage = function (message) {
  4474. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4475. var date = new Date();
  4476. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4477. };
  4478. Tools._LogDisabled = function (message) {
  4479. // nothing to do
  4480. };
  4481. Tools._LogEnabled = function (message) {
  4482. var formattedMessage = Tools._FormatMessage(message);
  4483. console.log("BJS - " + formattedMessage);
  4484. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4485. Tools._AddLogEntry(entry);
  4486. };
  4487. Tools._WarnDisabled = function (message) {
  4488. // nothing to do
  4489. };
  4490. Tools._WarnEnabled = function (message) {
  4491. var formattedMessage = Tools._FormatMessage(message);
  4492. console.warn("BJS - " + formattedMessage);
  4493. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4494. Tools._AddLogEntry(entry);
  4495. };
  4496. Tools._ErrorDisabled = function (message) {
  4497. // nothing to do
  4498. };
  4499. Tools._ErrorEnabled = function (message) {
  4500. Tools.errorsCount++;
  4501. var formattedMessage = Tools._FormatMessage(message);
  4502. console.error("BJS - " + formattedMessage);
  4503. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4504. Tools._AddLogEntry(entry);
  4505. };
  4506. Object.defineProperty(Tools, "LogCache", {
  4507. get: function () {
  4508. return Tools._LogCache;
  4509. },
  4510. enumerable: true,
  4511. configurable: true
  4512. });
  4513. Tools.ClearLogCache = function () {
  4514. Tools._LogCache = "";
  4515. Tools.errorsCount = 0;
  4516. };
  4517. Object.defineProperty(Tools, "LogLevels", {
  4518. set: function (level) {
  4519. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4520. Tools.Log = Tools._LogEnabled;
  4521. }
  4522. else {
  4523. Tools.Log = Tools._LogDisabled;
  4524. }
  4525. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4526. Tools.Warn = Tools._WarnEnabled;
  4527. }
  4528. else {
  4529. Tools.Warn = Tools._WarnDisabled;
  4530. }
  4531. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4532. Tools.Error = Tools._ErrorEnabled;
  4533. }
  4534. else {
  4535. Tools.Error = Tools._ErrorDisabled;
  4536. }
  4537. },
  4538. enumerable: true,
  4539. configurable: true
  4540. });
  4541. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4542. get: function () {
  4543. return Tools._PerformanceNoneLogLevel;
  4544. },
  4545. enumerable: true,
  4546. configurable: true
  4547. });
  4548. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4549. get: function () {
  4550. return Tools._PerformanceUserMarkLogLevel;
  4551. },
  4552. enumerable: true,
  4553. configurable: true
  4554. });
  4555. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4556. get: function () {
  4557. return Tools._PerformanceConsoleLogLevel;
  4558. },
  4559. enumerable: true,
  4560. configurable: true
  4561. });
  4562. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4563. set: function (level) {
  4564. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4565. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4566. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4567. return;
  4568. }
  4569. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4570. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4571. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4572. return;
  4573. }
  4574. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4575. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4576. },
  4577. enumerable: true,
  4578. configurable: true
  4579. });
  4580. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4581. };
  4582. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4583. };
  4584. Tools._StartUserMark = function (counterName, condition) {
  4585. if (condition === void 0) { condition = true; }
  4586. if (!condition || !Tools._performance.mark) {
  4587. return;
  4588. }
  4589. Tools._performance.mark(counterName + "-Begin");
  4590. };
  4591. Tools._EndUserMark = function (counterName, condition) {
  4592. if (condition === void 0) { condition = true; }
  4593. if (!condition || !Tools._performance.mark) {
  4594. return;
  4595. }
  4596. Tools._performance.mark(counterName + "-End");
  4597. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4598. };
  4599. Tools._StartPerformanceConsole = function (counterName, condition) {
  4600. if (condition === void 0) { condition = true; }
  4601. if (!condition) {
  4602. return;
  4603. }
  4604. Tools._StartUserMark(counterName, condition);
  4605. if (console.time) {
  4606. console.time(counterName);
  4607. }
  4608. };
  4609. Tools._EndPerformanceConsole = function (counterName, condition) {
  4610. if (condition === void 0) { condition = true; }
  4611. if (!condition) {
  4612. return;
  4613. }
  4614. Tools._EndUserMark(counterName, condition);
  4615. if (console.time) {
  4616. console.timeEnd(counterName);
  4617. }
  4618. };
  4619. Object.defineProperty(Tools, "Now", {
  4620. get: function () {
  4621. if (window.performance && window.performance.now) {
  4622. return window.performance.now();
  4623. }
  4624. return new Date().getTime();
  4625. },
  4626. enumerable: true,
  4627. configurable: true
  4628. });
  4629. Tools.BaseUrl = "";
  4630. Tools.CorsBehavior = "anonymous";
  4631. // Logs
  4632. Tools._NoneLogLevel = 0;
  4633. Tools._MessageLogLevel = 1;
  4634. Tools._WarningLogLevel = 2;
  4635. Tools._ErrorLogLevel = 4;
  4636. Tools._LogCache = "";
  4637. Tools.errorsCount = 0;
  4638. Tools.Log = Tools._LogEnabled;
  4639. Tools.Warn = Tools._WarnEnabled;
  4640. Tools.Error = Tools._ErrorEnabled;
  4641. // Performances
  4642. Tools._PerformanceNoneLogLevel = 0;
  4643. Tools._PerformanceUserMarkLogLevel = 1;
  4644. Tools._PerformanceConsoleLogLevel = 2;
  4645. Tools._performance = window.performance;
  4646. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4647. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4648. return Tools;
  4649. })();
  4650. BABYLON.Tools = Tools;
  4651. /**
  4652. * An implementation of a loop for asynchronous functions.
  4653. */
  4654. var AsyncLoop = (function () {
  4655. /**
  4656. * Constroctor.
  4657. * @param iterations the number of iterations.
  4658. * @param _fn the function to run each iteration
  4659. * @param _successCallback the callback that will be called upon succesful execution
  4660. * @param offset starting offset.
  4661. */
  4662. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4663. if (offset === void 0) { offset = 0; }
  4664. this.iterations = iterations;
  4665. this._fn = _fn;
  4666. this._successCallback = _successCallback;
  4667. this.index = offset - 1;
  4668. this._done = false;
  4669. }
  4670. /**
  4671. * Execute the next iteration. Must be called after the last iteration was finished.
  4672. */
  4673. AsyncLoop.prototype.executeNext = function () {
  4674. if (!this._done) {
  4675. if (this.index + 1 < this.iterations) {
  4676. ++this.index;
  4677. this._fn(this);
  4678. }
  4679. else {
  4680. this.breakLoop();
  4681. }
  4682. }
  4683. };
  4684. /**
  4685. * Break the loop and run the success callback.
  4686. */
  4687. AsyncLoop.prototype.breakLoop = function () {
  4688. this._done = true;
  4689. this._successCallback();
  4690. };
  4691. /**
  4692. * Helper function
  4693. */
  4694. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4695. if (offset === void 0) { offset = 0; }
  4696. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4697. loop.executeNext();
  4698. return loop;
  4699. };
  4700. /**
  4701. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4702. * @param iterations total number of iterations
  4703. * @param syncedIterations number of synchronous iterations in each async iteration.
  4704. * @param fn the function to call each iteration.
  4705. * @param callback a success call back that will be called when iterating stops.
  4706. * @param breakFunction a break condition (optional)
  4707. * @param timeout timeout settings for the setTimeout function. default - 0.
  4708. * @constructor
  4709. */
  4710. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4711. if (timeout === void 0) { timeout = 0; }
  4712. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4713. if (breakFunction && breakFunction())
  4714. loop.breakLoop();
  4715. else {
  4716. setTimeout(function () {
  4717. for (var i = 0; i < syncedIterations; ++i) {
  4718. var iteration = (loop.index * syncedIterations) + i;
  4719. if (iteration >= iterations)
  4720. break;
  4721. fn(iteration);
  4722. if (breakFunction && breakFunction()) {
  4723. loop.breakLoop();
  4724. break;
  4725. }
  4726. }
  4727. loop.executeNext();
  4728. }, timeout);
  4729. }
  4730. }, callback);
  4731. };
  4732. return AsyncLoop;
  4733. })();
  4734. BABYLON.AsyncLoop = AsyncLoop;
  4735. })(BABYLON || (BABYLON = {}));
  4736. var BABYLON;
  4737. (function (BABYLON) {
  4738. var _DepthCullingState = (function () {
  4739. function _DepthCullingState() {
  4740. this._isDepthTestDirty = false;
  4741. this._isDepthMaskDirty = false;
  4742. this._isDepthFuncDirty = false;
  4743. this._isCullFaceDirty = false;
  4744. this._isCullDirty = false;
  4745. this._isZOffsetDirty = false;
  4746. }
  4747. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4748. get: function () {
  4749. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4750. },
  4751. enumerable: true,
  4752. configurable: true
  4753. });
  4754. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4755. get: function () {
  4756. return this._zOffset;
  4757. },
  4758. set: function (value) {
  4759. if (this._zOffset === value) {
  4760. return;
  4761. }
  4762. this._zOffset = value;
  4763. this._isZOffsetDirty = true;
  4764. },
  4765. enumerable: true,
  4766. configurable: true
  4767. });
  4768. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4769. get: function () {
  4770. return this._cullFace;
  4771. },
  4772. set: function (value) {
  4773. if (this._cullFace === value) {
  4774. return;
  4775. }
  4776. this._cullFace = value;
  4777. this._isCullFaceDirty = true;
  4778. },
  4779. enumerable: true,
  4780. configurable: true
  4781. });
  4782. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4783. get: function () {
  4784. return this._cull;
  4785. },
  4786. set: function (value) {
  4787. if (this._cull === value) {
  4788. return;
  4789. }
  4790. this._cull = value;
  4791. this._isCullDirty = true;
  4792. },
  4793. enumerable: true,
  4794. configurable: true
  4795. });
  4796. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4797. get: function () {
  4798. return this._depthFunc;
  4799. },
  4800. set: function (value) {
  4801. if (this._depthFunc === value) {
  4802. return;
  4803. }
  4804. this._depthFunc = value;
  4805. this._isDepthFuncDirty = true;
  4806. },
  4807. enumerable: true,
  4808. configurable: true
  4809. });
  4810. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4811. get: function () {
  4812. return this._depthMask;
  4813. },
  4814. set: function (value) {
  4815. if (this._depthMask === value) {
  4816. return;
  4817. }
  4818. this._depthMask = value;
  4819. this._isDepthMaskDirty = true;
  4820. },
  4821. enumerable: true,
  4822. configurable: true
  4823. });
  4824. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4825. get: function () {
  4826. return this._depthTest;
  4827. },
  4828. set: function (value) {
  4829. if (this._depthTest === value) {
  4830. return;
  4831. }
  4832. this._depthTest = value;
  4833. this._isDepthTestDirty = true;
  4834. },
  4835. enumerable: true,
  4836. configurable: true
  4837. });
  4838. _DepthCullingState.prototype.reset = function () {
  4839. this._depthMask = true;
  4840. this._depthTest = true;
  4841. this._depthFunc = null;
  4842. this._cull = null;
  4843. this._cullFace = null;
  4844. this._zOffset = 0;
  4845. this._isDepthTestDirty = true;
  4846. this._isDepthMaskDirty = true;
  4847. this._isDepthFuncDirty = false;
  4848. this._isCullFaceDirty = false;
  4849. this._isCullDirty = false;
  4850. this._isZOffsetDirty = false;
  4851. };
  4852. _DepthCullingState.prototype.apply = function (gl) {
  4853. if (!this.isDirty) {
  4854. return;
  4855. }
  4856. // Cull
  4857. if (this._isCullDirty) {
  4858. if (this.cull) {
  4859. gl.enable(gl.CULL_FACE);
  4860. }
  4861. else {
  4862. gl.disable(gl.CULL_FACE);
  4863. }
  4864. this._isCullDirty = false;
  4865. }
  4866. // Cull face
  4867. if (this._isCullFaceDirty) {
  4868. gl.cullFace(this.cullFace);
  4869. this._isCullFaceDirty = false;
  4870. }
  4871. // Depth mask
  4872. if (this._isDepthMaskDirty) {
  4873. gl.depthMask(this.depthMask);
  4874. this._isDepthMaskDirty = false;
  4875. }
  4876. // Depth test
  4877. if (this._isDepthTestDirty) {
  4878. if (this.depthTest) {
  4879. gl.enable(gl.DEPTH_TEST);
  4880. }
  4881. else {
  4882. gl.disable(gl.DEPTH_TEST);
  4883. }
  4884. this._isDepthTestDirty = false;
  4885. }
  4886. // Depth func
  4887. if (this._isDepthFuncDirty) {
  4888. gl.depthFunc(this.depthFunc);
  4889. this._isDepthFuncDirty = false;
  4890. }
  4891. // zOffset
  4892. if (this._isZOffsetDirty) {
  4893. if (this.zOffset) {
  4894. gl.enable(gl.POLYGON_OFFSET_FILL);
  4895. gl.polygonOffset(this.zOffset, 0);
  4896. }
  4897. else {
  4898. gl.disable(gl.POLYGON_OFFSET_FILL);
  4899. }
  4900. this._isZOffsetDirty = false;
  4901. }
  4902. };
  4903. return _DepthCullingState;
  4904. })();
  4905. BABYLON._DepthCullingState = _DepthCullingState;
  4906. var _AlphaState = (function () {
  4907. function _AlphaState() {
  4908. this._isAlphaBlendDirty = false;
  4909. this._isBlendFunctionParametersDirty = false;
  4910. this._alphaBlend = false;
  4911. this._blendFunctionParameters = new Array(4);
  4912. }
  4913. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4914. get: function () {
  4915. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4916. },
  4917. enumerable: true,
  4918. configurable: true
  4919. });
  4920. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4921. get: function () {
  4922. return this._alphaBlend;
  4923. },
  4924. set: function (value) {
  4925. if (this._alphaBlend === value) {
  4926. return;
  4927. }
  4928. this._alphaBlend = value;
  4929. this._isAlphaBlendDirty = true;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4935. if (this._blendFunctionParameters[0] === value0 &&
  4936. this._blendFunctionParameters[1] === value1 &&
  4937. this._blendFunctionParameters[2] === value2 &&
  4938. this._blendFunctionParameters[3] === value3) {
  4939. return;
  4940. }
  4941. this._blendFunctionParameters[0] = value0;
  4942. this._blendFunctionParameters[1] = value1;
  4943. this._blendFunctionParameters[2] = value2;
  4944. this._blendFunctionParameters[3] = value3;
  4945. this._isBlendFunctionParametersDirty = true;
  4946. };
  4947. _AlphaState.prototype.reset = function () {
  4948. this._alphaBlend = false;
  4949. this._blendFunctionParameters[0] = null;
  4950. this._blendFunctionParameters[1] = null;
  4951. this._blendFunctionParameters[2] = null;
  4952. this._blendFunctionParameters[3] = null;
  4953. this._isAlphaBlendDirty = true;
  4954. this._isBlendFunctionParametersDirty = false;
  4955. };
  4956. _AlphaState.prototype.apply = function (gl) {
  4957. if (!this.isDirty) {
  4958. return;
  4959. }
  4960. // Alpha blend
  4961. if (this._isAlphaBlendDirty) {
  4962. if (this._alphaBlend) {
  4963. gl.enable(gl.BLEND);
  4964. }
  4965. else {
  4966. gl.disable(gl.BLEND);
  4967. }
  4968. this._isAlphaBlendDirty = false;
  4969. }
  4970. // Alpha function
  4971. if (this._isBlendFunctionParametersDirty) {
  4972. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4973. this._isBlendFunctionParametersDirty = false;
  4974. }
  4975. };
  4976. return _AlphaState;
  4977. })();
  4978. BABYLON._AlphaState = _AlphaState;
  4979. var compileShader = function (gl, source, type, defines) {
  4980. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4981. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4982. gl.compileShader(shader);
  4983. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4984. throw new Error(gl.getShaderInfoLog(shader));
  4985. }
  4986. return shader;
  4987. };
  4988. var getWebGLTextureType = function (gl, type) {
  4989. var textureType = gl.UNSIGNED_BYTE;
  4990. if (type === Engine.TEXTURETYPE_FLOAT)
  4991. textureType = gl.FLOAT;
  4992. return textureType;
  4993. };
  4994. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4995. var magFilter = gl.NEAREST;
  4996. var minFilter = gl.NEAREST;
  4997. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4998. magFilter = gl.LINEAR;
  4999. if (generateMipMaps) {
  5000. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5001. }
  5002. else {
  5003. minFilter = gl.LINEAR;
  5004. }
  5005. }
  5006. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5007. magFilter = gl.LINEAR;
  5008. if (generateMipMaps) {
  5009. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5010. }
  5011. else {
  5012. minFilter = gl.LINEAR;
  5013. }
  5014. }
  5015. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5016. magFilter = gl.NEAREST;
  5017. if (generateMipMaps) {
  5018. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5019. }
  5020. else {
  5021. minFilter = gl.NEAREST;
  5022. }
  5023. }
  5024. return {
  5025. min: minFilter,
  5026. mag: magFilter
  5027. };
  5028. };
  5029. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5031. var engine = scene.getEngine();
  5032. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5033. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5034. gl.bindTexture(gl.TEXTURE_2D, texture);
  5035. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5036. texture._baseWidth = width;
  5037. texture._baseHeight = height;
  5038. texture._width = potWidth;
  5039. texture._height = potHeight;
  5040. texture.isReady = true;
  5041. processFunction(potWidth, potHeight);
  5042. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5044. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5045. if (!noMipmap && !isCompressed) {
  5046. gl.generateMipmap(gl.TEXTURE_2D);
  5047. }
  5048. gl.bindTexture(gl.TEXTURE_2D, null);
  5049. engine.resetTextureCache();
  5050. scene._removePendingData(texture);
  5051. };
  5052. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5053. var onload = function () {
  5054. loadedImages[index] = img;
  5055. loadedImages._internalCount++;
  5056. scene._removePendingData(img);
  5057. if (loadedImages._internalCount === 6) {
  5058. onfinish(loadedImages);
  5059. }
  5060. };
  5061. var onerror = function () {
  5062. scene._removePendingData(img);
  5063. };
  5064. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5065. scene._addPendingData(img);
  5066. };
  5067. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5068. var loadedImages = [];
  5069. loadedImages._internalCount = 0;
  5070. for (var index = 0; index < 6; index++) {
  5071. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5072. }
  5073. };
  5074. var EngineCapabilities = (function () {
  5075. function EngineCapabilities() {
  5076. }
  5077. return EngineCapabilities;
  5078. })();
  5079. BABYLON.EngineCapabilities = EngineCapabilities;
  5080. /**
  5081. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5082. */
  5083. var Engine = (function () {
  5084. /**
  5085. * @constructor
  5086. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5087. * @param {boolean} [antialias] - enable antialias
  5088. * @param options - further options to be sent to the getContext function
  5089. */
  5090. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5091. var _this = this;
  5092. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5093. // Public members
  5094. this.isFullscreen = false;
  5095. this.isPointerLock = false;
  5096. this.cullBackFaces = true;
  5097. this.renderEvenInBackground = true;
  5098. // To enable/disable IDB support and avoid XHR on .manifest
  5099. this.enableOfflineSupport = true;
  5100. this.scenes = new Array();
  5101. this._windowIsBackground = false;
  5102. this._drawCalls = 0;
  5103. this._renderingQueueLaunched = false;
  5104. this._activeRenderLoops = [];
  5105. // FPS
  5106. this.fpsRange = 60;
  5107. this.previousFramesDuration = [];
  5108. this.fps = 60;
  5109. this.deltaTime = 0;
  5110. // States
  5111. this._depthCullingState = new _DepthCullingState();
  5112. this._alphaState = new _AlphaState();
  5113. this._alphaMode = Engine.ALPHA_DISABLE;
  5114. // Cache
  5115. this._loadedTexturesCache = new Array();
  5116. this._maxTextureChannels = 16;
  5117. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5118. this._compiledEffects = {};
  5119. this._uintIndicesCurrentlySet = false;
  5120. this._renderingCanvas = canvas;
  5121. options = options || {};
  5122. options.antialias = antialias;
  5123. if (options.preserveDrawingBuffer === undefined) {
  5124. options.preserveDrawingBuffer = false;
  5125. }
  5126. // GL
  5127. try {
  5128. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5129. }
  5130. catch (e) {
  5131. throw new Error("WebGL not supported");
  5132. }
  5133. if (!this._gl) {
  5134. throw new Error("WebGL not supported");
  5135. }
  5136. this._onBlur = function () {
  5137. _this._windowIsBackground = true;
  5138. };
  5139. this._onFocus = function () {
  5140. _this._windowIsBackground = false;
  5141. };
  5142. window.addEventListener("blur", this._onBlur);
  5143. window.addEventListener("focus", this._onFocus);
  5144. // Viewport
  5145. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5146. this.resize();
  5147. // Caps
  5148. this._caps = new EngineCapabilities();
  5149. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5150. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5151. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5152. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5153. // Infos
  5154. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5155. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5156. if (rendererInfo != null) {
  5157. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5158. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5159. }
  5160. if (!this._glVendor) {
  5161. this._glVendor = "Unknown vendor";
  5162. }
  5163. if (!this._glRenderer) {
  5164. this._glRenderer = "Unknown renderer";
  5165. }
  5166. // Extensions
  5167. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5168. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5169. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5170. 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');
  5171. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5172. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5173. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5174. this._caps.highPrecisionShaderSupported = true;
  5175. if (this._gl.getShaderPrecisionFormat) {
  5176. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5177. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5178. }
  5179. // Depth buffer
  5180. this.setDepthBuffer(true);
  5181. this.setDepthFunctionToLessOrEqual();
  5182. this.setDepthWrite(true);
  5183. // Fullscreen
  5184. this._onFullscreenChange = function () {
  5185. if (document.fullscreen !== undefined) {
  5186. _this.isFullscreen = document.fullscreen;
  5187. }
  5188. else if (document.mozFullScreen !== undefined) {
  5189. _this.isFullscreen = document.mozFullScreen;
  5190. }
  5191. else if (document.webkitIsFullScreen !== undefined) {
  5192. _this.isFullscreen = document.webkitIsFullScreen;
  5193. }
  5194. else if (document.msIsFullScreen !== undefined) {
  5195. _this.isFullscreen = document.msIsFullScreen;
  5196. }
  5197. // Pointer lock
  5198. if (_this.isFullscreen && _this._pointerLockRequested) {
  5199. canvas.requestPointerLock = canvas.requestPointerLock ||
  5200. canvas.msRequestPointerLock ||
  5201. canvas.mozRequestPointerLock ||
  5202. canvas.webkitRequestPointerLock;
  5203. if (canvas.requestPointerLock) {
  5204. canvas.requestPointerLock();
  5205. }
  5206. }
  5207. };
  5208. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5209. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5210. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5211. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5212. // Pointer lock
  5213. this._onPointerLockChange = function () {
  5214. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5215. document.webkitPointerLockElement === canvas ||
  5216. document.msPointerLockElement === canvas ||
  5217. document.pointerLockElement === canvas);
  5218. };
  5219. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5220. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5221. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5222. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5223. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5224. Engine.audioEngine = new BABYLON.AudioEngine();
  5225. }
  5226. //default loading screen
  5227. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5228. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5229. }
  5230. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5231. get: function () {
  5232. return Engine._ALPHA_DISABLE;
  5233. },
  5234. enumerable: true,
  5235. configurable: true
  5236. });
  5237. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5238. get: function () {
  5239. return Engine._ALPHA_ONEONE;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(Engine, "ALPHA_ADD", {
  5245. get: function () {
  5246. return Engine._ALPHA_ADD;
  5247. },
  5248. enumerable: true,
  5249. configurable: true
  5250. });
  5251. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5252. get: function () {
  5253. return Engine._ALPHA_COMBINE;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5259. get: function () {
  5260. return Engine._ALPHA_SUBTRACT;
  5261. },
  5262. enumerable: true,
  5263. configurable: true
  5264. });
  5265. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5266. get: function () {
  5267. return Engine._ALPHA_MULTIPLY;
  5268. },
  5269. enumerable: true,
  5270. configurable: true
  5271. });
  5272. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5273. get: function () {
  5274. return Engine._ALPHA_MAXIMIZED;
  5275. },
  5276. enumerable: true,
  5277. configurable: true
  5278. });
  5279. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5280. get: function () {
  5281. return Engine._DELAYLOADSTATE_NONE;
  5282. },
  5283. enumerable: true,
  5284. configurable: true
  5285. });
  5286. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5287. get: function () {
  5288. return Engine._DELAYLOADSTATE_LOADED;
  5289. },
  5290. enumerable: true,
  5291. configurable: true
  5292. });
  5293. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5294. get: function () {
  5295. return Engine._DELAYLOADSTATE_LOADING;
  5296. },
  5297. enumerable: true,
  5298. configurable: true
  5299. });
  5300. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5301. get: function () {
  5302. return Engine._DELAYLOADSTATE_NOTLOADED;
  5303. },
  5304. enumerable: true,
  5305. configurable: true
  5306. });
  5307. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5308. get: function () {
  5309. return Engine._TEXTUREFORMAT_ALPHA;
  5310. },
  5311. enumerable: true,
  5312. configurable: true
  5313. });
  5314. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5315. get: function () {
  5316. return Engine._TEXTUREFORMAT_LUMINANCE;
  5317. },
  5318. enumerable: true,
  5319. configurable: true
  5320. });
  5321. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5322. get: function () {
  5323. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5324. },
  5325. enumerable: true,
  5326. configurable: true
  5327. });
  5328. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5329. get: function () {
  5330. return Engine._TEXTUREFORMAT_RGB;
  5331. },
  5332. enumerable: true,
  5333. configurable: true
  5334. });
  5335. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5336. get: function () {
  5337. return Engine._TEXTUREFORMAT_RGBA;
  5338. },
  5339. enumerable: true,
  5340. configurable: true
  5341. });
  5342. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5343. get: function () {
  5344. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5345. },
  5346. enumerable: true,
  5347. configurable: true
  5348. });
  5349. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5350. get: function () {
  5351. return Engine._TEXTURETYPE_FLOAT;
  5352. },
  5353. enumerable: true,
  5354. configurable: true
  5355. });
  5356. Object.defineProperty(Engine, "Version", {
  5357. get: function () {
  5358. return "2.3.0-alpha";
  5359. },
  5360. enumerable: true,
  5361. configurable: true
  5362. });
  5363. Engine.prototype._prepareWorkingCanvas = function () {
  5364. if (this._workingCanvas) {
  5365. return;
  5366. }
  5367. this._workingCanvas = document.createElement("canvas");
  5368. this._workingContext = this._workingCanvas.getContext("2d");
  5369. };
  5370. Engine.prototype.resetTextureCache = function () {
  5371. for (var index = 0; index < this._maxTextureChannels; index++) {
  5372. this._activeTexturesCache[index] = null;
  5373. }
  5374. };
  5375. Engine.prototype.getGlInfo = function () {
  5376. return {
  5377. vendor: this._glVendor,
  5378. renderer: this._glRenderer,
  5379. version: this._glVersion
  5380. };
  5381. };
  5382. Engine.prototype.getAspectRatio = function (camera) {
  5383. var viewport = camera.viewport;
  5384. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5385. };
  5386. Engine.prototype.getRenderWidth = function () {
  5387. if (this._currentRenderTarget) {
  5388. return this._currentRenderTarget._width;
  5389. }
  5390. return this._renderingCanvas.width;
  5391. };
  5392. Engine.prototype.getRenderHeight = function () {
  5393. if (this._currentRenderTarget) {
  5394. return this._currentRenderTarget._height;
  5395. }
  5396. return this._renderingCanvas.height;
  5397. };
  5398. Engine.prototype.getRenderingCanvas = function () {
  5399. return this._renderingCanvas;
  5400. };
  5401. Engine.prototype.getRenderingCanvasClientRect = function () {
  5402. return this._renderingCanvas.getBoundingClientRect();
  5403. };
  5404. Engine.prototype.setHardwareScalingLevel = function (level) {
  5405. this._hardwareScalingLevel = level;
  5406. this.resize();
  5407. };
  5408. Engine.prototype.getHardwareScalingLevel = function () {
  5409. return this._hardwareScalingLevel;
  5410. };
  5411. Engine.prototype.getLoadedTexturesCache = function () {
  5412. return this._loadedTexturesCache;
  5413. };
  5414. Engine.prototype.getCaps = function () {
  5415. return this._caps;
  5416. };
  5417. Object.defineProperty(Engine.prototype, "drawCalls", {
  5418. get: function () {
  5419. return this._drawCalls;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. // Methods
  5425. Engine.prototype.resetDrawCalls = function () {
  5426. this._drawCalls = 0;
  5427. };
  5428. Engine.prototype.setDepthFunctionToGreater = function () {
  5429. this._depthCullingState.depthFunc = this._gl.GREATER;
  5430. };
  5431. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5432. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5433. };
  5434. Engine.prototype.setDepthFunctionToLess = function () {
  5435. this._depthCullingState.depthFunc = this._gl.LESS;
  5436. };
  5437. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5438. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5439. };
  5440. /**
  5441. * stop executing a render loop function and remove it from the execution array
  5442. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5443. */
  5444. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5445. if (!renderFunction) {
  5446. this._activeRenderLoops = [];
  5447. return;
  5448. }
  5449. var index = this._activeRenderLoops.indexOf(renderFunction);
  5450. if (index >= 0) {
  5451. this._activeRenderLoops.splice(index, 1);
  5452. }
  5453. };
  5454. Engine.prototype._renderLoop = function () {
  5455. var shouldRender = true;
  5456. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5457. shouldRender = false;
  5458. }
  5459. if (shouldRender) {
  5460. // Start new frame
  5461. this.beginFrame();
  5462. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5463. var renderFunction = this._activeRenderLoops[index];
  5464. renderFunction();
  5465. }
  5466. // Present
  5467. this.endFrame();
  5468. }
  5469. if (this._activeRenderLoops.length > 0) {
  5470. // Register new frame
  5471. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5472. }
  5473. else {
  5474. this._renderingQueueLaunched = false;
  5475. }
  5476. };
  5477. /**
  5478. * Register and execute a render loop. The engine can have more than one render function.
  5479. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5480. * @example
  5481. * engine.runRenderLoop(function () {
  5482. * scene.render()
  5483. * })
  5484. */
  5485. Engine.prototype.runRenderLoop = function (renderFunction) {
  5486. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5487. return;
  5488. }
  5489. this._activeRenderLoops.push(renderFunction);
  5490. if (!this._renderingQueueLaunched) {
  5491. this._renderingQueueLaunched = true;
  5492. this._bindedRenderFunction = this._renderLoop.bind(this);
  5493. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5494. }
  5495. };
  5496. /**
  5497. * Toggle full screen mode.
  5498. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5499. */
  5500. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5501. if (this.isFullscreen) {
  5502. BABYLON.Tools.ExitFullscreen();
  5503. }
  5504. else {
  5505. this._pointerLockRequested = requestPointerLock;
  5506. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5507. }
  5508. };
  5509. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5510. this.applyStates();
  5511. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5512. if (this._depthCullingState.depthMask) {
  5513. this._gl.clearDepth(1.0);
  5514. }
  5515. var mode = 0;
  5516. if (backBuffer)
  5517. mode |= this._gl.COLOR_BUFFER_BIT;
  5518. if (depthStencil && this._depthCullingState.depthMask)
  5519. mode |= this._gl.DEPTH_BUFFER_BIT;
  5520. this._gl.clear(mode);
  5521. };
  5522. /**
  5523. * Set the WebGL's viewport
  5524. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5525. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5526. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5527. */
  5528. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5529. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5530. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5531. var x = viewport.x || 0;
  5532. var y = viewport.y || 0;
  5533. this._cachedViewport = viewport;
  5534. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5535. };
  5536. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5537. this._cachedViewport = null;
  5538. this._gl.viewport(x, y, width, height);
  5539. };
  5540. Engine.prototype.beginFrame = function () {
  5541. this._measureFps();
  5542. };
  5543. Engine.prototype.endFrame = function () {
  5544. //this.flushFramebuffer();
  5545. };
  5546. /**
  5547. * resize the view according to the canvas' size.
  5548. * @example
  5549. * window.addEventListener("resize", function () {
  5550. * engine.resize();
  5551. * });
  5552. */
  5553. Engine.prototype.resize = function () {
  5554. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5555. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5556. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5557. for (var index = 0; index < this.scenes.length; index++) {
  5558. var scene = this.scenes[index];
  5559. if (scene.debugLayer.isVisible()) {
  5560. scene.debugLayer._syncPositions();
  5561. }
  5562. }
  5563. };
  5564. /**
  5565. * force a specific size of the canvas
  5566. * @param {number} width - the new canvas' width
  5567. * @param {number} height - the new canvas' height
  5568. */
  5569. Engine.prototype.setSize = function (width, height) {
  5570. this._renderingCanvas.width = width;
  5571. this._renderingCanvas.height = height;
  5572. for (var index = 0; index < this.scenes.length; index++) {
  5573. var scene = this.scenes[index];
  5574. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5575. var cam = scene.cameras[camIndex];
  5576. cam._currentRenderId = 0;
  5577. }
  5578. }
  5579. };
  5580. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5581. this._currentRenderTarget = texture;
  5582. var gl = this._gl;
  5583. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5584. if (texture.isCube) {
  5585. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5586. }
  5587. else {
  5588. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5589. }
  5590. this._gl.viewport(0, 0, texture._width, texture._height);
  5591. this.wipeCaches();
  5592. };
  5593. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5594. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5595. this._currentRenderTarget = null;
  5596. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5597. var gl = this._gl;
  5598. gl.bindTexture(gl.TEXTURE_2D, texture);
  5599. gl.generateMipmap(gl.TEXTURE_2D);
  5600. gl.bindTexture(gl.TEXTURE_2D, null);
  5601. }
  5602. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5603. };
  5604. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5605. if (texture.generateMipMaps) {
  5606. var gl = this._gl;
  5607. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5608. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5609. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5610. }
  5611. };
  5612. Engine.prototype.flushFramebuffer = function () {
  5613. this._gl.flush();
  5614. };
  5615. Engine.prototype.restoreDefaultFramebuffer = function () {
  5616. this._currentRenderTarget = null;
  5617. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5618. this.setViewport(this._cachedViewport);
  5619. this.wipeCaches();
  5620. };
  5621. // VBOs
  5622. Engine.prototype._resetVertexBufferBinding = function () {
  5623. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5624. this._cachedVertexBuffers = null;
  5625. };
  5626. Engine.prototype.createVertexBuffer = function (vertices) {
  5627. var vbo = this._gl.createBuffer();
  5628. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5629. if (vertices instanceof Float32Array) {
  5630. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5631. }
  5632. else {
  5633. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5634. }
  5635. this._resetVertexBufferBinding();
  5636. vbo.references = 1;
  5637. return vbo;
  5638. };
  5639. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5640. var vbo = this._gl.createBuffer();
  5641. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5642. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5643. this._resetVertexBufferBinding();
  5644. vbo.references = 1;
  5645. return vbo;
  5646. };
  5647. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5648. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5649. if (offset === undefined) {
  5650. offset = 0;
  5651. }
  5652. if (vertices instanceof Float32Array) {
  5653. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5654. }
  5655. else {
  5656. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5657. }
  5658. this._resetVertexBufferBinding();
  5659. };
  5660. Engine.prototype._resetIndexBufferBinding = function () {
  5661. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5662. this._cachedIndexBuffer = null;
  5663. };
  5664. Engine.prototype.createIndexBuffer = function (indices) {
  5665. var vbo = this._gl.createBuffer();
  5666. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5667. // Check for 32 bits indices
  5668. var arrayBuffer;
  5669. var need32Bits = false;
  5670. if (this._caps.uintIndices) {
  5671. for (var index = 0; index < indices.length; index++) {
  5672. if (indices[index] > 65535) {
  5673. need32Bits = true;
  5674. break;
  5675. }
  5676. }
  5677. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5678. }
  5679. else {
  5680. arrayBuffer = new Uint16Array(indices);
  5681. }
  5682. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5683. this._resetIndexBufferBinding();
  5684. vbo.references = 1;
  5685. vbo.is32Bits = need32Bits;
  5686. return vbo;
  5687. };
  5688. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5689. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5690. this._cachedVertexBuffers = vertexBuffer;
  5691. this._cachedEffectForVertexBuffers = effect;
  5692. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5693. var offset = 0;
  5694. for (var index = 0; index < vertexDeclaration.length; index++) {
  5695. var order = effect.getAttributeLocation(index);
  5696. if (order >= 0) {
  5697. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5698. }
  5699. offset += vertexDeclaration[index] * 4;
  5700. }
  5701. }
  5702. if (this._cachedIndexBuffer !== indexBuffer) {
  5703. this._cachedIndexBuffer = indexBuffer;
  5704. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5705. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5706. }
  5707. };
  5708. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5709. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5710. this._cachedVertexBuffers = vertexBuffers;
  5711. this._cachedEffectForVertexBuffers = effect;
  5712. var attributes = effect.getAttributesNames();
  5713. for (var index = 0; index < attributes.length; index++) {
  5714. var order = effect.getAttributeLocation(index);
  5715. if (order >= 0) {
  5716. var vertexBuffer = vertexBuffers[attributes[index]];
  5717. if (!vertexBuffer) {
  5718. continue;
  5719. }
  5720. var stride = vertexBuffer.getStrideSize();
  5721. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5722. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5723. }
  5724. }
  5725. }
  5726. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5727. this._cachedIndexBuffer = indexBuffer;
  5728. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5729. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5730. }
  5731. };
  5732. Engine.prototype._releaseBuffer = function (buffer) {
  5733. buffer.references--;
  5734. if (buffer.references === 0) {
  5735. this._gl.deleteBuffer(buffer);
  5736. return true;
  5737. }
  5738. return false;
  5739. };
  5740. Engine.prototype.createInstancesBuffer = function (capacity) {
  5741. var buffer = this._gl.createBuffer();
  5742. buffer.capacity = capacity;
  5743. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5744. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5745. return buffer;
  5746. };
  5747. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5748. this._gl.deleteBuffer(buffer);
  5749. };
  5750. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5751. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5752. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5753. for (var index = 0; index < 4; index++) {
  5754. var offsetLocation = offsetLocations[index];
  5755. this._gl.enableVertexAttribArray(offsetLocation);
  5756. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5757. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5758. }
  5759. };
  5760. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5761. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5762. for (var index = 0; index < 4; index++) {
  5763. var offsetLocation = offsetLocations[index];
  5764. this._gl.disableVertexAttribArray(offsetLocation);
  5765. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5766. }
  5767. };
  5768. Engine.prototype.applyStates = function () {
  5769. this._depthCullingState.apply(this._gl);
  5770. this._alphaState.apply(this._gl);
  5771. };
  5772. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5773. // Apply states
  5774. this.applyStates();
  5775. this._drawCalls++;
  5776. // Render
  5777. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5778. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5779. if (instancesCount) {
  5780. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5781. return;
  5782. }
  5783. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5784. };
  5785. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5786. // Apply states
  5787. this.applyStates();
  5788. this._drawCalls++;
  5789. if (instancesCount) {
  5790. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5791. return;
  5792. }
  5793. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5794. };
  5795. // Shaders
  5796. Engine.prototype._releaseEffect = function (effect) {
  5797. if (this._compiledEffects[effect._key]) {
  5798. delete this._compiledEffects[effect._key];
  5799. if (effect.getProgram()) {
  5800. this._gl.deleteProgram(effect.getProgram());
  5801. }
  5802. }
  5803. };
  5804. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5805. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5806. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5807. var name = vertex + "+" + fragment + "@" + defines;
  5808. if (this._compiledEffects[name]) {
  5809. return this._compiledEffects[name];
  5810. }
  5811. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5812. effect._key = name;
  5813. this._compiledEffects[name] = effect;
  5814. return effect;
  5815. };
  5816. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5817. if (uniformsNames === void 0) { uniformsNames = []; }
  5818. if (samplers === void 0) { samplers = []; }
  5819. if (defines === void 0) { defines = ""; }
  5820. return this.createEffect({
  5821. vertex: "particles",
  5822. fragmentElement: fragmentName
  5823. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5824. };
  5825. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5826. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5827. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5828. var shaderProgram = this._gl.createProgram();
  5829. this._gl.attachShader(shaderProgram, vertexShader);
  5830. this._gl.attachShader(shaderProgram, fragmentShader);
  5831. this._gl.linkProgram(shaderProgram);
  5832. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5833. if (!linked) {
  5834. var error = this._gl.getProgramInfoLog(shaderProgram);
  5835. if (error) {
  5836. throw new Error(error);
  5837. }
  5838. }
  5839. this._gl.deleteShader(vertexShader);
  5840. this._gl.deleteShader(fragmentShader);
  5841. return shaderProgram;
  5842. };
  5843. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5844. var results = [];
  5845. for (var index = 0; index < uniformsNames.length; index++) {
  5846. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5847. }
  5848. return results;
  5849. };
  5850. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5851. var results = [];
  5852. for (var index = 0; index < attributesNames.length; index++) {
  5853. try {
  5854. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5855. }
  5856. catch (e) {
  5857. results.push(-1);
  5858. }
  5859. }
  5860. return results;
  5861. };
  5862. Engine.prototype.enableEffect = function (effect) {
  5863. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5864. if (effect && effect.onBind) {
  5865. effect.onBind(effect);
  5866. }
  5867. return;
  5868. }
  5869. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5870. // Use program
  5871. this._gl.useProgram(effect.getProgram());
  5872. for (var i in this._vertexAttribArrays) {
  5873. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5874. continue;
  5875. }
  5876. this._vertexAttribArrays[i] = false;
  5877. this._gl.disableVertexAttribArray(i);
  5878. }
  5879. var attributesCount = effect.getAttributesCount();
  5880. for (var index = 0; index < attributesCount; index++) {
  5881. // Attributes
  5882. var order = effect.getAttributeLocation(index);
  5883. if (order >= 0) {
  5884. this._vertexAttribArrays[order] = true;
  5885. this._gl.enableVertexAttribArray(order);
  5886. }
  5887. }
  5888. this._currentEffect = effect;
  5889. if (effect.onBind) {
  5890. effect.onBind(effect);
  5891. }
  5892. };
  5893. Engine.prototype.setArray = function (uniform, array) {
  5894. if (!uniform)
  5895. return;
  5896. this._gl.uniform1fv(uniform, array);
  5897. };
  5898. Engine.prototype.setArray2 = function (uniform, array) {
  5899. if (!uniform || array.length % 2 !== 0)
  5900. return;
  5901. this._gl.uniform2fv(uniform, array);
  5902. };
  5903. Engine.prototype.setArray3 = function (uniform, array) {
  5904. if (!uniform || array.length % 3 !== 0)
  5905. return;
  5906. this._gl.uniform3fv(uniform, array);
  5907. };
  5908. Engine.prototype.setArray4 = function (uniform, array) {
  5909. if (!uniform || array.length % 4 !== 0)
  5910. return;
  5911. this._gl.uniform4fv(uniform, array);
  5912. };
  5913. Engine.prototype.setMatrices = function (uniform, matrices) {
  5914. if (!uniform)
  5915. return;
  5916. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5917. };
  5918. Engine.prototype.setMatrix = function (uniform, matrix) {
  5919. if (!uniform)
  5920. return;
  5921. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5922. };
  5923. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5924. if (!uniform)
  5925. return;
  5926. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5927. };
  5928. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5929. if (!uniform)
  5930. return;
  5931. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5932. };
  5933. Engine.prototype.setFloat = function (uniform, value) {
  5934. if (!uniform)
  5935. return;
  5936. this._gl.uniform1f(uniform, value);
  5937. };
  5938. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5939. if (!uniform)
  5940. return;
  5941. this._gl.uniform2f(uniform, x, y);
  5942. };
  5943. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5944. if (!uniform)
  5945. return;
  5946. this._gl.uniform3f(uniform, x, y, z);
  5947. };
  5948. Engine.prototype.setBool = function (uniform, bool) {
  5949. if (!uniform)
  5950. return;
  5951. this._gl.uniform1i(uniform, bool);
  5952. };
  5953. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5954. if (!uniform)
  5955. return;
  5956. this._gl.uniform4f(uniform, x, y, z, w);
  5957. };
  5958. Engine.prototype.setColor3 = function (uniform, color3) {
  5959. if (!uniform)
  5960. return;
  5961. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5962. };
  5963. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5964. if (!uniform)
  5965. return;
  5966. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5967. };
  5968. // States
  5969. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5970. if (zOffset === void 0) { zOffset = 0; }
  5971. if (reverseSide === void 0) { reverseSide = false; }
  5972. // Culling
  5973. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5974. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5975. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5976. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5977. if (culling) {
  5978. this._depthCullingState.cullFace = cullFace;
  5979. this._depthCullingState.cull = true;
  5980. }
  5981. else {
  5982. this._depthCullingState.cull = false;
  5983. }
  5984. }
  5985. // Z offset
  5986. this._depthCullingState.zOffset = zOffset;
  5987. };
  5988. Engine.prototype.setDepthBuffer = function (enable) {
  5989. this._depthCullingState.depthTest = enable;
  5990. };
  5991. Engine.prototype.getDepthWrite = function () {
  5992. return this._depthCullingState.depthMask;
  5993. };
  5994. Engine.prototype.setDepthWrite = function (enable) {
  5995. this._depthCullingState.depthMask = enable;
  5996. };
  5997. Engine.prototype.setColorWrite = function (enable) {
  5998. this._gl.colorMask(enable, enable, enable, enable);
  5999. };
  6000. Engine.prototype.setAlphaMode = function (mode) {
  6001. if (this._alphaMode === mode) {
  6002. return;
  6003. }
  6004. switch (mode) {
  6005. case Engine.ALPHA_DISABLE:
  6006. this.setDepthWrite(true);
  6007. this._alphaState.alphaBlend = false;
  6008. break;
  6009. case Engine.ALPHA_COMBINE:
  6010. this.setDepthWrite(false);
  6011. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6012. this._alphaState.alphaBlend = true;
  6013. break;
  6014. case Engine.ALPHA_ONEONE:
  6015. this.setDepthWrite(false);
  6016. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6017. this._alphaState.alphaBlend = true;
  6018. break;
  6019. case Engine.ALPHA_ADD:
  6020. this.setDepthWrite(false);
  6021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6022. this._alphaState.alphaBlend = true;
  6023. break;
  6024. case Engine.ALPHA_SUBTRACT:
  6025. this.setDepthWrite(false);
  6026. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6027. this._alphaState.alphaBlend = true;
  6028. break;
  6029. case Engine.ALPHA_MULTIPLY:
  6030. this.setDepthWrite(false);
  6031. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6032. this._alphaState.alphaBlend = true;
  6033. break;
  6034. case Engine.ALPHA_MAXIMIZED:
  6035. this.setDepthWrite(false);
  6036. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6037. this._alphaState.alphaBlend = true;
  6038. break;
  6039. }
  6040. this._alphaMode = mode;
  6041. };
  6042. Engine.prototype.getAlphaMode = function () {
  6043. return this._alphaMode;
  6044. };
  6045. Engine.prototype.setAlphaTesting = function (enable) {
  6046. this._alphaTest = enable;
  6047. };
  6048. Engine.prototype.getAlphaTesting = function () {
  6049. return this._alphaTest;
  6050. };
  6051. // Textures
  6052. Engine.prototype.wipeCaches = function () {
  6053. this.resetTextureCache();
  6054. this._currentEffect = null;
  6055. this._depthCullingState.reset();
  6056. this._alphaState.reset();
  6057. this._cachedVertexBuffers = null;
  6058. this._cachedIndexBuffer = null;
  6059. this._cachedEffectForVertexBuffers = null;
  6060. };
  6061. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6062. var gl = this._gl;
  6063. gl.bindTexture(gl.TEXTURE_2D, texture);
  6064. var magFilter = gl.NEAREST;
  6065. var minFilter = gl.NEAREST;
  6066. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6067. magFilter = gl.LINEAR;
  6068. minFilter = gl.LINEAR;
  6069. }
  6070. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6071. magFilter = gl.LINEAR;
  6072. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6073. }
  6074. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6076. gl.bindTexture(gl.TEXTURE_2D, null);
  6077. texture.samplingMode = samplingMode;
  6078. };
  6079. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6080. var _this = this;
  6081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6082. if (onLoad === void 0) { onLoad = null; }
  6083. if (onError === void 0) { onError = null; }
  6084. if (buffer === void 0) { buffer = null; }
  6085. var texture = this._gl.createTexture();
  6086. var extension;
  6087. var fromData = false;
  6088. if (url.substr(0, 5) === "data:") {
  6089. fromData = true;
  6090. }
  6091. if (!fromData)
  6092. extension = url.substr(url.length - 4, 4).toLowerCase();
  6093. else {
  6094. var oldUrl = url;
  6095. fromData = oldUrl.split(':');
  6096. url = oldUrl;
  6097. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6098. }
  6099. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6100. var isTGA = (extension === ".tga");
  6101. scene._addPendingData(texture);
  6102. texture.url = url;
  6103. texture.noMipmap = noMipmap;
  6104. texture.references = 1;
  6105. texture.samplingMode = samplingMode;
  6106. this._loadedTexturesCache.push(texture);
  6107. var onerror = function () {
  6108. scene._removePendingData(texture);
  6109. if (onError) {
  6110. onError();
  6111. }
  6112. };
  6113. var callback;
  6114. if (isTGA) {
  6115. callback = function (arrayBuffer) {
  6116. var data = new Uint8Array(arrayBuffer);
  6117. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6118. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6119. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6120. if (onLoad) {
  6121. onLoad();
  6122. }
  6123. }, samplingMode);
  6124. };
  6125. if (!(fromData instanceof Array))
  6126. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6127. callback(arrayBuffer);
  6128. }, onerror, scene.database, true);
  6129. else
  6130. callback(buffer);
  6131. }
  6132. else if (isDDS) {
  6133. callback = function (data) {
  6134. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6135. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6136. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6137. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6138. if (onLoad) {
  6139. onLoad();
  6140. }
  6141. }, samplingMode);
  6142. };
  6143. if (!(fromData instanceof Array))
  6144. BABYLON.Tools.LoadFile(url, function (data) {
  6145. callback(data);
  6146. }, onerror, scene.database, true);
  6147. else
  6148. callback(buffer);
  6149. }
  6150. else {
  6151. var onload = function (img) {
  6152. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6153. var isPot = (img.width === potWidth && img.height === potHeight);
  6154. if (!isPot) {
  6155. _this._prepareWorkingCanvas();
  6156. _this._workingCanvas.width = potWidth;
  6157. _this._workingCanvas.height = potHeight;
  6158. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6159. _this._workingContext.imageSmoothingEnabled = false;
  6160. _this._workingContext.mozImageSmoothingEnabled = false;
  6161. _this._workingContext.oImageSmoothingEnabled = false;
  6162. _this._workingContext.webkitImageSmoothingEnabled = false;
  6163. _this._workingContext.msImageSmoothingEnabled = false;
  6164. }
  6165. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6166. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6167. _this._workingContext.imageSmoothingEnabled = true;
  6168. _this._workingContext.mozImageSmoothingEnabled = true;
  6169. _this._workingContext.oImageSmoothingEnabled = true;
  6170. _this._workingContext.webkitImageSmoothingEnabled = true;
  6171. _this._workingContext.msImageSmoothingEnabled = true;
  6172. }
  6173. }
  6174. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6175. if (onLoad) {
  6176. onLoad();
  6177. }
  6178. }, samplingMode);
  6179. };
  6180. if (!(fromData instanceof Array))
  6181. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6182. else
  6183. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6184. }
  6185. return texture;
  6186. };
  6187. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6188. if (compression === void 0) { compression = null; }
  6189. var internalFormat = this._gl.RGBA;
  6190. switch (format) {
  6191. case Engine.TEXTUREFORMAT_ALPHA:
  6192. internalFormat = this._gl.ALPHA;
  6193. break;
  6194. case Engine.TEXTUREFORMAT_LUMINANCE:
  6195. internalFormat = this._gl.LUMINANCE;
  6196. break;
  6197. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6198. internalFormat = this._gl.LUMINANCE_ALPHA;
  6199. break;
  6200. case Engine.TEXTUREFORMAT_RGB:
  6201. internalFormat = this._gl.RGB;
  6202. break;
  6203. case Engine.TEXTUREFORMAT_RGBA:
  6204. internalFormat = this._gl.RGBA;
  6205. break;
  6206. }
  6207. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6208. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6209. if (compression) {
  6210. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6211. }
  6212. else {
  6213. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6214. }
  6215. if (texture.generateMipMaps) {
  6216. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6217. }
  6218. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6219. this.resetTextureCache();
  6220. texture.isReady = true;
  6221. };
  6222. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6223. if (compression === void 0) { compression = null; }
  6224. var texture = this._gl.createTexture();
  6225. texture._baseWidth = width;
  6226. texture._baseHeight = height;
  6227. texture._width = width;
  6228. texture._height = height;
  6229. texture.references = 1;
  6230. this.updateRawTexture(texture, data, format, invertY, compression);
  6231. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6232. // Filters
  6233. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6234. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6235. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6236. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6237. texture.samplingMode = samplingMode;
  6238. this._loadedTexturesCache.push(texture);
  6239. return texture;
  6240. };
  6241. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6242. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6243. var texture = this._gl.createTexture();
  6244. texture._baseWidth = width;
  6245. texture._baseHeight = height;
  6246. if (forceExponantOfTwo) {
  6247. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6248. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6249. }
  6250. this.resetTextureCache();
  6251. texture._width = width;
  6252. texture._height = height;
  6253. texture.isReady = false;
  6254. texture.generateMipMaps = generateMipMaps;
  6255. texture.references = 1;
  6256. texture.samplingMode = samplingMode;
  6257. this.updateTextureSamplingMode(samplingMode, texture);
  6258. this._loadedTexturesCache.push(texture);
  6259. return texture;
  6260. };
  6261. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6262. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6263. if (texture.isCube) {
  6264. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6265. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6266. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6267. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6268. }
  6269. else {
  6270. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6273. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6274. }
  6275. };
  6276. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6277. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6278. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6279. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6280. if (texture.generateMipMaps) {
  6281. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6282. }
  6283. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6284. this.resetTextureCache();
  6285. texture.isReady = true;
  6286. };
  6287. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6288. if (texture._isDisabled) {
  6289. return;
  6290. }
  6291. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6292. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6293. try {
  6294. // Testing video texture support
  6295. if (this._videoTextureSupported === undefined) {
  6296. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6297. if (this._gl.getError() !== 0) {
  6298. this._videoTextureSupported = false;
  6299. }
  6300. else {
  6301. this._videoTextureSupported = true;
  6302. }
  6303. }
  6304. // Copy video through the current working canvas if video texture is not supported
  6305. if (!this._videoTextureSupported) {
  6306. if (!texture._workingCanvas) {
  6307. texture._workingCanvas = document.createElement("canvas");
  6308. texture._workingContext = texture._workingCanvas.getContext("2d");
  6309. texture._workingCanvas.width = texture._width;
  6310. texture._workingCanvas.height = texture._height;
  6311. }
  6312. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6313. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6314. }
  6315. else {
  6316. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6317. }
  6318. if (texture.generateMipMaps) {
  6319. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6320. }
  6321. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6322. this.resetTextureCache();
  6323. texture.isReady = true;
  6324. }
  6325. catch (ex) {
  6326. // Something unexpected
  6327. // Let's disable the texture
  6328. texture._isDisabled = true;
  6329. }
  6330. };
  6331. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6332. // old version had a "generateMipMaps" arg instead of options.
  6333. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6334. // in the same way, generateDepthBuffer is defaulted to true
  6335. var generateMipMaps = false;
  6336. var generateDepthBuffer = true;
  6337. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6338. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6339. if (options !== undefined) {
  6340. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6341. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6342. type = options.type === undefined ? type : options.type;
  6343. if (options.samplingMode !== undefined) {
  6344. samplingMode = options.samplingMode;
  6345. }
  6346. if (type === Engine.TEXTURETYPE_FLOAT) {
  6347. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6348. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6349. }
  6350. }
  6351. var gl = this._gl;
  6352. var texture = gl.createTexture();
  6353. gl.bindTexture(gl.TEXTURE_2D, texture);
  6354. var width = size.width || size;
  6355. var height = size.height || size;
  6356. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6357. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6358. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6359. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6360. }
  6361. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6362. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6365. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6366. var depthBuffer;
  6367. // Create the depth buffer
  6368. if (generateDepthBuffer) {
  6369. depthBuffer = gl.createRenderbuffer();
  6370. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6371. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6372. }
  6373. // Create the framebuffer
  6374. var framebuffer = gl.createFramebuffer();
  6375. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6376. if (generateDepthBuffer) {
  6377. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6378. }
  6379. if (generateMipMaps) {
  6380. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6381. }
  6382. // Unbind
  6383. gl.bindTexture(gl.TEXTURE_2D, null);
  6384. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6385. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6386. texture._framebuffer = framebuffer;
  6387. if (generateDepthBuffer) {
  6388. texture._depthBuffer = depthBuffer;
  6389. }
  6390. texture._width = width;
  6391. texture._height = height;
  6392. texture.isReady = true;
  6393. texture.generateMipMaps = generateMipMaps;
  6394. texture.references = 1;
  6395. texture.samplingMode = samplingMode;
  6396. this.resetTextureCache();
  6397. this._loadedTexturesCache.push(texture);
  6398. return texture;
  6399. };
  6400. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6401. var gl = this._gl;
  6402. var texture = gl.createTexture();
  6403. var generateMipMaps = true;
  6404. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6405. if (options !== undefined) {
  6406. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6407. if (options.samplingMode !== undefined) {
  6408. samplingMode = options.samplingMode;
  6409. }
  6410. }
  6411. texture.isCube = true;
  6412. texture.references = 1;
  6413. texture.generateMipMaps = generateMipMaps;
  6414. texture.references = 1;
  6415. texture.samplingMode = samplingMode;
  6416. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6417. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6418. for (var face = 0; face < 6; face++) {
  6419. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6420. }
  6421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6425. // Create the depth buffer
  6426. var depthBuffer = gl.createRenderbuffer();
  6427. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6428. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6429. // Create the framebuffer
  6430. var framebuffer = gl.createFramebuffer();
  6431. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6432. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6433. // mipmaps
  6434. if (texture.generateMipMaps) {
  6435. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6436. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6437. }
  6438. // Unbind
  6439. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6440. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6441. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6442. texture._framebuffer = framebuffer;
  6443. texture._depthBuffer = depthBuffer;
  6444. this.resetTextureCache();
  6445. texture._width = size;
  6446. texture._height = size;
  6447. texture.isReady = true;
  6448. return texture;
  6449. };
  6450. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6451. var _this = this;
  6452. var gl = this._gl;
  6453. var texture = gl.createTexture();
  6454. texture.isCube = true;
  6455. texture.url = rootUrl;
  6456. texture.references = 1;
  6457. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6458. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6459. if (isDDS) {
  6460. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6461. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6462. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6463. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6464. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6465. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6466. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6467. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6468. }
  6469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6473. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6474. _this.resetTextureCache();
  6475. texture._width = info.width;
  6476. texture._height = info.height;
  6477. texture.isReady = true;
  6478. }, null, null, true);
  6479. }
  6480. else {
  6481. cascadeLoad(rootUrl, scene, function (imgs) {
  6482. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6483. var height = width;
  6484. _this._prepareWorkingCanvas();
  6485. _this._workingCanvas.width = width;
  6486. _this._workingCanvas.height = height;
  6487. var faces = [
  6488. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6489. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6490. ];
  6491. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6492. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6493. for (var index = 0; index < faces.length; index++) {
  6494. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6495. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6496. }
  6497. if (!noMipmap) {
  6498. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6499. }
  6500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6504. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6505. _this.resetTextureCache();
  6506. texture._width = width;
  6507. texture._height = height;
  6508. texture.isReady = true;
  6509. }, extensions);
  6510. }
  6511. return texture;
  6512. };
  6513. Engine.prototype._releaseTexture = function (texture) {
  6514. var gl = this._gl;
  6515. if (texture._framebuffer) {
  6516. gl.deleteFramebuffer(texture._framebuffer);
  6517. }
  6518. if (texture._depthBuffer) {
  6519. gl.deleteRenderbuffer(texture._depthBuffer);
  6520. }
  6521. gl.deleteTexture(texture);
  6522. // Unbind channels
  6523. this.unbindAllTextures();
  6524. var index = this._loadedTexturesCache.indexOf(texture);
  6525. if (index !== -1) {
  6526. this._loadedTexturesCache.splice(index, 1);
  6527. }
  6528. };
  6529. Engine.prototype.bindSamplers = function (effect) {
  6530. this._gl.useProgram(effect.getProgram());
  6531. var samplers = effect.getSamplers();
  6532. for (var index = 0; index < samplers.length; index++) {
  6533. var uniform = effect.getUniform(samplers[index]);
  6534. this._gl.uniform1i(uniform, index);
  6535. }
  6536. this._currentEffect = null;
  6537. };
  6538. Engine.prototype._bindTexture = function (channel, texture) {
  6539. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6540. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6541. this._activeTexturesCache[channel] = null;
  6542. };
  6543. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6544. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6545. };
  6546. Engine.prototype.unbindAllTextures = function () {
  6547. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6548. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6549. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6550. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6551. this._activeTexturesCache[channel] = null;
  6552. }
  6553. };
  6554. Engine.prototype.setTexture = function (channel, texture) {
  6555. if (channel < 0) {
  6556. return;
  6557. }
  6558. // Not ready?
  6559. if (!texture || !texture.isReady()) {
  6560. if (this._activeTexturesCache[channel] != null) {
  6561. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6562. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6563. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6564. this._activeTexturesCache[channel] = null;
  6565. }
  6566. return;
  6567. }
  6568. // Video
  6569. var alreadyActivated = false;
  6570. if (texture instanceof BABYLON.VideoTexture) {
  6571. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6572. alreadyActivated = true;
  6573. texture.update();
  6574. }
  6575. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6576. texture.delayLoad();
  6577. return;
  6578. }
  6579. if (this._activeTexturesCache[channel] === texture) {
  6580. return;
  6581. }
  6582. this._activeTexturesCache[channel] = texture;
  6583. var internalTexture = texture.getInternalTexture();
  6584. if (!alreadyActivated) {
  6585. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6586. }
  6587. if (internalTexture.isCube) {
  6588. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6589. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6590. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6591. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6592. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6593. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6594. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6595. }
  6596. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6597. }
  6598. else {
  6599. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6600. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6601. internalTexture._cachedWrapU = texture.wrapU;
  6602. switch (texture.wrapU) {
  6603. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6604. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6605. break;
  6606. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6608. break;
  6609. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6611. break;
  6612. }
  6613. }
  6614. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6615. internalTexture._cachedWrapV = texture.wrapV;
  6616. switch (texture.wrapV) {
  6617. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6618. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6619. break;
  6620. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6622. break;
  6623. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6625. break;
  6626. }
  6627. }
  6628. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6629. }
  6630. };
  6631. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6632. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6633. var value = texture.anisotropicFilteringLevel;
  6634. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6635. value = 1;
  6636. }
  6637. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6638. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6639. texture._cachedAnisotropicFilteringLevel = value;
  6640. }
  6641. };
  6642. Engine.prototype.readPixels = function (x, y, width, height) {
  6643. var data = new Uint8Array(height * width * 4);
  6644. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6645. return data;
  6646. };
  6647. Engine.prototype.releaseInternalTexture = function (texture) {
  6648. if (!texture) {
  6649. return;
  6650. }
  6651. texture.references--;
  6652. // Final reference ?
  6653. if (texture.references === 0) {
  6654. var texturesCache = this.getLoadedTexturesCache();
  6655. var index = texturesCache.indexOf(texture);
  6656. if (index > -1) {
  6657. texturesCache.splice(index, 1);
  6658. }
  6659. this._releaseTexture(texture);
  6660. }
  6661. };
  6662. // Dispose
  6663. Engine.prototype.dispose = function () {
  6664. this.hideLoadingUI();
  6665. this.stopRenderLoop();
  6666. // Release scenes
  6667. while (this.scenes.length) {
  6668. this.scenes[0].dispose();
  6669. }
  6670. // Release audio engine
  6671. Engine.audioEngine.dispose();
  6672. // Release effects
  6673. for (var name in this._compiledEffects) {
  6674. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6675. }
  6676. // Unbind
  6677. for (var i in this._vertexAttribArrays) {
  6678. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6679. continue;
  6680. }
  6681. this._gl.disableVertexAttribArray(i);
  6682. }
  6683. this._gl = null;
  6684. // Events
  6685. window.removeEventListener("blur", this._onBlur);
  6686. window.removeEventListener("focus", this._onFocus);
  6687. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6688. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6689. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6690. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6691. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6692. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6693. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6694. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6695. };
  6696. // Loading screen
  6697. Engine.prototype.displayLoadingUI = function () {
  6698. this._loadingScreen.displayLoadingUI();
  6699. };
  6700. Engine.prototype.hideLoadingUI = function () {
  6701. this._loadingScreen.hideLoadingUI();
  6702. };
  6703. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6704. get: function () {
  6705. return this._loadingScreen;
  6706. },
  6707. set: function (loadingScreen) {
  6708. this._loadingScreen = loadingScreen;
  6709. },
  6710. enumerable: true,
  6711. configurable: true
  6712. });
  6713. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6714. set: function (text) {
  6715. this._loadingScreen.loadingUIText = text;
  6716. },
  6717. enumerable: true,
  6718. configurable: true
  6719. });
  6720. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6721. set: function (color) {
  6722. this._loadingScreen.loadingUIBackgroundColor = color;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. // FPS
  6728. Engine.prototype.getFps = function () {
  6729. return this.fps;
  6730. };
  6731. Engine.prototype.getDeltaTime = function () {
  6732. return this.deltaTime;
  6733. };
  6734. Engine.prototype._measureFps = function () {
  6735. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6736. var length = this.previousFramesDuration.length;
  6737. if (length >= 2) {
  6738. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6739. }
  6740. if (length >= this.fpsRange) {
  6741. if (length > this.fpsRange) {
  6742. this.previousFramesDuration.splice(0, 1);
  6743. length = this.previousFramesDuration.length;
  6744. }
  6745. var sum = 0;
  6746. for (var id = 0; id < length - 1; id++) {
  6747. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6748. }
  6749. this.fps = 1000.0 / (sum / (length - 1));
  6750. }
  6751. };
  6752. // Statics
  6753. Engine.isSupported = function () {
  6754. try {
  6755. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6756. if (navigator.isCocoonJS) {
  6757. return true;
  6758. }
  6759. var tempcanvas = document.createElement("canvas");
  6760. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6761. return gl != null && !!window.WebGLRenderingContext;
  6762. }
  6763. catch (e) {
  6764. return false;
  6765. }
  6766. };
  6767. // Const statics
  6768. Engine._ALPHA_DISABLE = 0;
  6769. Engine._ALPHA_ADD = 1;
  6770. Engine._ALPHA_COMBINE = 2;
  6771. Engine._ALPHA_SUBTRACT = 3;
  6772. Engine._ALPHA_MULTIPLY = 4;
  6773. Engine._ALPHA_MAXIMIZED = 5;
  6774. Engine._ALPHA_ONEONE = 6;
  6775. Engine._DELAYLOADSTATE_NONE = 0;
  6776. Engine._DELAYLOADSTATE_LOADED = 1;
  6777. Engine._DELAYLOADSTATE_LOADING = 2;
  6778. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6779. Engine._TEXTUREFORMAT_ALPHA = 0;
  6780. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6781. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6782. Engine._TEXTUREFORMAT_RGB = 4;
  6783. Engine._TEXTUREFORMAT_RGBA = 5;
  6784. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6785. Engine._TEXTURETYPE_FLOAT = 1;
  6786. // Updatable statics so stick with vars here
  6787. Engine.Epsilon = 0.001;
  6788. Engine.CollisionsEpsilon = 0.001;
  6789. Engine.CodeRepository = "src/";
  6790. Engine.ShadersRepository = "src/Shaders/";
  6791. return Engine;
  6792. })();
  6793. BABYLON.Engine = Engine;
  6794. })(BABYLON || (BABYLON = {}));
  6795. var BABYLON;
  6796. (function (BABYLON) {
  6797. /**
  6798. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6799. */
  6800. var Node = (function () {
  6801. /**
  6802. * @constructor
  6803. * @param {string} name - the name and id to be given to this node
  6804. * @param {BABYLON.Scene} the scene this node will be added to
  6805. */
  6806. function Node(name, scene) {
  6807. this.state = "";
  6808. this.animations = new Array();
  6809. this._childrenFlag = -1;
  6810. this._isEnabled = true;
  6811. this._isReady = true;
  6812. this._currentRenderId = -1;
  6813. this._parentRenderId = -1;
  6814. this.name = name;
  6815. this.id = name;
  6816. this._scene = scene;
  6817. this._initCache();
  6818. }
  6819. Node.prototype.getScene = function () {
  6820. return this._scene;
  6821. };
  6822. Node.prototype.getEngine = function () {
  6823. return this._scene.getEngine();
  6824. };
  6825. // override it in derived class
  6826. Node.prototype.getWorldMatrix = function () {
  6827. return BABYLON.Matrix.Identity();
  6828. };
  6829. // override it in derived class if you add new variables to the cache
  6830. // and call the parent class method
  6831. Node.prototype._initCache = function () {
  6832. this._cache = {};
  6833. this._cache.parent = undefined;
  6834. };
  6835. Node.prototype.updateCache = function (force) {
  6836. if (!force && this.isSynchronized())
  6837. return;
  6838. this._cache.parent = this.parent;
  6839. this._updateCache();
  6840. };
  6841. // override it in derived class if you add new variables to the cache
  6842. // and call the parent class method if !ignoreParentClass
  6843. Node.prototype._updateCache = function (ignoreParentClass) {
  6844. };
  6845. // override it in derived class if you add new variables to the cache
  6846. Node.prototype._isSynchronized = function () {
  6847. return true;
  6848. };
  6849. Node.prototype._markSyncedWithParent = function () {
  6850. this._parentRenderId = this.parent._currentRenderId;
  6851. };
  6852. Node.prototype.isSynchronizedWithParent = function () {
  6853. if (!this.parent) {
  6854. return true;
  6855. }
  6856. if (this._parentRenderId !== this.parent._currentRenderId) {
  6857. return false;
  6858. }
  6859. return this.parent.isSynchronized();
  6860. };
  6861. Node.prototype.isSynchronized = function (updateCache) {
  6862. var check = this.hasNewParent();
  6863. check = check || !this.isSynchronizedWithParent();
  6864. check = check || !this._isSynchronized();
  6865. if (updateCache)
  6866. this.updateCache(true);
  6867. return !check;
  6868. };
  6869. Node.prototype.hasNewParent = function (update) {
  6870. if (this._cache.parent === this.parent)
  6871. return false;
  6872. if (update)
  6873. this._cache.parent = this.parent;
  6874. return true;
  6875. };
  6876. /**
  6877. * Is this node ready to be used/rendered
  6878. * @return {boolean} is it ready
  6879. */
  6880. Node.prototype.isReady = function () {
  6881. return this._isReady;
  6882. };
  6883. /**
  6884. * Is this node enabled.
  6885. * If the node has a parent and is enabled, the parent will be inspected as well.
  6886. * @return {boolean} whether this node (and its parent) is enabled.
  6887. * @see setEnabled
  6888. */
  6889. Node.prototype.isEnabled = function () {
  6890. if (!this._isEnabled) {
  6891. return false;
  6892. }
  6893. if (this.parent) {
  6894. return this.parent.isEnabled();
  6895. }
  6896. return true;
  6897. };
  6898. /**
  6899. * Set the enabled state of this node.
  6900. * @param {boolean} value - the new enabled state
  6901. * @see isEnabled
  6902. */
  6903. Node.prototype.setEnabled = function (value) {
  6904. this._isEnabled = value;
  6905. };
  6906. /**
  6907. * Is this node a descendant of the given node.
  6908. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6909. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6910. * @see parent
  6911. */
  6912. Node.prototype.isDescendantOf = function (ancestor) {
  6913. if (this.parent) {
  6914. if (this.parent === ancestor) {
  6915. return true;
  6916. }
  6917. return this.parent.isDescendantOf(ancestor);
  6918. }
  6919. return false;
  6920. };
  6921. Node.prototype._getDescendants = function (list, results) {
  6922. for (var index = 0; index < list.length; index++) {
  6923. var item = list[index];
  6924. if (item.isDescendantOf(this)) {
  6925. results.push(item);
  6926. }
  6927. }
  6928. };
  6929. /**
  6930. * Will return all nodes that have this node as parent.
  6931. * @return {BABYLON.Node[]} all children nodes of all types.
  6932. */
  6933. Node.prototype.getDescendants = function () {
  6934. var results = [];
  6935. this._getDescendants(this._scene.meshes, results);
  6936. this._getDescendants(this._scene.lights, results);
  6937. this._getDescendants(this._scene.cameras, results);
  6938. return results;
  6939. };
  6940. Node.prototype._setReady = function (state) {
  6941. if (state === this._isReady) {
  6942. return;
  6943. }
  6944. if (!state) {
  6945. this._isReady = false;
  6946. return;
  6947. }
  6948. this._isReady = true;
  6949. if (this.onReady) {
  6950. this.onReady(this);
  6951. }
  6952. };
  6953. Node.prototype.getAnimationByName = function (name) {
  6954. for (var i = 0; i < this.animations.length; i++) {
  6955. var animation = this.animations[i];
  6956. if (animation.name === name) {
  6957. return animation;
  6958. }
  6959. }
  6960. return null;
  6961. };
  6962. return Node;
  6963. })();
  6964. BABYLON.Node = Node;
  6965. })(BABYLON || (BABYLON = {}));
  6966. var BABYLON;
  6967. (function (BABYLON) {
  6968. var FilesInput = (function () {
  6969. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6970. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6971. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6972. this._engine = p_engine;
  6973. this._canvas = p_canvas;
  6974. this._currentScene = p_scene;
  6975. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6976. this._progressCallback = p_progressCallback;
  6977. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6978. this._textureLoadingCallback = p_textureLoadingCallback;
  6979. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6980. }
  6981. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6982. var _this = this;
  6983. if (p_elementToMonitor) {
  6984. this._elementToMonitor = p_elementToMonitor;
  6985. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6986. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6987. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6988. }
  6989. };
  6990. FilesInput.prototype.renderFunction = function () {
  6991. if (this._additionnalRenderLoopLogicCallback) {
  6992. this._additionnalRenderLoopLogicCallback();
  6993. }
  6994. if (this._currentScene) {
  6995. if (this._textureLoadingCallback) {
  6996. var remaining = this._currentScene.getWaitingItemsCount();
  6997. if (remaining > 0) {
  6998. this._textureLoadingCallback(remaining);
  6999. }
  7000. }
  7001. this._currentScene.render();
  7002. }
  7003. };
  7004. FilesInput.prototype.drag = function (e) {
  7005. e.stopPropagation();
  7006. e.preventDefault();
  7007. };
  7008. FilesInput.prototype.drop = function (eventDrop) {
  7009. eventDrop.stopPropagation();
  7010. eventDrop.preventDefault();
  7011. this.loadFiles(eventDrop);
  7012. };
  7013. FilesInput.prototype.loadFiles = function (event) {
  7014. if (this._startingProcessingFilesCallback)
  7015. this._startingProcessingFilesCallback();
  7016. // Handling data transfer via drag'n'drop
  7017. if (event && event.dataTransfer && event.dataTransfer.files) {
  7018. this._filesToLoad = event.dataTransfer.files;
  7019. }
  7020. // Handling files from input files
  7021. if (event && event.target && event.target.files) {
  7022. this._filesToLoad = event.target.files;
  7023. }
  7024. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7025. for (var i = 0; i < this._filesToLoad.length; i++) {
  7026. switch (this._filesToLoad[i].type) {
  7027. case "image/jpeg":
  7028. case "image/png":
  7029. case "image/bmp":
  7030. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7031. break;
  7032. case "image/targa":
  7033. case "image/vnd.ms-dds":
  7034. case "audio/wav":
  7035. case "audio/x-wav":
  7036. case "audio/mp3":
  7037. case "audio/mpeg":
  7038. case "audio/mpeg3":
  7039. case "audio/x-mpeg-3":
  7040. case "audio/ogg":
  7041. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7042. break;
  7043. default:
  7044. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7045. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7046. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7047. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7048. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7049. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7050. this._sceneFileToLoad = this._filesToLoad[i];
  7051. }
  7052. break;
  7053. }
  7054. }
  7055. this.reload();
  7056. }
  7057. };
  7058. FilesInput.prototype.reload = function () {
  7059. var _this = this;
  7060. var that = this;
  7061. // If a ".babylon" file has been provided
  7062. if (this._sceneFileToLoad) {
  7063. if (this._currentScene) {
  7064. if (BABYLON.Tools.errorsCount > 0) {
  7065. BABYLON.Tools.ClearLogCache();
  7066. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7067. }
  7068. this._engine.stopRenderLoop();
  7069. this._currentScene.dispose();
  7070. }
  7071. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7072. that._currentScene = newScene;
  7073. // Wait for textures and shaders to be ready
  7074. that._currentScene.executeWhenReady(function () {
  7075. // Attach camera to canvas inputs
  7076. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7077. that._currentScene.createDefaultCameraOrLight();
  7078. }
  7079. that._currentScene.activeCamera.attachControl(that._canvas);
  7080. if (that._sceneLoadedCallback) {
  7081. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7082. }
  7083. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7084. });
  7085. }, function (progress) {
  7086. if (_this._progressCallback) {
  7087. _this._progressCallback(progress);
  7088. }
  7089. });
  7090. }
  7091. else {
  7092. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7093. }
  7094. };
  7095. FilesInput.FilesTextures = new Array();
  7096. FilesInput.FilesToLoad = new Array();
  7097. return FilesInput;
  7098. })();
  7099. BABYLON.FilesInput = FilesInput;
  7100. })(BABYLON || (BABYLON = {}));
  7101. var BABYLON;
  7102. (function (BABYLON) {
  7103. var IntersectionInfo = (function () {
  7104. function IntersectionInfo(bu, bv, distance) {
  7105. this.bu = bu;
  7106. this.bv = bv;
  7107. this.distance = distance;
  7108. this.faceId = 0;
  7109. this.subMeshId = 0;
  7110. }
  7111. return IntersectionInfo;
  7112. })();
  7113. BABYLON.IntersectionInfo = IntersectionInfo;
  7114. var PickingInfo = (function () {
  7115. function PickingInfo() {
  7116. this.hit = false;
  7117. this.distance = 0;
  7118. this.pickedPoint = null;
  7119. this.pickedMesh = null;
  7120. this.bu = 0;
  7121. this.bv = 0;
  7122. this.faceId = -1;
  7123. this.subMeshId = 0;
  7124. this.pickedSprite = null;
  7125. }
  7126. // Methods
  7127. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7128. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7129. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7130. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7131. return null;
  7132. }
  7133. var indices = this.pickedMesh.getIndices();
  7134. var result;
  7135. if (useVerticesNormals) {
  7136. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7137. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7138. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7139. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7140. normal0 = normal0.scale(this.bu);
  7141. normal1 = normal1.scale(this.bv);
  7142. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7143. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7144. }
  7145. else {
  7146. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7147. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7148. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7149. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7150. var p1p2 = vertex1.subtract(vertex2);
  7151. var p3p2 = vertex3.subtract(vertex2);
  7152. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7153. }
  7154. if (useWorldCoordinates) {
  7155. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7156. }
  7157. return BABYLON.Vector3.Normalize(result);
  7158. };
  7159. PickingInfo.prototype.getTextureCoordinates = function () {
  7160. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7161. return null;
  7162. }
  7163. var indices = this.pickedMesh.getIndices();
  7164. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7165. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7166. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7167. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7168. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7169. uv1 = uv1.scale(this.bu);
  7170. uv2 = uv2.scale(this.bv);
  7171. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7172. };
  7173. return PickingInfo;
  7174. })();
  7175. BABYLON.PickingInfo = PickingInfo;
  7176. })(BABYLON || (BABYLON = {}));
  7177. var BABYLON;
  7178. (function (BABYLON) {
  7179. var BoundingSphere = (function () {
  7180. function BoundingSphere(minimum, maximum) {
  7181. this.minimum = minimum;
  7182. this.maximum = maximum;
  7183. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7184. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7185. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7186. this.radius = distance * 0.5;
  7187. this.centerWorld = BABYLON.Vector3.Zero();
  7188. this._update(BABYLON.Matrix.Identity());
  7189. }
  7190. // Methods
  7191. BoundingSphere.prototype._update = function (world) {
  7192. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7193. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7194. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7195. };
  7196. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7197. for (var i = 0; i < 6; i++) {
  7198. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7199. return false;
  7200. }
  7201. return true;
  7202. };
  7203. BoundingSphere.prototype.intersectsPoint = function (point) {
  7204. var x = this.centerWorld.x - point.x;
  7205. var y = this.centerWorld.y - point.y;
  7206. var z = this.centerWorld.z - point.z;
  7207. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7208. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7209. return false;
  7210. return true;
  7211. };
  7212. // Statics
  7213. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7214. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7215. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7216. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7217. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7218. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7219. return false;
  7220. return true;
  7221. };
  7222. return BoundingSphere;
  7223. })();
  7224. BABYLON.BoundingSphere = BoundingSphere;
  7225. })(BABYLON || (BABYLON = {}));
  7226. var BABYLON;
  7227. (function (BABYLON) {
  7228. var BoundingBox = (function () {
  7229. function BoundingBox(minimum, maximum) {
  7230. this.minimum = minimum;
  7231. this.maximum = maximum;
  7232. this.vectors = new Array();
  7233. this.vectorsWorld = new Array();
  7234. // Bounding vectors
  7235. this.vectors.push(this.minimum.clone());
  7236. this.vectors.push(this.maximum.clone());
  7237. this.vectors.push(this.minimum.clone());
  7238. this.vectors[2].x = this.maximum.x;
  7239. this.vectors.push(this.minimum.clone());
  7240. this.vectors[3].y = this.maximum.y;
  7241. this.vectors.push(this.minimum.clone());
  7242. this.vectors[4].z = this.maximum.z;
  7243. this.vectors.push(this.maximum.clone());
  7244. this.vectors[5].z = this.minimum.z;
  7245. this.vectors.push(this.maximum.clone());
  7246. this.vectors[6].x = this.minimum.x;
  7247. this.vectors.push(this.maximum.clone());
  7248. this.vectors[7].y = this.minimum.y;
  7249. // OBB
  7250. this.center = this.maximum.add(this.minimum).scale(0.5);
  7251. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7252. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7253. // World
  7254. for (var index = 0; index < this.vectors.length; index++) {
  7255. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7256. }
  7257. this.minimumWorld = BABYLON.Vector3.Zero();
  7258. this.maximumWorld = BABYLON.Vector3.Zero();
  7259. this._update(BABYLON.Matrix.Identity());
  7260. }
  7261. // Methods
  7262. BoundingBox.prototype.getWorldMatrix = function () {
  7263. return this._worldMatrix;
  7264. };
  7265. BoundingBox.prototype._update = function (world) {
  7266. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7267. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7268. for (var index = 0; index < this.vectors.length; index++) {
  7269. var v = this.vectorsWorld[index];
  7270. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7271. if (v.x < this.minimumWorld.x)
  7272. this.minimumWorld.x = v.x;
  7273. if (v.y < this.minimumWorld.y)
  7274. this.minimumWorld.y = v.y;
  7275. if (v.z < this.minimumWorld.z)
  7276. this.minimumWorld.z = v.z;
  7277. if (v.x > this.maximumWorld.x)
  7278. this.maximumWorld.x = v.x;
  7279. if (v.y > this.maximumWorld.y)
  7280. this.maximumWorld.y = v.y;
  7281. if (v.z > this.maximumWorld.z)
  7282. this.maximumWorld.z = v.z;
  7283. }
  7284. // OBB
  7285. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7286. this.center.scaleInPlace(0.5);
  7287. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7288. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7290. this._worldMatrix = world;
  7291. };
  7292. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7293. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7294. };
  7295. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7296. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7297. };
  7298. BoundingBox.prototype.intersectsPoint = function (point) {
  7299. var delta = -BABYLON.Engine.Epsilon;
  7300. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7301. return false;
  7302. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7303. return false;
  7304. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7305. return false;
  7306. return true;
  7307. };
  7308. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7309. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7310. };
  7311. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7312. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7313. return false;
  7314. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7315. return false;
  7316. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7317. return false;
  7318. return true;
  7319. };
  7320. // Statics
  7321. BoundingBox.Intersects = function (box0, box1) {
  7322. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7323. return false;
  7324. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7325. return false;
  7326. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7327. return false;
  7328. return true;
  7329. };
  7330. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7331. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7332. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7333. return (num <= (sphereRadius * sphereRadius));
  7334. };
  7335. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7336. for (var p = 0; p < 6; p++) {
  7337. for (var i = 0; i < 8; i++) {
  7338. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7339. return false;
  7340. }
  7341. }
  7342. }
  7343. return true;
  7344. };
  7345. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7346. for (var p = 0; p < 6; p++) {
  7347. var inCount = 8;
  7348. for (var i = 0; i < 8; i++) {
  7349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7350. --inCount;
  7351. }
  7352. else {
  7353. break;
  7354. }
  7355. }
  7356. if (inCount === 0)
  7357. return false;
  7358. }
  7359. return true;
  7360. };
  7361. return BoundingBox;
  7362. })();
  7363. BABYLON.BoundingBox = BoundingBox;
  7364. })(BABYLON || (BABYLON = {}));
  7365. var BABYLON;
  7366. (function (BABYLON) {
  7367. var computeBoxExtents = function (axis, box) {
  7368. var p = BABYLON.Vector3.Dot(box.center, axis);
  7369. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7370. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7371. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7372. var r = r0 + r1 + r2;
  7373. return {
  7374. min: p - r,
  7375. max: p + r
  7376. };
  7377. };
  7378. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7379. var axisOverlap = function (axis, box0, box1) {
  7380. var result0 = computeBoxExtents(axis, box0);
  7381. var result1 = computeBoxExtents(axis, box1);
  7382. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7383. };
  7384. var BoundingInfo = (function () {
  7385. function BoundingInfo(minimum, maximum) {
  7386. this.minimum = minimum;
  7387. this.maximum = maximum;
  7388. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7389. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7390. }
  7391. // Methods
  7392. BoundingInfo.prototype._update = function (world) {
  7393. this.boundingBox._update(world);
  7394. this.boundingSphere._update(world);
  7395. };
  7396. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7397. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7398. return false;
  7399. return this.boundingBox.isInFrustum(frustumPlanes);
  7400. };
  7401. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7402. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7403. };
  7404. BoundingInfo.prototype._checkCollision = function (collider) {
  7405. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7406. };
  7407. BoundingInfo.prototype.intersectsPoint = function (point) {
  7408. if (!this.boundingSphere.centerWorld) {
  7409. return false;
  7410. }
  7411. if (!this.boundingSphere.intersectsPoint(point)) {
  7412. return false;
  7413. }
  7414. if (!this.boundingBox.intersectsPoint(point)) {
  7415. return false;
  7416. }
  7417. return true;
  7418. };
  7419. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7420. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7421. return false;
  7422. }
  7423. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7424. return false;
  7425. }
  7426. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7427. return false;
  7428. }
  7429. if (!precise) {
  7430. return true;
  7431. }
  7432. var box0 = this.boundingBox;
  7433. var box1 = boundingInfo.boundingBox;
  7434. if (!axisOverlap(box0.directions[0], box0, box1))
  7435. return false;
  7436. if (!axisOverlap(box0.directions[1], box0, box1))
  7437. return false;
  7438. if (!axisOverlap(box0.directions[2], box0, box1))
  7439. return false;
  7440. if (!axisOverlap(box1.directions[0], box0, box1))
  7441. return false;
  7442. if (!axisOverlap(box1.directions[1], box0, box1))
  7443. return false;
  7444. if (!axisOverlap(box1.directions[2], box0, box1))
  7445. return false;
  7446. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7447. return false;
  7448. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7449. return false;
  7450. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7451. return false;
  7452. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7453. return false;
  7454. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7455. return false;
  7456. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7457. return false;
  7458. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7459. return false;
  7460. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7461. return false;
  7462. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7463. return false;
  7464. return true;
  7465. };
  7466. return BoundingInfo;
  7467. })();
  7468. BABYLON.BoundingInfo = BoundingInfo;
  7469. })(BABYLON || (BABYLON = {}));
  7470. var BABYLON;
  7471. (function (BABYLON) {
  7472. var AbstractMesh = (function (_super) {
  7473. __extends(AbstractMesh, _super);
  7474. function AbstractMesh(name, scene) {
  7475. var _this = this;
  7476. _super.call(this, name, scene);
  7477. // Properties
  7478. this.definedFacingForward = true; // orientation for POV movement & rotation
  7479. this.position = new BABYLON.Vector3(0, 0, 0);
  7480. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7481. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7482. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7483. this.visibility = 1.0;
  7484. this.alphaIndex = Number.MAX_VALUE;
  7485. this.infiniteDistance = false;
  7486. this.isVisible = true;
  7487. this.isPickable = true;
  7488. this.showBoundingBox = false;
  7489. this.showSubMeshesBoundingBox = false;
  7490. this.onDispose = null;
  7491. this.isBlocker = false;
  7492. this.renderingGroupId = 0;
  7493. this.receiveShadows = false;
  7494. this.renderOutline = false;
  7495. this.outlineColor = BABYLON.Color3.Red();
  7496. this.outlineWidth = 0.02;
  7497. this.renderOverlay = false;
  7498. this.overlayColor = BABYLON.Color3.Red();
  7499. this.overlayAlpha = 0.5;
  7500. this.hasVertexAlpha = false;
  7501. this.useVertexColors = true;
  7502. this.applyFog = true;
  7503. this.computeBonesUsingShaders = true;
  7504. this.scalingDeterminant = 1;
  7505. this.numBoneInfluencers = 4;
  7506. this.useOctreeForRenderingSelection = true;
  7507. this.useOctreeForPicking = true;
  7508. this.useOctreeForCollisions = true;
  7509. this.layerMask = 0x0FFFFFFF;
  7510. this.alwaysSelectAsActiveMesh = false;
  7511. // Physics
  7512. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7513. // Collisions
  7514. this._checkCollisions = false;
  7515. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7516. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7517. this._collider = new BABYLON.Collider();
  7518. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7519. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7520. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7521. // Edges
  7522. this.edgesWidth = 1;
  7523. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7524. // Cache
  7525. this._localScaling = BABYLON.Matrix.Zero();
  7526. this._localRotation = BABYLON.Matrix.Zero();
  7527. this._localTranslation = BABYLON.Matrix.Zero();
  7528. this._localBillboard = BABYLON.Matrix.Zero();
  7529. this._localPivotScaling = BABYLON.Matrix.Zero();
  7530. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7531. this._localWorld = BABYLON.Matrix.Zero();
  7532. this._worldMatrix = BABYLON.Matrix.Zero();
  7533. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7534. this._absolutePosition = BABYLON.Vector3.Zero();
  7535. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7536. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7537. this._isDirty = false;
  7538. this._pivotMatrix = BABYLON.Matrix.Identity();
  7539. this._isDisposed = false;
  7540. this._renderId = 0;
  7541. this._intersectionsInProgress = new Array();
  7542. this._onAfterWorldMatrixUpdate = new Array();
  7543. this._isWorldMatrixFrozen = false;
  7544. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7545. if (collidedMesh === void 0) { collidedMesh = null; }
  7546. //TODO move this to the collision coordinator!
  7547. if (_this.getScene().workerCollisions)
  7548. newPosition.multiplyInPlace(_this._collider.radius);
  7549. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7550. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7551. _this.position.addInPlace(_this._diffPositionForCollisions);
  7552. }
  7553. if (_this.onCollide && collidedMesh) {
  7554. _this.onCollide(collidedMesh);
  7555. }
  7556. if (_this.onCollisionPositionChange) {
  7557. _this.onCollisionPositionChange(_this.position);
  7558. }
  7559. };
  7560. scene.addMesh(this);
  7561. }
  7562. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7563. get: function () {
  7564. return AbstractMesh._BILLBOARDMODE_NONE;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7570. get: function () {
  7571. return AbstractMesh._BILLBOARDMODE_X;
  7572. },
  7573. enumerable: true,
  7574. configurable: true
  7575. });
  7576. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7577. get: function () {
  7578. return AbstractMesh._BILLBOARDMODE_Y;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7584. get: function () {
  7585. return AbstractMesh._BILLBOARDMODE_Z;
  7586. },
  7587. enumerable: true,
  7588. configurable: true
  7589. });
  7590. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7591. get: function () {
  7592. return AbstractMesh._BILLBOARDMODE_ALL;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. // Methods
  7598. AbstractMesh.prototype.disableEdgesRendering = function () {
  7599. if (this._edgesRenderer !== undefined) {
  7600. this._edgesRenderer.dispose();
  7601. this._edgesRenderer = undefined;
  7602. }
  7603. };
  7604. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7605. if (epsilon === void 0) { epsilon = 0.95; }
  7606. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7607. this.disableEdgesRendering();
  7608. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7609. };
  7610. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7611. get: function () {
  7612. return false;
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. AbstractMesh.prototype.getLOD = function (camera) {
  7618. return this;
  7619. };
  7620. AbstractMesh.prototype.getTotalVertices = function () {
  7621. return 0;
  7622. };
  7623. AbstractMesh.prototype.getIndices = function () {
  7624. return null;
  7625. };
  7626. AbstractMesh.prototype.getVerticesData = function (kind) {
  7627. return null;
  7628. };
  7629. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7630. return false;
  7631. };
  7632. AbstractMesh.prototype.getBoundingInfo = function () {
  7633. if (this._masterMesh) {
  7634. return this._masterMesh.getBoundingInfo();
  7635. }
  7636. if (!this._boundingInfo) {
  7637. this._updateBoundingInfo();
  7638. }
  7639. return this._boundingInfo;
  7640. };
  7641. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7642. get: function () {
  7643. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. AbstractMesh.prototype._preActivate = function () {
  7649. };
  7650. AbstractMesh.prototype._activate = function (renderId) {
  7651. this._renderId = renderId;
  7652. };
  7653. AbstractMesh.prototype.getWorldMatrix = function () {
  7654. if (this._masterMesh) {
  7655. return this._masterMesh.getWorldMatrix();
  7656. }
  7657. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7658. this.computeWorldMatrix();
  7659. }
  7660. return this._worldMatrix;
  7661. };
  7662. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7663. get: function () {
  7664. return this._worldMatrix;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7670. get: function () {
  7671. return this._absolutePosition;
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7677. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7678. this.computeWorldMatrix(true);
  7679. this._isWorldMatrixFrozen = true;
  7680. };
  7681. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7682. this._isWorldMatrixFrozen = false;
  7683. this.computeWorldMatrix(true);
  7684. };
  7685. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7686. get: function () {
  7687. return this._isWorldMatrixFrozen;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7693. axis.normalize();
  7694. if (!this.rotationQuaternion) {
  7695. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7696. this.rotation = BABYLON.Vector3.Zero();
  7697. }
  7698. var rotationQuaternion;
  7699. if (!space || space === BABYLON.Space.LOCAL) {
  7700. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7701. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7702. }
  7703. else {
  7704. if (this.parent) {
  7705. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7706. invertParentWorldMatrix.invert();
  7707. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7708. }
  7709. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7710. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7711. }
  7712. };
  7713. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7714. var displacementVector = axis.scale(distance);
  7715. if (!space || space === BABYLON.Space.LOCAL) {
  7716. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7717. this.setPositionWithLocalVector(tempV3);
  7718. }
  7719. else {
  7720. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7721. }
  7722. };
  7723. AbstractMesh.prototype.getAbsolutePosition = function () {
  7724. this.computeWorldMatrix();
  7725. return this._absolutePosition;
  7726. };
  7727. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7728. if (!absolutePosition) {
  7729. return;
  7730. }
  7731. var absolutePositionX;
  7732. var absolutePositionY;
  7733. var absolutePositionZ;
  7734. if (absolutePosition.x === undefined) {
  7735. if (arguments.length < 3) {
  7736. return;
  7737. }
  7738. absolutePositionX = arguments[0];
  7739. absolutePositionY = arguments[1];
  7740. absolutePositionZ = arguments[2];
  7741. }
  7742. else {
  7743. absolutePositionX = absolutePosition.x;
  7744. absolutePositionY = absolutePosition.y;
  7745. absolutePositionZ = absolutePosition.z;
  7746. }
  7747. if (this.parent) {
  7748. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7749. invertParentWorldMatrix.invert();
  7750. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7751. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7752. }
  7753. else {
  7754. this.position.x = absolutePositionX;
  7755. this.position.y = absolutePositionY;
  7756. this.position.z = absolutePositionZ;
  7757. }
  7758. };
  7759. // ================================== Point of View Movement =================================
  7760. /**
  7761. * Perform relative position change from the point of view of behind the front of the mesh.
  7762. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7763. * Supports definition of mesh facing forward or backward.
  7764. * @param {number} amountRight
  7765. * @param {number} amountUp
  7766. * @param {number} amountForward
  7767. */
  7768. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7769. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7770. };
  7771. /**
  7772. * Calculate relative position change from the point of view of behind the front of the mesh.
  7773. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7774. * Supports definition of mesh facing forward or backward.
  7775. * @param {number} amountRight
  7776. * @param {number} amountUp
  7777. * @param {number} amountForward
  7778. */
  7779. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7780. var rotMatrix = new BABYLON.Matrix();
  7781. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7782. rotQuaternion.toRotationMatrix(rotMatrix);
  7783. var translationDelta = BABYLON.Vector3.Zero();
  7784. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7785. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7786. return translationDelta;
  7787. };
  7788. // ================================== Point of View Rotation =================================
  7789. /**
  7790. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7791. * Supports definition of mesh facing forward or backward.
  7792. * @param {number} flipBack
  7793. * @param {number} twirlClockwise
  7794. * @param {number} tiltRight
  7795. */
  7796. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7797. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7798. };
  7799. /**
  7800. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7801. * Supports definition of mesh facing forward or backward.
  7802. * @param {number} flipBack
  7803. * @param {number} twirlClockwise
  7804. * @param {number} tiltRight
  7805. */
  7806. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7807. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7808. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7809. };
  7810. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7811. this._pivotMatrix = matrix;
  7812. this._cache.pivotMatrixUpdated = true;
  7813. };
  7814. AbstractMesh.prototype.getPivotMatrix = function () {
  7815. return this._pivotMatrix;
  7816. };
  7817. AbstractMesh.prototype._isSynchronized = function () {
  7818. if (this._isDirty) {
  7819. return false;
  7820. }
  7821. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7822. return false;
  7823. if (this._cache.pivotMatrixUpdated) {
  7824. return false;
  7825. }
  7826. if (this.infiniteDistance) {
  7827. return false;
  7828. }
  7829. if (!this._cache.position.equals(this.position))
  7830. return false;
  7831. if (this.rotationQuaternion) {
  7832. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7833. return false;
  7834. }
  7835. else {
  7836. if (!this._cache.rotation.equals(this.rotation))
  7837. return false;
  7838. }
  7839. if (!this._cache.scaling.equals(this.scaling))
  7840. return false;
  7841. return true;
  7842. };
  7843. AbstractMesh.prototype._initCache = function () {
  7844. _super.prototype._initCache.call(this);
  7845. this._cache.localMatrixUpdated = false;
  7846. this._cache.position = BABYLON.Vector3.Zero();
  7847. this._cache.scaling = BABYLON.Vector3.Zero();
  7848. this._cache.rotation = BABYLON.Vector3.Zero();
  7849. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7850. this._cache.billboardMode = -1;
  7851. };
  7852. AbstractMesh.prototype.markAsDirty = function (property) {
  7853. if (property === "rotation") {
  7854. this.rotationQuaternion = null;
  7855. }
  7856. this._currentRenderId = Number.MAX_VALUE;
  7857. this._isDirty = true;
  7858. };
  7859. AbstractMesh.prototype._updateBoundingInfo = function () {
  7860. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7861. this._boundingInfo._update(this.worldMatrixFromCache);
  7862. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7863. };
  7864. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7865. if (!this.subMeshes) {
  7866. return;
  7867. }
  7868. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7869. var subMesh = this.subMeshes[subIndex];
  7870. subMesh.updateBoundingInfo(matrix);
  7871. }
  7872. };
  7873. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7874. if (this._isWorldMatrixFrozen) {
  7875. return this._worldMatrix;
  7876. }
  7877. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7878. return this._worldMatrix;
  7879. }
  7880. this._cache.position.copyFrom(this.position);
  7881. this._cache.scaling.copyFrom(this.scaling);
  7882. this._cache.pivotMatrixUpdated = false;
  7883. this._cache.billboardMode = this.billboardMode;
  7884. this._currentRenderId = this.getScene().getRenderId();
  7885. this._isDirty = false;
  7886. // Scaling
  7887. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7888. // Rotation
  7889. if (this.rotationQuaternion) {
  7890. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7891. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7892. }
  7893. else {
  7894. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7895. this._cache.rotation.copyFrom(this.rotation);
  7896. }
  7897. // Translation
  7898. if (this.infiniteDistance && !this.parent) {
  7899. var camera = this.getScene().activeCamera;
  7900. if (camera) {
  7901. var cameraWorldMatrix = camera.getWorldMatrix();
  7902. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7903. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7904. }
  7905. }
  7906. else {
  7907. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7908. }
  7909. // Composing transformations
  7910. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7911. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7912. // Billboarding
  7913. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7914. var localPosition = this.position.clone();
  7915. var zero = this.getScene().activeCamera.globalPosition.clone();
  7916. if (this.parent && this.parent.position) {
  7917. localPosition.addInPlace(this.parent.position);
  7918. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7919. }
  7920. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7921. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7922. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7923. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7924. zero.y = localPosition.y + 0.001;
  7925. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7926. zero.z = localPosition.z + 0.001;
  7927. }
  7928. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7929. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7930. this._localBillboard.invert();
  7931. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7932. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7933. }
  7934. // Local world
  7935. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7936. // Parent
  7937. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7938. this._markSyncedWithParent();
  7939. if (this._meshToBoneReferal) {
  7940. if (!this._localMeshReferalTransform) {
  7941. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7942. }
  7943. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7944. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7945. }
  7946. else {
  7947. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7948. }
  7949. }
  7950. else {
  7951. this._worldMatrix.copyFrom(this._localWorld);
  7952. }
  7953. // Bounding info
  7954. this._updateBoundingInfo();
  7955. // Absolute position
  7956. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7957. // Callbacks
  7958. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7959. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7960. }
  7961. return this._worldMatrix;
  7962. };
  7963. /**
  7964. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7965. * @param func: callback function to add
  7966. */
  7967. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7968. this._onAfterWorldMatrixUpdate.push(func);
  7969. };
  7970. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7971. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7972. if (index > -1) {
  7973. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7974. }
  7975. };
  7976. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7977. this.computeWorldMatrix();
  7978. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7979. };
  7980. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7981. this.computeWorldMatrix();
  7982. var invLocalWorldMatrix = this._localWorld.clone();
  7983. invLocalWorldMatrix.invert();
  7984. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7985. };
  7986. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7987. this.computeWorldMatrix(true);
  7988. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7989. };
  7990. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7991. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7992. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7993. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7994. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7995. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7996. /// <returns>Mesh oriented towards targetMesh</returns>
  7997. yawCor = yawCor || 0; // default to zero if undefined
  7998. pitchCor = pitchCor || 0;
  7999. rollCor = rollCor || 0;
  8000. var dv = targetPoint.subtract(this.position);
  8001. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8002. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8003. var pitch = Math.atan2(dv.y, len);
  8004. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8005. };
  8006. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8007. this._meshToBoneReferal = affectedMesh;
  8008. this.parent = bone;
  8009. if (bone.getWorldMatrix().determinant() < 0) {
  8010. this.scalingDeterminant *= -1;
  8011. }
  8012. };
  8013. AbstractMesh.prototype.detachFromBone = function () {
  8014. if (this.parent.getWorldMatrix().determinant() < 0) {
  8015. this.scalingDeterminant *= -1;
  8016. }
  8017. this._meshToBoneReferal = null;
  8018. this.parent = null;
  8019. };
  8020. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8021. return this._boundingInfo.isInFrustum(frustumPlanes);
  8022. };
  8023. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8024. if (!camera) {
  8025. camera = this.getScene().activeCamera;
  8026. }
  8027. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8028. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8029. return false;
  8030. }
  8031. return true;
  8032. };
  8033. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8034. if (!this._boundingInfo || !mesh._boundingInfo) {
  8035. return false;
  8036. }
  8037. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8038. };
  8039. AbstractMesh.prototype.intersectsPoint = function (point) {
  8040. if (!this._boundingInfo) {
  8041. return false;
  8042. }
  8043. return this._boundingInfo.intersectsPoint(point);
  8044. };
  8045. // Physics
  8046. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8047. var physicsEngine = this.getScene().getPhysicsEngine();
  8048. if (!physicsEngine) {
  8049. return null;
  8050. }
  8051. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8052. if (impostor.impostor) {
  8053. // Old API
  8054. options = impostor;
  8055. impostor = impostor.impostor;
  8056. }
  8057. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8058. physicsEngine._unregisterMesh(this);
  8059. return null;
  8060. }
  8061. if (!options) {
  8062. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8063. }
  8064. else {
  8065. if (!options.mass && options.mass !== 0)
  8066. options.mass = 0;
  8067. if (!options.friction && options.friction !== 0)
  8068. options.friction = 0.2;
  8069. if (!options.restitution && options.restitution !== 0)
  8070. options.restitution = 0.2;
  8071. }
  8072. this._physicImpostor = impostor;
  8073. this._physicsMass = options.mass;
  8074. this._physicsFriction = options.friction;
  8075. this._physicRestitution = options.restitution;
  8076. return physicsEngine._registerMesh(this, impostor, options);
  8077. };
  8078. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8079. if (!this._physicImpostor) {
  8080. return BABYLON.PhysicsEngine.NoImpostor;
  8081. }
  8082. return this._physicImpostor;
  8083. };
  8084. AbstractMesh.prototype.getPhysicsMass = function () {
  8085. if (!this._physicsMass) {
  8086. return 0;
  8087. }
  8088. return this._physicsMass;
  8089. };
  8090. AbstractMesh.prototype.getPhysicsFriction = function () {
  8091. if (!this._physicsFriction) {
  8092. return 0;
  8093. }
  8094. return this._physicsFriction;
  8095. };
  8096. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8097. if (!this._physicRestitution) {
  8098. return 0;
  8099. }
  8100. return this._physicRestitution;
  8101. };
  8102. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8103. if (!camera) {
  8104. camera = this.getScene().activeCamera;
  8105. }
  8106. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8107. };
  8108. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8109. if (!camera) {
  8110. camera = this.getScene().activeCamera;
  8111. }
  8112. return this.absolutePosition.subtract(camera.position).length();
  8113. };
  8114. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8115. if (!this._physicImpostor) {
  8116. return;
  8117. }
  8118. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8119. };
  8120. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8121. if (!this._physicImpostor) {
  8122. return;
  8123. }
  8124. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8125. };
  8126. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8127. if (!this._physicImpostor) {
  8128. return;
  8129. }
  8130. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8131. };
  8132. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8133. // Collisions
  8134. get: function () {
  8135. return this._checkCollisions;
  8136. },
  8137. set: function (collisionEnabled) {
  8138. this._checkCollisions = collisionEnabled;
  8139. if (this.getScene().workerCollisions) {
  8140. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8141. }
  8142. },
  8143. enumerable: true,
  8144. configurable: true
  8145. });
  8146. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8147. var globalPosition = this.getAbsolutePosition();
  8148. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8149. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8150. this._collider.radius = this.ellipsoid;
  8151. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8152. };
  8153. // Submeshes octree
  8154. /**
  8155. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8156. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8157. */
  8158. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8159. if (maxCapacity === void 0) { maxCapacity = 64; }
  8160. if (maxDepth === void 0) { maxDepth = 2; }
  8161. if (!this._submeshesOctree) {
  8162. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8163. }
  8164. this.computeWorldMatrix(true);
  8165. // Update octree
  8166. var bbox = this.getBoundingInfo().boundingBox;
  8167. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8168. return this._submeshesOctree;
  8169. };
  8170. // Collisions
  8171. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8172. this._generatePointsArray();
  8173. // Transformation
  8174. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8175. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8176. subMesh._lastColliderWorldVertices = [];
  8177. subMesh._trianglePlanes = [];
  8178. var start = subMesh.verticesStart;
  8179. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8180. for (var i = start; i < end; i++) {
  8181. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8182. }
  8183. }
  8184. // Collide
  8185. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8186. if (collider.collisionFound) {
  8187. collider.collidedMesh = this;
  8188. }
  8189. };
  8190. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8191. var subMeshes;
  8192. var len;
  8193. // Octrees
  8194. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8195. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8196. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8197. len = intersections.length;
  8198. subMeshes = intersections.data;
  8199. }
  8200. else {
  8201. subMeshes = this.subMeshes;
  8202. len = subMeshes.length;
  8203. }
  8204. for (var index = 0; index < len; index++) {
  8205. var subMesh = subMeshes[index];
  8206. // Bounding test
  8207. if (len > 1 && !subMesh._checkCollision(collider))
  8208. continue;
  8209. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8210. }
  8211. };
  8212. AbstractMesh.prototype._checkCollision = function (collider) {
  8213. // Bounding box test
  8214. if (!this._boundingInfo._checkCollision(collider))
  8215. return;
  8216. // Transformation matrix
  8217. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8218. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8219. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8220. };
  8221. // Picking
  8222. AbstractMesh.prototype._generatePointsArray = function () {
  8223. return false;
  8224. };
  8225. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8226. var pickingInfo = new BABYLON.PickingInfo();
  8227. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8228. return pickingInfo;
  8229. }
  8230. if (!this._generatePointsArray()) {
  8231. return pickingInfo;
  8232. }
  8233. var intersectInfo = null;
  8234. // Octrees
  8235. var subMeshes;
  8236. var len;
  8237. if (this._submeshesOctree && this.useOctreeForPicking) {
  8238. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8239. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8240. len = intersections.length;
  8241. subMeshes = intersections.data;
  8242. }
  8243. else {
  8244. subMeshes = this.subMeshes;
  8245. len = subMeshes.length;
  8246. }
  8247. for (var index = 0; index < len; index++) {
  8248. var subMesh = subMeshes[index];
  8249. // Bounding test
  8250. if (len > 1 && !subMesh.canIntersects(ray))
  8251. continue;
  8252. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8253. if (currentIntersectInfo) {
  8254. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8255. intersectInfo = currentIntersectInfo;
  8256. intersectInfo.subMeshId = index;
  8257. if (fastCheck) {
  8258. break;
  8259. }
  8260. }
  8261. }
  8262. }
  8263. if (intersectInfo) {
  8264. // Get picked point
  8265. var world = this.getWorldMatrix();
  8266. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8267. var direction = ray.direction.clone();
  8268. direction = direction.scale(intersectInfo.distance);
  8269. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8270. var pickedPoint = worldOrigin.add(worldDirection);
  8271. // Return result
  8272. pickingInfo.hit = true;
  8273. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8274. pickingInfo.pickedPoint = pickedPoint;
  8275. pickingInfo.pickedMesh = this;
  8276. pickingInfo.bu = intersectInfo.bu;
  8277. pickingInfo.bv = intersectInfo.bv;
  8278. pickingInfo.faceId = intersectInfo.faceId;
  8279. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8280. return pickingInfo;
  8281. }
  8282. return pickingInfo;
  8283. };
  8284. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8285. return null;
  8286. };
  8287. AbstractMesh.prototype.releaseSubMeshes = function () {
  8288. if (this.subMeshes) {
  8289. while (this.subMeshes.length) {
  8290. this.subMeshes[0].dispose();
  8291. }
  8292. }
  8293. else {
  8294. this.subMeshes = new Array();
  8295. }
  8296. };
  8297. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8298. var index;
  8299. // Animations
  8300. this.getScene().stopAnimation(this);
  8301. // Physics
  8302. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8303. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8304. }
  8305. // Intersections in progress
  8306. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8307. var other = this._intersectionsInProgress[index];
  8308. var pos = other._intersectionsInProgress.indexOf(this);
  8309. other._intersectionsInProgress.splice(pos, 1);
  8310. }
  8311. this._intersectionsInProgress = [];
  8312. // Edges
  8313. if (this._edgesRenderer) {
  8314. this._edgesRenderer.dispose();
  8315. this._edgesRenderer = null;
  8316. }
  8317. // SubMeshes
  8318. this.releaseSubMeshes();
  8319. // Remove from scene
  8320. this.getScene().removeMesh(this);
  8321. if (!doNotRecurse) {
  8322. // Particles
  8323. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8324. if (this.getScene().particleSystems[index].emitter === this) {
  8325. this.getScene().particleSystems[index].dispose();
  8326. index--;
  8327. }
  8328. }
  8329. // Children
  8330. var objects = this.getScene().meshes.slice(0);
  8331. for (index = 0; index < objects.length; index++) {
  8332. if (objects[index].parent === this) {
  8333. objects[index].dispose();
  8334. }
  8335. }
  8336. }
  8337. else {
  8338. for (index = 0; index < this.getScene().meshes.length; index++) {
  8339. var obj = this.getScene().meshes[index];
  8340. if (obj.parent === this) {
  8341. obj.parent = null;
  8342. obj.computeWorldMatrix(true);
  8343. }
  8344. }
  8345. }
  8346. this._onAfterWorldMatrixUpdate = [];
  8347. this._isDisposed = true;
  8348. // Callback
  8349. if (this.onDispose) {
  8350. this.onDispose();
  8351. }
  8352. };
  8353. // Statics
  8354. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8355. AbstractMesh._BILLBOARDMODE_X = 1;
  8356. AbstractMesh._BILLBOARDMODE_Y = 2;
  8357. AbstractMesh._BILLBOARDMODE_Z = 4;
  8358. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8359. return AbstractMesh;
  8360. })(BABYLON.Node);
  8361. BABYLON.AbstractMesh = AbstractMesh;
  8362. })(BABYLON || (BABYLON = {}));
  8363. var BABYLON;
  8364. (function (BABYLON) {
  8365. var Light = (function (_super) {
  8366. __extends(Light, _super);
  8367. function Light(name, scene) {
  8368. _super.call(this, name, scene);
  8369. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8370. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8371. this.intensity = 1.0;
  8372. this.range = Number.MAX_VALUE;
  8373. this.includeOnlyWithLayerMask = 0;
  8374. this.includedOnlyMeshes = new Array();
  8375. this.excludedMeshes = new Array();
  8376. this.excludeWithLayerMask = 0;
  8377. this._excludedMeshesIds = new Array();
  8378. this._includedOnlyMeshesIds = new Array();
  8379. scene.addLight(this);
  8380. }
  8381. Light.prototype.getShadowGenerator = function () {
  8382. return this._shadowGenerator;
  8383. };
  8384. Light.prototype.getAbsolutePosition = function () {
  8385. return BABYLON.Vector3.Zero();
  8386. };
  8387. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8388. };
  8389. Light.prototype._getWorldMatrix = function () {
  8390. return BABYLON.Matrix.Identity();
  8391. };
  8392. Light.prototype.canAffectMesh = function (mesh) {
  8393. if (!mesh) {
  8394. return true;
  8395. }
  8396. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8397. return false;
  8398. }
  8399. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8400. return false;
  8401. }
  8402. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8403. return false;
  8404. }
  8405. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8406. return false;
  8407. }
  8408. return true;
  8409. };
  8410. Light.prototype.getWorldMatrix = function () {
  8411. this._currentRenderId = this.getScene().getRenderId();
  8412. var worldMatrix = this._getWorldMatrix();
  8413. if (this.parent && this.parent.getWorldMatrix) {
  8414. if (!this._parentedWorldMatrix) {
  8415. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8416. }
  8417. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8418. this._markSyncedWithParent();
  8419. return this._parentedWorldMatrix;
  8420. }
  8421. return worldMatrix;
  8422. };
  8423. Light.prototype.dispose = function () {
  8424. if (this._shadowGenerator) {
  8425. this._shadowGenerator.dispose();
  8426. this._shadowGenerator = null;
  8427. }
  8428. // Animations
  8429. this.getScene().stopAnimation(this);
  8430. // Remove from scene
  8431. this.getScene().removeLight(this);
  8432. };
  8433. return Light;
  8434. })(BABYLON.Node);
  8435. BABYLON.Light = Light;
  8436. })(BABYLON || (BABYLON = {}));
  8437. var BABYLON;
  8438. (function (BABYLON) {
  8439. var PointLight = (function (_super) {
  8440. __extends(PointLight, _super);
  8441. function PointLight(name, position, scene) {
  8442. _super.call(this, name, scene);
  8443. this.position = position;
  8444. }
  8445. PointLight.prototype.getAbsolutePosition = function () {
  8446. return this.transformedPosition ? this.transformedPosition : this.position;
  8447. };
  8448. PointLight.prototype.computeTransformedPosition = function () {
  8449. if (this.parent && this.parent.getWorldMatrix) {
  8450. if (!this.transformedPosition) {
  8451. this.transformedPosition = BABYLON.Vector3.Zero();
  8452. }
  8453. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8454. return true;
  8455. }
  8456. return false;
  8457. };
  8458. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8459. if (this.parent && this.parent.getWorldMatrix) {
  8460. this.computeTransformedPosition();
  8461. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8462. return;
  8463. }
  8464. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8465. };
  8466. PointLight.prototype.needCube = function () {
  8467. return true;
  8468. };
  8469. PointLight.prototype.supportsVSM = function () {
  8470. return false;
  8471. };
  8472. PointLight.prototype.needRefreshPerFrame = function () {
  8473. return false;
  8474. };
  8475. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8476. switch (faceIndex) {
  8477. case 0:
  8478. return new BABYLON.Vector3(1, 0, 0);
  8479. case 1:
  8480. return new BABYLON.Vector3(-1, 0, 0);
  8481. case 2:
  8482. return new BABYLON.Vector3(0, -1, 0);
  8483. case 3:
  8484. return new BABYLON.Vector3(0, 1, 0);
  8485. case 4:
  8486. return new BABYLON.Vector3(0, 0, 1);
  8487. case 5:
  8488. return new BABYLON.Vector3(0, 0, -1);
  8489. }
  8490. return BABYLON.Vector3.Zero();
  8491. };
  8492. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8493. var activeCamera = this.getScene().activeCamera;
  8494. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8495. };
  8496. PointLight.prototype._getWorldMatrix = function () {
  8497. if (!this._worldMatrix) {
  8498. this._worldMatrix = BABYLON.Matrix.Identity();
  8499. }
  8500. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8501. return this._worldMatrix;
  8502. };
  8503. return PointLight;
  8504. })(BABYLON.Light);
  8505. BABYLON.PointLight = PointLight;
  8506. })(BABYLON || (BABYLON = {}));
  8507. var BABYLON;
  8508. (function (BABYLON) {
  8509. var SpotLight = (function (_super) {
  8510. __extends(SpotLight, _super);
  8511. function SpotLight(name, position, direction, angle, exponent, scene) {
  8512. _super.call(this, name, scene);
  8513. this.position = position;
  8514. this.direction = direction;
  8515. this.angle = angle;
  8516. this.exponent = exponent;
  8517. }
  8518. SpotLight.prototype.getAbsolutePosition = function () {
  8519. return this.transformedPosition ? this.transformedPosition : this.position;
  8520. };
  8521. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8522. var activeCamera = this.getScene().activeCamera;
  8523. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8524. };
  8525. SpotLight.prototype.needCube = function () {
  8526. return false;
  8527. };
  8528. SpotLight.prototype.supportsVSM = function () {
  8529. return true;
  8530. };
  8531. SpotLight.prototype.needRefreshPerFrame = function () {
  8532. return false;
  8533. };
  8534. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8535. return this.direction;
  8536. };
  8537. SpotLight.prototype.setDirectionToTarget = function (target) {
  8538. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8539. return this.direction;
  8540. };
  8541. SpotLight.prototype.computeTransformedPosition = function () {
  8542. if (this.parent && this.parent.getWorldMatrix) {
  8543. if (!this.transformedPosition) {
  8544. this.transformedPosition = BABYLON.Vector3.Zero();
  8545. }
  8546. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8547. return true;
  8548. }
  8549. return false;
  8550. };
  8551. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8552. var normalizeDirection;
  8553. if (this.parent && this.parent.getWorldMatrix) {
  8554. if (!this._transformedDirection) {
  8555. this._transformedDirection = BABYLON.Vector3.Zero();
  8556. }
  8557. this.computeTransformedPosition();
  8558. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8559. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8560. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8561. }
  8562. else {
  8563. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8564. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8565. }
  8566. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8567. };
  8568. SpotLight.prototype._getWorldMatrix = function () {
  8569. if (!this._worldMatrix) {
  8570. this._worldMatrix = BABYLON.Matrix.Identity();
  8571. }
  8572. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8573. return this._worldMatrix;
  8574. };
  8575. return SpotLight;
  8576. })(BABYLON.Light);
  8577. BABYLON.SpotLight = SpotLight;
  8578. })(BABYLON || (BABYLON = {}));
  8579. var BABYLON;
  8580. (function (BABYLON) {
  8581. var HemisphericLight = (function (_super) {
  8582. __extends(HemisphericLight, _super);
  8583. function HemisphericLight(name, direction, scene) {
  8584. _super.call(this, name, scene);
  8585. this.direction = direction;
  8586. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8587. }
  8588. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8589. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8590. return this.direction;
  8591. };
  8592. HemisphericLight.prototype.getShadowGenerator = function () {
  8593. return null;
  8594. };
  8595. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8596. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8597. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8598. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8599. };
  8600. HemisphericLight.prototype._getWorldMatrix = function () {
  8601. if (!this._worldMatrix) {
  8602. this._worldMatrix = BABYLON.Matrix.Identity();
  8603. }
  8604. return this._worldMatrix;
  8605. };
  8606. return HemisphericLight;
  8607. })(BABYLON.Light);
  8608. BABYLON.HemisphericLight = HemisphericLight;
  8609. })(BABYLON || (BABYLON = {}));
  8610. var BABYLON;
  8611. (function (BABYLON) {
  8612. var DirectionalLight = (function (_super) {
  8613. __extends(DirectionalLight, _super);
  8614. function DirectionalLight(name, direction, scene) {
  8615. _super.call(this, name, scene);
  8616. this.direction = direction;
  8617. this.shadowOrthoScale = 0.5;
  8618. this.autoUpdateExtends = true;
  8619. // Cache
  8620. this._orthoLeft = Number.MAX_VALUE;
  8621. this._orthoRight = Number.MIN_VALUE;
  8622. this._orthoTop = Number.MIN_VALUE;
  8623. this._orthoBottom = Number.MAX_VALUE;
  8624. this.position = direction.scale(-1);
  8625. }
  8626. DirectionalLight.prototype.getAbsolutePosition = function () {
  8627. return this.transformedPosition ? this.transformedPosition : this.position;
  8628. };
  8629. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8630. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8631. return this.direction;
  8632. };
  8633. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8634. var activeCamera = this.getScene().activeCamera;
  8635. // Check extends
  8636. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8637. var tempVector3 = BABYLON.Vector3.Zero();
  8638. this._orthoLeft = Number.MAX_VALUE;
  8639. this._orthoRight = Number.MIN_VALUE;
  8640. this._orthoTop = Number.MIN_VALUE;
  8641. this._orthoBottom = Number.MAX_VALUE;
  8642. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8643. var mesh = renderList[meshIndex];
  8644. if (!mesh) {
  8645. continue;
  8646. }
  8647. var boundingInfo = mesh.getBoundingInfo();
  8648. if (!boundingInfo) {
  8649. continue;
  8650. }
  8651. var boundingBox = boundingInfo.boundingBox;
  8652. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8653. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8654. if (tempVector3.x < this._orthoLeft)
  8655. this._orthoLeft = tempVector3.x;
  8656. if (tempVector3.y < this._orthoBottom)
  8657. this._orthoBottom = tempVector3.y;
  8658. if (tempVector3.x > this._orthoRight)
  8659. this._orthoRight = tempVector3.x;
  8660. if (tempVector3.y > this._orthoTop)
  8661. this._orthoTop = tempVector3.y;
  8662. }
  8663. }
  8664. }
  8665. var xOffset = this._orthoRight - this._orthoLeft;
  8666. var yOffset = this._orthoTop - this._orthoBottom;
  8667. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8668. };
  8669. DirectionalLight.prototype.supportsVSM = function () {
  8670. return true;
  8671. };
  8672. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8673. return true;
  8674. };
  8675. DirectionalLight.prototype.needCube = function () {
  8676. return false;
  8677. };
  8678. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  8679. return this.direction;
  8680. };
  8681. DirectionalLight.prototype.computeTransformedPosition = function () {
  8682. if (this.parent && this.parent.getWorldMatrix) {
  8683. if (!this.transformedPosition) {
  8684. this.transformedPosition = BABYLON.Vector3.Zero();
  8685. }
  8686. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8687. return true;
  8688. }
  8689. return false;
  8690. };
  8691. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8692. if (this.parent && this.parent.getWorldMatrix) {
  8693. if (!this._transformedDirection) {
  8694. this._transformedDirection = BABYLON.Vector3.Zero();
  8695. }
  8696. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8697. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8698. return;
  8699. }
  8700. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8701. };
  8702. DirectionalLight.prototype._getWorldMatrix = function () {
  8703. if (!this._worldMatrix) {
  8704. this._worldMatrix = BABYLON.Matrix.Identity();
  8705. }
  8706. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8707. return this._worldMatrix;
  8708. };
  8709. return DirectionalLight;
  8710. })(BABYLON.Light);
  8711. BABYLON.DirectionalLight = DirectionalLight;
  8712. })(BABYLON || (BABYLON = {}));
  8713. var BABYLON;
  8714. (function (BABYLON) {
  8715. var ShadowGenerator = (function () {
  8716. function ShadowGenerator(mapSize, light) {
  8717. var _this = this;
  8718. // Members
  8719. this._filter = ShadowGenerator.FILTER_NONE;
  8720. this.blurScale = 2;
  8721. this._blurBoxOffset = 0;
  8722. this._bias = 0.00005;
  8723. this._lightDirection = BABYLON.Vector3.Zero();
  8724. this._darkness = 0;
  8725. this._transparencyShadow = false;
  8726. this._viewMatrix = BABYLON.Matrix.Zero();
  8727. this._projectionMatrix = BABYLON.Matrix.Zero();
  8728. this._transformMatrix = BABYLON.Matrix.Zero();
  8729. this._worldViewProjection = BABYLON.Matrix.Zero();
  8730. this._currentFaceIndex = 0;
  8731. this._currentFaceIndexCache = 0;
  8732. this._light = light;
  8733. this._scene = light.getScene();
  8734. this._mapSize = mapSize;
  8735. light._shadowGenerator = this;
  8736. // Render target
  8737. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  8738. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8739. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8740. this._shadowMap.anisotropicFilteringLevel = 1;
  8741. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8742. this._shadowMap.renderParticles = false;
  8743. this._shadowMap.onBeforeRender = function (faceIndex) {
  8744. _this._currentFaceIndex = faceIndex;
  8745. };
  8746. this._shadowMap.onAfterUnbind = function () {
  8747. if (!_this.useBlurVarianceShadowMap) {
  8748. return;
  8749. }
  8750. if (!_this._shadowMap2) {
  8751. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8752. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8753. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8754. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8755. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8756. _this._downSamplePostprocess.onApply = function (effect) {
  8757. effect.setTexture("textureSampler", _this._shadowMap);
  8758. };
  8759. _this.blurBoxOffset = 1;
  8760. }
  8761. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8762. };
  8763. // Custom render function
  8764. var renderSubMesh = function (subMesh) {
  8765. var mesh = subMesh.getRenderingMesh();
  8766. var scene = _this._scene;
  8767. var engine = scene.getEngine();
  8768. // Culling
  8769. engine.setState(subMesh.getMaterial().backFaceCulling);
  8770. // Managing instances
  8771. var batch = mesh._getInstancesRenderList(subMesh._id);
  8772. if (batch.mustReturn) {
  8773. return;
  8774. }
  8775. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8776. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8777. engine.enableEffect(_this._effect);
  8778. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8779. var material = subMesh.getMaterial();
  8780. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8781. // Alpha test
  8782. if (material && material.needAlphaTesting()) {
  8783. var alphaTexture = material.getAlphaTestTexture();
  8784. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8785. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8786. }
  8787. // Bones
  8788. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8789. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8790. }
  8791. // Draw
  8792. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8793. }
  8794. else {
  8795. // Need to reset refresh rate of the shadowMap
  8796. _this._shadowMap.resetRefreshCounter();
  8797. }
  8798. };
  8799. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8800. var index;
  8801. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8802. renderSubMesh(opaqueSubMeshes.data[index]);
  8803. }
  8804. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8805. renderSubMesh(alphaTestSubMeshes.data[index]);
  8806. }
  8807. if (_this._transparencyShadow) {
  8808. for (index = 0; index < transparentSubMeshes.length; index++) {
  8809. renderSubMesh(transparentSubMeshes.data[index]);
  8810. }
  8811. }
  8812. };
  8813. this._shadowMap.onClear = function (engine) {
  8814. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8815. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8816. }
  8817. else {
  8818. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8819. }
  8820. };
  8821. }
  8822. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8823. // Static
  8824. get: function () {
  8825. return ShadowGenerator._FILTER_NONE;
  8826. },
  8827. enumerable: true,
  8828. configurable: true
  8829. });
  8830. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8831. get: function () {
  8832. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8838. get: function () {
  8839. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8840. },
  8841. enumerable: true,
  8842. configurable: true
  8843. });
  8844. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8845. get: function () {
  8846. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8847. },
  8848. enumerable: true,
  8849. configurable: true
  8850. });
  8851. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8852. get: function () {
  8853. return this._bias;
  8854. },
  8855. set: function (bias) {
  8856. this._bias = bias;
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8862. get: function () {
  8863. return this._blurBoxOffset;
  8864. },
  8865. set: function (value) {
  8866. var _this = this;
  8867. if (this._blurBoxOffset === value) {
  8868. return;
  8869. }
  8870. this._blurBoxOffset = value;
  8871. if (this._boxBlurPostprocess) {
  8872. this._boxBlurPostprocess.dispose();
  8873. }
  8874. 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);
  8875. this._boxBlurPostprocess.onApply = function (effect) {
  8876. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8877. };
  8878. },
  8879. enumerable: true,
  8880. configurable: true
  8881. });
  8882. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8883. get: function () {
  8884. return this._filter;
  8885. },
  8886. set: function (value) {
  8887. if (this._filter === value) {
  8888. return;
  8889. }
  8890. this._filter = value;
  8891. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  8892. this._shadowMap.anisotropicFilteringLevel = 16;
  8893. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8894. }
  8895. else {
  8896. this._shadowMap.anisotropicFilteringLevel = 1;
  8897. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8898. }
  8899. },
  8900. enumerable: true,
  8901. configurable: true
  8902. });
  8903. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8904. get: function () {
  8905. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8906. },
  8907. set: function (value) {
  8908. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8909. },
  8910. enumerable: true,
  8911. configurable: true
  8912. });
  8913. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8914. get: function () {
  8915. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8916. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8917. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8918. },
  8919. set: function (value) {
  8920. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8921. },
  8922. enumerable: true,
  8923. configurable: true
  8924. });
  8925. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8926. get: function () {
  8927. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8928. },
  8929. set: function (value) {
  8930. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8936. var defines = [];
  8937. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8938. defines.push("#define VSM");
  8939. }
  8940. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8941. var mesh = subMesh.getMesh();
  8942. var material = subMesh.getMaterial();
  8943. // Alpha test
  8944. if (material && material.needAlphaTesting()) {
  8945. defines.push("#define ALPHATEST");
  8946. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8947. attribs.push(BABYLON.VertexBuffer.UVKind);
  8948. defines.push("#define UV1");
  8949. }
  8950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8951. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8952. defines.push("#define UV2");
  8953. }
  8954. }
  8955. // Bones
  8956. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8959. if (mesh.numBoneInfluencers > 4) {
  8960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  8961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  8962. }
  8963. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  8964. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8965. }
  8966. else {
  8967. defines.push("#define NUM_BONE_INFLUENCERS 0");
  8968. }
  8969. // Instances
  8970. if (useInstances) {
  8971. defines.push("#define INSTANCES");
  8972. attribs.push("world0");
  8973. attribs.push("world1");
  8974. attribs.push("world2");
  8975. attribs.push("world3");
  8976. }
  8977. // Get correct effect
  8978. var join = defines.join("\n");
  8979. if (this._cachedDefines !== join) {
  8980. this._cachedDefines = join;
  8981. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8982. }
  8983. return this._effect.isReady();
  8984. };
  8985. ShadowGenerator.prototype.getShadowMap = function () {
  8986. return this._shadowMap;
  8987. };
  8988. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8989. if (this._shadowMap2) {
  8990. return this._shadowMap2;
  8991. }
  8992. return this._shadowMap;
  8993. };
  8994. ShadowGenerator.prototype.getLight = function () {
  8995. return this._light;
  8996. };
  8997. // Methods
  8998. ShadowGenerator.prototype.getTransformMatrix = function () {
  8999. var scene = this._scene;
  9000. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9001. return this._transformMatrix;
  9002. }
  9003. this._currentRenderID = scene.getRenderId();
  9004. this._currentFaceIndexCache = this._currentFaceIndex;
  9005. var lightPosition = this._light.position;
  9006. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9007. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9008. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9009. }
  9010. if (this._light.computeTransformedPosition()) {
  9011. lightPosition = this._light.transformedPosition;
  9012. }
  9013. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9014. this._cachedPosition = lightPosition.clone();
  9015. this._cachedDirection = this._lightDirection.clone();
  9016. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9017. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9018. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9019. }
  9020. return this._transformMatrix;
  9021. };
  9022. ShadowGenerator.prototype.getDarkness = function () {
  9023. return this._darkness;
  9024. };
  9025. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9026. if (darkness >= 1.0)
  9027. this._darkness = 1.0;
  9028. else if (darkness <= 0.0)
  9029. this._darkness = 0.0;
  9030. else
  9031. this._darkness = darkness;
  9032. };
  9033. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9034. this._transparencyShadow = hasShadow;
  9035. };
  9036. ShadowGenerator.prototype._packHalf = function (depth) {
  9037. var scale = depth * 255.0;
  9038. var fract = scale - Math.floor(scale);
  9039. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9040. };
  9041. ShadowGenerator.prototype.dispose = function () {
  9042. this._shadowMap.dispose();
  9043. if (this._shadowMap2) {
  9044. this._shadowMap2.dispose();
  9045. }
  9046. if (this._downSamplePostprocess) {
  9047. this._downSamplePostprocess.dispose();
  9048. }
  9049. if (this._boxBlurPostprocess) {
  9050. this._boxBlurPostprocess.dispose();
  9051. }
  9052. };
  9053. ShadowGenerator._FILTER_NONE = 0;
  9054. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9055. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9056. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9057. return ShadowGenerator;
  9058. })();
  9059. BABYLON.ShadowGenerator = ShadowGenerator;
  9060. })(BABYLON || (BABYLON = {}));
  9061. var BABYLON;
  9062. (function (BABYLON) {
  9063. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9064. if (boxMin.x > sphereCenter.x + sphereRadius)
  9065. return false;
  9066. if (sphereCenter.x - sphereRadius > boxMax.x)
  9067. return false;
  9068. if (boxMin.y > sphereCenter.y + sphereRadius)
  9069. return false;
  9070. if (sphereCenter.y - sphereRadius > boxMax.y)
  9071. return false;
  9072. if (boxMin.z > sphereCenter.z + sphereRadius)
  9073. return false;
  9074. if (sphereCenter.z - sphereRadius > boxMax.z)
  9075. return false;
  9076. return true;
  9077. };
  9078. var getLowestRoot = function (a, b, c, maxR) {
  9079. var determinant = b * b - 4.0 * a * c;
  9080. var result = { root: 0, found: false };
  9081. if (determinant < 0)
  9082. return result;
  9083. var sqrtD = Math.sqrt(determinant);
  9084. var r1 = (-b - sqrtD) / (2.0 * a);
  9085. var r2 = (-b + sqrtD) / (2.0 * a);
  9086. if (r1 > r2) {
  9087. var temp = r2;
  9088. r2 = r1;
  9089. r1 = temp;
  9090. }
  9091. if (r1 > 0 && r1 < maxR) {
  9092. result.root = r1;
  9093. result.found = true;
  9094. return result;
  9095. }
  9096. if (r2 > 0 && r2 < maxR) {
  9097. result.root = r2;
  9098. result.found = true;
  9099. return result;
  9100. }
  9101. return result;
  9102. };
  9103. var Collider = (function () {
  9104. function Collider() {
  9105. this.radius = new BABYLON.Vector3(1, 1, 1);
  9106. this.retry = 0;
  9107. this.basePointWorld = BABYLON.Vector3.Zero();
  9108. this.velocityWorld = BABYLON.Vector3.Zero();
  9109. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9110. this._collisionPoint = BABYLON.Vector3.Zero();
  9111. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9112. this._tempVector = BABYLON.Vector3.Zero();
  9113. this._tempVector2 = BABYLON.Vector3.Zero();
  9114. this._tempVector3 = BABYLON.Vector3.Zero();
  9115. this._tempVector4 = BABYLON.Vector3.Zero();
  9116. this._edge = BABYLON.Vector3.Zero();
  9117. this._baseToVertex = BABYLON.Vector3.Zero();
  9118. this._destinationPoint = BABYLON.Vector3.Zero();
  9119. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9120. this._displacementVector = BABYLON.Vector3.Zero();
  9121. }
  9122. // Methods
  9123. Collider.prototype._initialize = function (source, dir, e) {
  9124. this.velocity = dir;
  9125. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9126. this.basePoint = source;
  9127. source.multiplyToRef(this.radius, this.basePointWorld);
  9128. dir.multiplyToRef(this.radius, this.velocityWorld);
  9129. this.velocityWorldLength = this.velocityWorld.length();
  9130. this.epsilon = e;
  9131. this.collisionFound = false;
  9132. };
  9133. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9134. pa.subtractToRef(point, this._tempVector);
  9135. pb.subtractToRef(point, this._tempVector2);
  9136. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9137. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9138. if (d < 0)
  9139. return false;
  9140. pc.subtractToRef(point, this._tempVector3);
  9141. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9142. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9143. if (d < 0)
  9144. return false;
  9145. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9146. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9147. return d >= 0;
  9148. };
  9149. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9150. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9151. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9152. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9153. return false;
  9154. }
  9155. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9156. return false;
  9157. return true;
  9158. };
  9159. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9160. var t0;
  9161. var embeddedInPlane = false;
  9162. //defensive programming, actually not needed.
  9163. if (!trianglePlaneArray) {
  9164. trianglePlaneArray = [];
  9165. }
  9166. if (!trianglePlaneArray[faceIndex]) {
  9167. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9168. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9169. }
  9170. var trianglePlane = trianglePlaneArray[faceIndex];
  9171. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9172. return;
  9173. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9174. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9175. if (normalDotVelocity == 0) {
  9176. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9177. return;
  9178. embeddedInPlane = true;
  9179. t0 = 0;
  9180. }
  9181. else {
  9182. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9183. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9184. if (t0 > t1) {
  9185. var temp = t1;
  9186. t1 = t0;
  9187. t0 = temp;
  9188. }
  9189. if (t0 > 1.0 || t1 < 0.0)
  9190. return;
  9191. if (t0 < 0)
  9192. t0 = 0;
  9193. if (t0 > 1.0)
  9194. t0 = 1.0;
  9195. }
  9196. this._collisionPoint.copyFromFloats(0, 0, 0);
  9197. var found = false;
  9198. var t = 1.0;
  9199. if (!embeddedInPlane) {
  9200. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9201. this.velocity.scaleToRef(t0, this._tempVector);
  9202. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9203. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9204. found = true;
  9205. t = t0;
  9206. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9207. }
  9208. }
  9209. if (!found) {
  9210. var velocitySquaredLength = this.velocity.lengthSquared();
  9211. var a = velocitySquaredLength;
  9212. this.basePoint.subtractToRef(p1, this._tempVector);
  9213. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9214. var c = this._tempVector.lengthSquared() - 1.0;
  9215. var lowestRoot = getLowestRoot(a, b, c, t);
  9216. if (lowestRoot.found) {
  9217. t = lowestRoot.root;
  9218. found = true;
  9219. this._collisionPoint.copyFrom(p1);
  9220. }
  9221. this.basePoint.subtractToRef(p2, this._tempVector);
  9222. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9223. c = this._tempVector.lengthSquared() - 1.0;
  9224. lowestRoot = getLowestRoot(a, b, c, t);
  9225. if (lowestRoot.found) {
  9226. t = lowestRoot.root;
  9227. found = true;
  9228. this._collisionPoint.copyFrom(p2);
  9229. }
  9230. this.basePoint.subtractToRef(p3, this._tempVector);
  9231. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9232. c = this._tempVector.lengthSquared() - 1.0;
  9233. lowestRoot = getLowestRoot(a, b, c, t);
  9234. if (lowestRoot.found) {
  9235. t = lowestRoot.root;
  9236. found = true;
  9237. this._collisionPoint.copyFrom(p3);
  9238. }
  9239. p2.subtractToRef(p1, this._edge);
  9240. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9241. var edgeSquaredLength = this._edge.lengthSquared();
  9242. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9243. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9244. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9245. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9246. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9247. lowestRoot = getLowestRoot(a, b, c, t);
  9248. if (lowestRoot.found) {
  9249. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9250. if (f >= 0.0 && f <= 1.0) {
  9251. t = lowestRoot.root;
  9252. found = true;
  9253. this._edge.scaleInPlace(f);
  9254. p1.addToRef(this._edge, this._collisionPoint);
  9255. }
  9256. }
  9257. p3.subtractToRef(p2, this._edge);
  9258. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9259. edgeSquaredLength = this._edge.lengthSquared();
  9260. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9261. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9262. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9263. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9264. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9265. lowestRoot = getLowestRoot(a, b, c, t);
  9266. if (lowestRoot.found) {
  9267. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9268. if (f >= 0.0 && f <= 1.0) {
  9269. t = lowestRoot.root;
  9270. found = true;
  9271. this._edge.scaleInPlace(f);
  9272. p2.addToRef(this._edge, this._collisionPoint);
  9273. }
  9274. }
  9275. p1.subtractToRef(p3, this._edge);
  9276. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9277. edgeSquaredLength = this._edge.lengthSquared();
  9278. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9279. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9280. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9281. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9282. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9283. lowestRoot = getLowestRoot(a, b, c, t);
  9284. if (lowestRoot.found) {
  9285. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9286. if (f >= 0.0 && f <= 1.0) {
  9287. t = lowestRoot.root;
  9288. found = true;
  9289. this._edge.scaleInPlace(f);
  9290. p3.addToRef(this._edge, this._collisionPoint);
  9291. }
  9292. }
  9293. }
  9294. if (found) {
  9295. var distToCollision = t * this.velocity.length();
  9296. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9297. if (!this.intersectionPoint) {
  9298. this.intersectionPoint = this._collisionPoint.clone();
  9299. }
  9300. else {
  9301. this.intersectionPoint.copyFrom(this._collisionPoint);
  9302. }
  9303. this.nearestDistance = distToCollision;
  9304. this.collisionFound = true;
  9305. }
  9306. }
  9307. };
  9308. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9309. for (var i = indexStart; i < indexEnd; i += 3) {
  9310. var p1 = pts[indices[i] - decal];
  9311. var p2 = pts[indices[i + 1] - decal];
  9312. var p3 = pts[indices[i + 2] - decal];
  9313. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9314. }
  9315. };
  9316. Collider.prototype._getResponse = function (pos, vel) {
  9317. pos.addToRef(vel, this._destinationPoint);
  9318. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9319. this.basePoint.addToRef(vel, pos);
  9320. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9321. this._slidePlaneNormal.normalize();
  9322. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9323. pos.addInPlace(this._displacementVector);
  9324. this.intersectionPoint.addInPlace(this._displacementVector);
  9325. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9326. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9327. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9328. };
  9329. return Collider;
  9330. })();
  9331. BABYLON.Collider = Collider;
  9332. })(BABYLON || (BABYLON = {}));
  9333. var BABYLON;
  9334. (function (BABYLON) {
  9335. //WebWorker code will be inserted to this variable.
  9336. BABYLON.CollisionWorker = "";
  9337. (function (WorkerTaskType) {
  9338. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9339. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9340. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9341. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9342. var WorkerTaskType = BABYLON.WorkerTaskType;
  9343. (function (WorkerReplyType) {
  9344. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9345. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9346. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9347. var WorkerReplyType = BABYLON.WorkerReplyType;
  9348. var CollisionCoordinatorWorker = (function () {
  9349. function CollisionCoordinatorWorker() {
  9350. var _this = this;
  9351. this._scaledPosition = BABYLON.Vector3.Zero();
  9352. this._scaledVelocity = BABYLON.Vector3.Zero();
  9353. this.onMeshUpdated = function (mesh) {
  9354. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9355. };
  9356. this.onGeometryUpdated = function (geometry) {
  9357. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9358. };
  9359. this._afterRender = function () {
  9360. if (!_this._init)
  9361. return;
  9362. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9363. return;
  9364. }
  9365. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9366. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9367. if (_this._runningUpdated > 4) {
  9368. return;
  9369. }
  9370. ++_this._runningUpdated;
  9371. var payload = {
  9372. updatedMeshes: _this._addUpdateMeshesList,
  9373. updatedGeometries: _this._addUpdateGeometriesList,
  9374. removedGeometries: _this._toRemoveGeometryArray,
  9375. removedMeshes: _this._toRemoveMeshesArray
  9376. };
  9377. var message = {
  9378. payload: payload,
  9379. taskType: WorkerTaskType.UPDATE
  9380. };
  9381. var serializable = [];
  9382. for (var id in payload.updatedGeometries) {
  9383. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9384. //prepare transferables
  9385. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9386. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9387. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9388. }
  9389. }
  9390. _this._worker.postMessage(message, serializable);
  9391. _this._addUpdateMeshesList = {};
  9392. _this._addUpdateGeometriesList = {};
  9393. _this._toRemoveGeometryArray = [];
  9394. _this._toRemoveMeshesArray = [];
  9395. };
  9396. this._onMessageFromWorker = function (e) {
  9397. var returnData = e.data;
  9398. if (returnData.error != WorkerReplyType.SUCCESS) {
  9399. //TODO what errors can be returned from the worker?
  9400. BABYLON.Tools.Warn("error returned from worker!");
  9401. return;
  9402. }
  9403. switch (returnData.taskType) {
  9404. case WorkerTaskType.INIT:
  9405. _this._init = true;
  9406. //Update the worked with ALL of the scene's current state
  9407. _this._scene.meshes.forEach(function (mesh) {
  9408. _this.onMeshAdded(mesh);
  9409. });
  9410. _this._scene.getGeometries().forEach(function (geometry) {
  9411. _this.onGeometryAdded(geometry);
  9412. });
  9413. break;
  9414. case WorkerTaskType.UPDATE:
  9415. _this._runningUpdated--;
  9416. break;
  9417. case WorkerTaskType.COLLIDE:
  9418. _this._runningCollisionTask = false;
  9419. var returnPayload = returnData.payload;
  9420. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9421. return;
  9422. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9423. //cleanup
  9424. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9425. break;
  9426. }
  9427. };
  9428. this._collisionsCallbackArray = [];
  9429. this._init = false;
  9430. this._runningUpdated = 0;
  9431. this._runningCollisionTask = false;
  9432. this._addUpdateMeshesList = {};
  9433. this._addUpdateGeometriesList = {};
  9434. this._toRemoveGeometryArray = [];
  9435. this._toRemoveMeshesArray = [];
  9436. }
  9437. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9438. if (!this._init)
  9439. return;
  9440. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9441. return;
  9442. position.divideToRef(collider.radius, this._scaledPosition);
  9443. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9444. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9445. var payload = {
  9446. collider: {
  9447. position: this._scaledPosition.asArray(),
  9448. velocity: this._scaledVelocity.asArray(),
  9449. radius: collider.radius.asArray()
  9450. },
  9451. collisionId: collisionIndex,
  9452. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9453. maximumRetry: maximumRetry
  9454. };
  9455. var message = {
  9456. payload: payload,
  9457. taskType: WorkerTaskType.COLLIDE
  9458. };
  9459. this._worker.postMessage(message);
  9460. };
  9461. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9462. this._scene = scene;
  9463. this._scene.registerAfterRender(this._afterRender);
  9464. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9465. this._worker = new Worker(workerUrl);
  9466. this._worker.onmessage = this._onMessageFromWorker;
  9467. var message = {
  9468. payload: {},
  9469. taskType: WorkerTaskType.INIT
  9470. };
  9471. this._worker.postMessage(message);
  9472. };
  9473. CollisionCoordinatorWorker.prototype.destroy = function () {
  9474. this._scene.unregisterAfterRender(this._afterRender);
  9475. this._worker.terminate();
  9476. };
  9477. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9478. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9479. this.onMeshUpdated(mesh);
  9480. };
  9481. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9482. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9483. };
  9484. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9485. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9486. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9487. this.onGeometryUpdated(geometry);
  9488. };
  9489. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9490. this._toRemoveGeometryArray.push(geometry.id);
  9491. };
  9492. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9493. var submeshes = [];
  9494. if (mesh.subMeshes) {
  9495. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9496. return {
  9497. position: idx,
  9498. verticesStart: sm.verticesStart,
  9499. verticesCount: sm.verticesCount,
  9500. indexStart: sm.indexStart,
  9501. indexCount: sm.indexCount,
  9502. hasMaterial: !!sm.getMaterial(),
  9503. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9504. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9505. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9506. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9507. };
  9508. });
  9509. }
  9510. var geometryId = null;
  9511. if (mesh instanceof BABYLON.Mesh) {
  9512. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9513. }
  9514. else if (mesh instanceof BABYLON.InstancedMesh) {
  9515. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9516. }
  9517. return {
  9518. uniqueId: mesh.uniqueId,
  9519. id: mesh.id,
  9520. name: mesh.name,
  9521. geometryId: geometryId,
  9522. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9523. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9524. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9525. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9526. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9527. subMeshes: submeshes,
  9528. checkCollisions: mesh.checkCollisions
  9529. };
  9530. };
  9531. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9532. return {
  9533. id: geometry.id,
  9534. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9535. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9536. indices: new Int32Array(geometry.getIndices() || []),
  9537. };
  9538. };
  9539. return CollisionCoordinatorWorker;
  9540. })();
  9541. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9542. var CollisionCoordinatorLegacy = (function () {
  9543. function CollisionCoordinatorLegacy() {
  9544. this._scaledPosition = BABYLON.Vector3.Zero();
  9545. this._scaledVelocity = BABYLON.Vector3.Zero();
  9546. this._finalPosition = BABYLON.Vector3.Zero();
  9547. }
  9548. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9549. position.divideToRef(collider.radius, this._scaledPosition);
  9550. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9551. collider.collidedMesh = null;
  9552. collider.retry = 0;
  9553. collider.initialVelocity = this._scaledVelocity;
  9554. collider.initialPosition = this._scaledPosition;
  9555. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9556. this._finalPosition.multiplyInPlace(collider.radius);
  9557. //run the callback
  9558. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9559. };
  9560. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9561. this._scene = scene;
  9562. };
  9563. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9564. //Legacy need no destruction method.
  9565. };
  9566. //No update in legacy mode
  9567. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9568. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9569. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9570. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9571. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9572. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9573. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9574. if (excludedMesh === void 0) { excludedMesh = null; }
  9575. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9576. if (collider.retry >= maximumRetry) {
  9577. finalPosition.copyFrom(position);
  9578. return;
  9579. }
  9580. collider._initialize(position, velocity, closeDistance);
  9581. // Check all meshes
  9582. for (var index = 0; index < this._scene.meshes.length; index++) {
  9583. var mesh = this._scene.meshes[index];
  9584. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9585. mesh._checkCollision(collider);
  9586. }
  9587. }
  9588. if (!collider.collisionFound) {
  9589. position.addToRef(velocity, finalPosition);
  9590. return;
  9591. }
  9592. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9593. collider._getResponse(position, velocity);
  9594. }
  9595. if (velocity.length() <= closeDistance) {
  9596. finalPosition.copyFrom(position);
  9597. return;
  9598. }
  9599. collider.retry++;
  9600. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9601. };
  9602. return CollisionCoordinatorLegacy;
  9603. })();
  9604. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9605. })(BABYLON || (BABYLON = {}));
  9606. var BABYLON;
  9607. (function (BABYLON) {
  9608. var VRCameraMetrics = (function () {
  9609. function VRCameraMetrics() {
  9610. this.compensateDistortion = true;
  9611. }
  9612. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9613. get: function () {
  9614. return this.hResolution / (2 * this.vResolution);
  9615. },
  9616. enumerable: true,
  9617. configurable: true
  9618. });
  9619. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9620. get: function () {
  9621. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9622. },
  9623. enumerable: true,
  9624. configurable: true
  9625. });
  9626. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9627. get: function () {
  9628. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9629. var h = (4 * meters) / this.hScreenSize;
  9630. return BABYLON.Matrix.Translation(h, 0, 0);
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9636. get: function () {
  9637. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9638. var h = (4 * meters) / this.hScreenSize;
  9639. return BABYLON.Matrix.Translation(-h, 0, 0);
  9640. },
  9641. enumerable: true,
  9642. configurable: true
  9643. });
  9644. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9645. get: function () {
  9646. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9652. get: function () {
  9653. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9654. },
  9655. enumerable: true,
  9656. configurable: true
  9657. });
  9658. VRCameraMetrics.GetDefault = function () {
  9659. var result = new VRCameraMetrics();
  9660. result.hResolution = 1280;
  9661. result.vResolution = 800;
  9662. result.hScreenSize = 0.149759993;
  9663. result.vScreenSize = 0.0935999975;
  9664. result.vScreenCenter = 0.0467999987,
  9665. result.eyeToScreenDistance = 0.0410000011;
  9666. result.lensSeparationDistance = 0.0635000020;
  9667. result.interpupillaryDistance = 0.0640000030;
  9668. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9669. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9670. result.postProcessScaleFactor = 1.714605507808412;
  9671. result.lensCenterOffset = 0.151976421;
  9672. return result;
  9673. };
  9674. return VRCameraMetrics;
  9675. })();
  9676. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9677. var Camera = (function (_super) {
  9678. __extends(Camera, _super);
  9679. function Camera(name, position, scene) {
  9680. _super.call(this, name, scene);
  9681. this.position = position;
  9682. // Members
  9683. this.upVector = BABYLON.Vector3.Up();
  9684. this.orthoLeft = null;
  9685. this.orthoRight = null;
  9686. this.orthoBottom = null;
  9687. this.orthoTop = null;
  9688. this.fov = 0.8;
  9689. this.minZ = 1.0;
  9690. this.maxZ = 10000.0;
  9691. this.inertia = 0.9;
  9692. this.mode = Camera.PERSPECTIVE_CAMERA;
  9693. this.isIntermediate = false;
  9694. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9695. this.layerMask = 0x0FFFFFFF;
  9696. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9697. // Camera rig members
  9698. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9699. this._rigCameras = new Array();
  9700. // Cache
  9701. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9702. this._projectionMatrix = new BABYLON.Matrix();
  9703. this._postProcesses = new Array();
  9704. this._postProcessesTakenIndices = [];
  9705. this._activeMeshes = new BABYLON.SmartArray(256);
  9706. this._globalPosition = BABYLON.Vector3.Zero();
  9707. scene.addCamera(this);
  9708. if (!scene.activeCamera) {
  9709. scene.activeCamera = this;
  9710. }
  9711. }
  9712. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9713. get: function () {
  9714. return Camera._PERSPECTIVE_CAMERA;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9720. get: function () {
  9721. return Camera._ORTHOGRAPHIC_CAMERA;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9727. get: function () {
  9728. return Camera._FOVMODE_VERTICAL_FIXED;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9734. get: function () {
  9735. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9741. get: function () {
  9742. return Camera._RIG_MODE_NONE;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9748. get: function () {
  9749. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9755. get: function () {
  9756. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9757. },
  9758. enumerable: true,
  9759. configurable: true
  9760. });
  9761. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9762. get: function () {
  9763. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9764. },
  9765. enumerable: true,
  9766. configurable: true
  9767. });
  9768. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9769. get: function () {
  9770. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9776. get: function () {
  9777. return Camera._RIG_MODE_VR;
  9778. },
  9779. enumerable: true,
  9780. configurable: true
  9781. });
  9782. Object.defineProperty(Camera.prototype, "globalPosition", {
  9783. get: function () {
  9784. return this._globalPosition;
  9785. },
  9786. enumerable: true,
  9787. configurable: true
  9788. });
  9789. Camera.prototype.getActiveMeshes = function () {
  9790. return this._activeMeshes;
  9791. };
  9792. Camera.prototype.isActiveMesh = function (mesh) {
  9793. return (this._activeMeshes.indexOf(mesh) !== -1);
  9794. };
  9795. //Cache
  9796. Camera.prototype._initCache = function () {
  9797. _super.prototype._initCache.call(this);
  9798. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9799. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9800. this._cache.mode = undefined;
  9801. this._cache.minZ = undefined;
  9802. this._cache.maxZ = undefined;
  9803. this._cache.fov = undefined;
  9804. this._cache.aspectRatio = undefined;
  9805. this._cache.orthoLeft = undefined;
  9806. this._cache.orthoRight = undefined;
  9807. this._cache.orthoBottom = undefined;
  9808. this._cache.orthoTop = undefined;
  9809. this._cache.renderWidth = undefined;
  9810. this._cache.renderHeight = undefined;
  9811. };
  9812. Camera.prototype._updateCache = function (ignoreParentClass) {
  9813. if (!ignoreParentClass) {
  9814. _super.prototype._updateCache.call(this);
  9815. }
  9816. var engine = this.getEngine();
  9817. this._cache.position.copyFrom(this.position);
  9818. this._cache.upVector.copyFrom(this.upVector);
  9819. this._cache.mode = this.mode;
  9820. this._cache.minZ = this.minZ;
  9821. this._cache.maxZ = this.maxZ;
  9822. this._cache.fov = this.fov;
  9823. this._cache.aspectRatio = engine.getAspectRatio(this);
  9824. this._cache.orthoLeft = this.orthoLeft;
  9825. this._cache.orthoRight = this.orthoRight;
  9826. this._cache.orthoBottom = this.orthoBottom;
  9827. this._cache.orthoTop = this.orthoTop;
  9828. this._cache.renderWidth = engine.getRenderWidth();
  9829. this._cache.renderHeight = engine.getRenderHeight();
  9830. };
  9831. Camera.prototype._updateFromScene = function () {
  9832. this.updateCache();
  9833. this._update();
  9834. };
  9835. // Synchronized
  9836. Camera.prototype._isSynchronized = function () {
  9837. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9838. };
  9839. Camera.prototype._isSynchronizedViewMatrix = function () {
  9840. if (!_super.prototype._isSynchronized.call(this))
  9841. return false;
  9842. return this._cache.position.equals(this.position)
  9843. && this._cache.upVector.equals(this.upVector)
  9844. && this.isSynchronizedWithParent();
  9845. };
  9846. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9847. var check = this._cache.mode === this.mode
  9848. && this._cache.minZ === this.minZ
  9849. && this._cache.maxZ === this.maxZ;
  9850. if (!check) {
  9851. return false;
  9852. }
  9853. var engine = this.getEngine();
  9854. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9855. check = this._cache.fov === this.fov
  9856. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9857. }
  9858. else {
  9859. check = this._cache.orthoLeft === this.orthoLeft
  9860. && this._cache.orthoRight === this.orthoRight
  9861. && this._cache.orthoBottom === this.orthoBottom
  9862. && this._cache.orthoTop === this.orthoTop
  9863. && this._cache.renderWidth === engine.getRenderWidth()
  9864. && this._cache.renderHeight === engine.getRenderHeight();
  9865. }
  9866. return check;
  9867. };
  9868. // Controls
  9869. Camera.prototype.attachControl = function (element) {
  9870. };
  9871. Camera.prototype.detachControl = function (element) {
  9872. };
  9873. Camera.prototype._update = function () {
  9874. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9875. this._updateRigCameras();
  9876. }
  9877. this._checkInputs();
  9878. };
  9879. Camera.prototype._checkInputs = function () {
  9880. };
  9881. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9882. if (insertAt === void 0) { insertAt = null; }
  9883. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9884. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9885. return 0;
  9886. }
  9887. if (insertAt == null || insertAt < 0) {
  9888. this._postProcesses.push(postProcess);
  9889. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9890. return this._postProcesses.length - 1;
  9891. }
  9892. var add = 0;
  9893. var i;
  9894. var start;
  9895. if (this._postProcesses[insertAt]) {
  9896. start = this._postProcesses.length - 1;
  9897. for (i = start; i >= insertAt + 1; --i) {
  9898. this._postProcesses[i + 1] = this._postProcesses[i];
  9899. }
  9900. add = 1;
  9901. }
  9902. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9903. if (this._postProcessesTakenIndices[i] < insertAt) {
  9904. continue;
  9905. }
  9906. start = this._postProcessesTakenIndices.length - 1;
  9907. for (var j = start; j >= i; --j) {
  9908. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9909. }
  9910. this._postProcessesTakenIndices[i] = insertAt;
  9911. break;
  9912. }
  9913. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9914. this._postProcessesTakenIndices.push(insertAt);
  9915. }
  9916. var result = insertAt + add;
  9917. this._postProcesses[result] = postProcess;
  9918. return result;
  9919. };
  9920. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9921. if (atIndices === void 0) { atIndices = null; }
  9922. var result = [];
  9923. var i;
  9924. var index;
  9925. if (!atIndices) {
  9926. var length = this._postProcesses.length;
  9927. for (i = 0; i < length; i++) {
  9928. if (this._postProcesses[i] !== postProcess) {
  9929. continue;
  9930. }
  9931. delete this._postProcesses[i];
  9932. index = this._postProcessesTakenIndices.indexOf(i);
  9933. this._postProcessesTakenIndices.splice(index, 1);
  9934. }
  9935. }
  9936. else {
  9937. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9938. for (i = 0; i < atIndices.length; i++) {
  9939. var foundPostProcess = this._postProcesses[atIndices[i]];
  9940. if (foundPostProcess !== postProcess) {
  9941. result.push(i);
  9942. continue;
  9943. }
  9944. delete this._postProcesses[atIndices[i]];
  9945. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9946. this._postProcessesTakenIndices.splice(index, 1);
  9947. }
  9948. }
  9949. return result;
  9950. };
  9951. Camera.prototype.getWorldMatrix = function () {
  9952. if (!this._worldMatrix) {
  9953. this._worldMatrix = BABYLON.Matrix.Identity();
  9954. }
  9955. var viewMatrix = this.getViewMatrix();
  9956. viewMatrix.invertToRef(this._worldMatrix);
  9957. return this._worldMatrix;
  9958. };
  9959. Camera.prototype._getViewMatrix = function () {
  9960. return BABYLON.Matrix.Identity();
  9961. };
  9962. Camera.prototype.getViewMatrix = function (force) {
  9963. this._computedViewMatrix = this._computeViewMatrix(force);
  9964. if (!force && this._isSynchronizedViewMatrix()) {
  9965. return this._computedViewMatrix;
  9966. }
  9967. if (!this.parent || !this.parent.getWorldMatrix) {
  9968. this._globalPosition.copyFrom(this.position);
  9969. }
  9970. else {
  9971. if (!this._worldMatrix) {
  9972. this._worldMatrix = BABYLON.Matrix.Identity();
  9973. }
  9974. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9975. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9976. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9977. this._computedViewMatrix.invert();
  9978. this._markSyncedWithParent();
  9979. }
  9980. this._currentRenderId = this.getScene().getRenderId();
  9981. return this._computedViewMatrix;
  9982. };
  9983. Camera.prototype._computeViewMatrix = function (force) {
  9984. if (!force && this._isSynchronizedViewMatrix()) {
  9985. return this._computedViewMatrix;
  9986. }
  9987. this._computedViewMatrix = this._getViewMatrix();
  9988. this._currentRenderId = this.getScene().getRenderId();
  9989. return this._computedViewMatrix;
  9990. };
  9991. Camera.prototype.getProjectionMatrix = function (force) {
  9992. if (!force && this._isSynchronizedProjectionMatrix()) {
  9993. return this._projectionMatrix;
  9994. }
  9995. var engine = this.getEngine();
  9996. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9997. if (this.minZ <= 0) {
  9998. this.minZ = 0.1;
  9999. }
  10000. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10001. return this._projectionMatrix;
  10002. }
  10003. var halfWidth = engine.getRenderWidth() / 2.0;
  10004. var halfHeight = engine.getRenderHeight() / 2.0;
  10005. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10006. return this._projectionMatrix;
  10007. };
  10008. Camera.prototype.dispose = function () {
  10009. // Animations
  10010. this.getScene().stopAnimation(this);
  10011. // Remove from scene
  10012. this.getScene().removeCamera(this);
  10013. while (this._rigCameras.length > 0) {
  10014. this._rigCameras.pop().dispose();
  10015. }
  10016. // Postprocesses
  10017. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10018. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10019. }
  10020. };
  10021. // ---- Camera rigs section ----
  10022. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10023. while (this._rigCameras.length > 0) {
  10024. this._rigCameras.pop().dispose();
  10025. }
  10026. this.cameraRigMode = mode;
  10027. this._cameraRigParams = {};
  10028. switch (this.cameraRigMode) {
  10029. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10030. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10031. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10032. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10033. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10034. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10035. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10036. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10037. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10038. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10039. break;
  10040. }
  10041. var postProcesses = new Array();
  10042. switch (this.cameraRigMode) {
  10043. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10044. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10045. this._rigCameras[0].isIntermediate = true;
  10046. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10047. postProcesses[1].onApply = function (effect) {
  10048. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10049. };
  10050. break;
  10051. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10052. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10053. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10054. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10055. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10056. var secondCamIndex = 1 - firstCamIndex;
  10057. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10058. this._rigCameras[firstCamIndex].isIntermediate = true;
  10059. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10060. break;
  10061. case Camera.RIG_MODE_VR:
  10062. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10063. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10064. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10065. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10066. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10067. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10068. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10069. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10070. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10071. if (metrics.compensateDistortion) {
  10072. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10073. }
  10074. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10075. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10076. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10077. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10078. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10079. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10080. if (metrics.compensateDistortion) {
  10081. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10082. }
  10083. break;
  10084. }
  10085. this._update();
  10086. };
  10087. Camera.prototype._getVRProjectionMatrix = function () {
  10088. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10089. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10090. return this._projectionMatrix;
  10091. };
  10092. Camera.prototype.setCameraRigParameter = function (name, value) {
  10093. this._cameraRigParams[name] = value;
  10094. //provisionnally:
  10095. if (name === "interaxialDistance") {
  10096. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10097. }
  10098. };
  10099. /**
  10100. * May needs to be overridden by children so sub has required properties to be copied
  10101. */
  10102. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10103. return null;
  10104. };
  10105. /**
  10106. * May needs to be overridden by children
  10107. */
  10108. Camera.prototype._updateRigCameras = function () {
  10109. for (var i = 0; i < this._rigCameras.length; i++) {
  10110. this._rigCameras[i].minZ = this.minZ;
  10111. this._rigCameras[i].maxZ = this.maxZ;
  10112. this._rigCameras[i].fov = this.fov;
  10113. }
  10114. // only update viewport when ANAGLYPH
  10115. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10116. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10117. }
  10118. };
  10119. // Statics
  10120. Camera._PERSPECTIVE_CAMERA = 0;
  10121. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10122. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10123. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10124. Camera._RIG_MODE_NONE = 0;
  10125. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10126. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10127. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10128. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10129. Camera._RIG_MODE_VR = 20;
  10130. return Camera;
  10131. })(BABYLON.Node);
  10132. BABYLON.Camera = Camera;
  10133. })(BABYLON || (BABYLON = {}));
  10134. var BABYLON;
  10135. (function (BABYLON) {
  10136. var TargetCamera = (function (_super) {
  10137. __extends(TargetCamera, _super);
  10138. function TargetCamera(name, position, scene) {
  10139. _super.call(this, name, position, scene);
  10140. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10141. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10142. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10143. this.speed = 2.0;
  10144. this.noRotationConstraint = false;
  10145. this.lockedTarget = null;
  10146. this._currentTarget = BABYLON.Vector3.Zero();
  10147. this._viewMatrix = BABYLON.Matrix.Zero();
  10148. this._camMatrix = BABYLON.Matrix.Zero();
  10149. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10150. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10151. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10152. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10153. this._lookAtTemp = BABYLON.Matrix.Zero();
  10154. this._tempMatrix = BABYLON.Matrix.Zero();
  10155. }
  10156. TargetCamera.prototype.getFrontPosition = function (distance) {
  10157. var direction = this.getTarget().subtract(this.position);
  10158. direction.normalize();
  10159. direction.scaleInPlace(distance);
  10160. return this.globalPosition.add(direction);
  10161. };
  10162. TargetCamera.prototype._getLockedTargetPosition = function () {
  10163. if (!this.lockedTarget) {
  10164. return null;
  10165. }
  10166. return this.lockedTarget.position || this.lockedTarget;
  10167. };
  10168. // Cache
  10169. TargetCamera.prototype._initCache = function () {
  10170. _super.prototype._initCache.call(this);
  10171. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10172. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10173. };
  10174. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10175. if (!ignoreParentClass) {
  10176. _super.prototype._updateCache.call(this);
  10177. }
  10178. var lockedTargetPosition = this._getLockedTargetPosition();
  10179. if (!lockedTargetPosition) {
  10180. this._cache.lockedTarget = null;
  10181. }
  10182. else {
  10183. if (!this._cache.lockedTarget) {
  10184. this._cache.lockedTarget = lockedTargetPosition.clone();
  10185. }
  10186. else {
  10187. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10188. }
  10189. }
  10190. this._cache.rotation.copyFrom(this.rotation);
  10191. };
  10192. // Synchronized
  10193. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10194. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10195. return false;
  10196. }
  10197. var lockedTargetPosition = this._getLockedTargetPosition();
  10198. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10199. && this._cache.rotation.equals(this.rotation);
  10200. };
  10201. // Methods
  10202. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10203. var engine = this.getEngine();
  10204. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10205. };
  10206. // Target
  10207. TargetCamera.prototype.setTarget = function (target) {
  10208. this.upVector.normalize();
  10209. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10210. this._camMatrix.invert();
  10211. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10212. var vDir = target.subtract(this.position);
  10213. if (vDir.x >= 0.0) {
  10214. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10215. }
  10216. else {
  10217. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10218. }
  10219. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10220. if (isNaN(this.rotation.x)) {
  10221. this.rotation.x = 0;
  10222. }
  10223. if (isNaN(this.rotation.y)) {
  10224. this.rotation.y = 0;
  10225. }
  10226. if (isNaN(this.rotation.z)) {
  10227. this.rotation.z = 0;
  10228. }
  10229. };
  10230. TargetCamera.prototype.getTarget = function () {
  10231. return this._currentTarget;
  10232. };
  10233. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10234. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10235. };
  10236. TargetCamera.prototype._updatePosition = function () {
  10237. this.position.addInPlace(this.cameraDirection);
  10238. };
  10239. TargetCamera.prototype._checkInputs = function () {
  10240. var needToMove = this._decideIfNeedsToMove();
  10241. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10242. // Move
  10243. if (needToMove) {
  10244. this._updatePosition();
  10245. }
  10246. // Rotate
  10247. if (needToRotate) {
  10248. this.rotation.x += this.cameraRotation.x;
  10249. this.rotation.y += this.cameraRotation.y;
  10250. if (!this.noRotationConstraint) {
  10251. var limit = (Math.PI / 2) * 0.95;
  10252. if (this.rotation.x > limit)
  10253. this.rotation.x = limit;
  10254. if (this.rotation.x < -limit)
  10255. this.rotation.x = -limit;
  10256. }
  10257. }
  10258. // Inertia
  10259. if (needToMove) {
  10260. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10261. this.cameraDirection.x = 0;
  10262. }
  10263. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10264. this.cameraDirection.y = 0;
  10265. }
  10266. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10267. this.cameraDirection.z = 0;
  10268. }
  10269. this.cameraDirection.scaleInPlace(this.inertia);
  10270. }
  10271. if (needToRotate) {
  10272. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10273. this.cameraRotation.x = 0;
  10274. }
  10275. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10276. this.cameraRotation.y = 0;
  10277. }
  10278. this.cameraRotation.scaleInPlace(this.inertia);
  10279. }
  10280. _super.prototype._checkInputs.call(this);
  10281. };
  10282. TargetCamera.prototype._getViewMatrix = function () {
  10283. if (!this.lockedTarget) {
  10284. // Compute
  10285. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10286. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10287. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10288. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10289. this._lookAtTemp.invert();
  10290. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10291. }
  10292. else {
  10293. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10294. }
  10295. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10296. // Computing target and final matrix
  10297. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10298. }
  10299. else {
  10300. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10301. }
  10302. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10303. return this._viewMatrix;
  10304. };
  10305. TargetCamera.prototype._getVRViewMatrix = function () {
  10306. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10307. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10308. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10309. // Computing target and final matrix
  10310. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10311. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10312. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10313. return this._viewMatrix;
  10314. };
  10315. /**
  10316. * @override
  10317. * Override Camera.createRigCamera
  10318. */
  10319. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10320. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10321. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10322. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10323. rigCamera._cameraRigParams = {};
  10324. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10325. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10326. }
  10327. return rigCamera;
  10328. }
  10329. return null;
  10330. };
  10331. /**
  10332. * @override
  10333. * Override Camera._updateRigCameras
  10334. */
  10335. TargetCamera.prototype._updateRigCameras = function () {
  10336. switch (this.cameraRigMode) {
  10337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10339. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10341. case BABYLON.Camera.RIG_MODE_VR:
  10342. var camLeft = this._rigCameras[0];
  10343. var camRight = this._rigCameras[1];
  10344. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10345. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10346. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10347. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10348. camLeft.position.copyFrom(this.position);
  10349. camRight.position.copyFrom(this.position);
  10350. }
  10351. else {
  10352. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10353. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10354. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10355. camLeft.setTarget(this.getTarget());
  10356. camRight.setTarget(this.getTarget());
  10357. }
  10358. break;
  10359. }
  10360. _super.prototype._updateRigCameras.call(this);
  10361. };
  10362. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10363. if (!this._rigCamTransformMatrix) {
  10364. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10365. }
  10366. var target = this.getTarget();
  10367. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10368. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10369. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10370. };
  10371. return TargetCamera;
  10372. })(BABYLON.Camera);
  10373. BABYLON.TargetCamera = TargetCamera;
  10374. })(BABYLON || (BABYLON = {}));
  10375. var BABYLON;
  10376. (function (BABYLON) {
  10377. var FreeCamera = (function (_super) {
  10378. __extends(FreeCamera, _super);
  10379. function FreeCamera(name, position, scene) {
  10380. var _this = this;
  10381. _super.call(this, name, position, scene);
  10382. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10383. this.keysUp = [38];
  10384. this.keysDown = [40];
  10385. this.keysLeft = [37];
  10386. this.keysRight = [39];
  10387. this.checkCollisions = false;
  10388. this.applyGravity = false;
  10389. this.angularSensibility = 2000.0;
  10390. this._keys = [];
  10391. this._collider = new BABYLON.Collider();
  10392. this._needMoveForGravity = false;
  10393. this._oldPosition = BABYLON.Vector3.Zero();
  10394. this._diffPosition = BABYLON.Vector3.Zero();
  10395. this._newPosition = BABYLON.Vector3.Zero();
  10396. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10397. if (collidedMesh === void 0) { collidedMesh = null; }
  10398. //TODO move this to the collision coordinator!
  10399. if (_this.getScene().workerCollisions)
  10400. newPosition.multiplyInPlace(_this._collider.radius);
  10401. var updatePosition = function (newPos) {
  10402. _this._newPosition.copyFrom(newPos);
  10403. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10404. var oldPosition = _this.position.clone();
  10405. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10406. _this.position.addInPlace(_this._diffPosition);
  10407. if (_this.onCollide && collidedMesh) {
  10408. _this.onCollide(collidedMesh);
  10409. }
  10410. }
  10411. };
  10412. updatePosition(newPosition);
  10413. };
  10414. }
  10415. // Controls
  10416. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10417. var _this = this;
  10418. var previousPosition;
  10419. var engine = this.getEngine();
  10420. if (this._attachedElement) {
  10421. return;
  10422. }
  10423. this._attachedElement = element;
  10424. if (this._onMouseDown === undefined) {
  10425. this._onMouseDown = function (evt) {
  10426. previousPosition = {
  10427. x: evt.clientX,
  10428. y: evt.clientY
  10429. };
  10430. if (!noPreventDefault) {
  10431. evt.preventDefault();
  10432. }
  10433. };
  10434. this._onMouseUp = function (evt) {
  10435. previousPosition = null;
  10436. if (!noPreventDefault) {
  10437. evt.preventDefault();
  10438. }
  10439. };
  10440. this._onMouseOut = function (evt) {
  10441. previousPosition = null;
  10442. _this._keys = [];
  10443. if (!noPreventDefault) {
  10444. evt.preventDefault();
  10445. }
  10446. };
  10447. this._onMouseMove = function (evt) {
  10448. if (!previousPosition && !engine.isPointerLock) {
  10449. return;
  10450. }
  10451. var offsetX;
  10452. var offsetY;
  10453. if (!engine.isPointerLock) {
  10454. offsetX = evt.clientX - previousPosition.x;
  10455. offsetY = evt.clientY - previousPosition.y;
  10456. }
  10457. else {
  10458. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10459. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10460. }
  10461. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10462. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10463. previousPosition = {
  10464. x: evt.clientX,
  10465. y: evt.clientY
  10466. };
  10467. if (!noPreventDefault) {
  10468. evt.preventDefault();
  10469. }
  10470. };
  10471. this._onKeyDown = function (evt) {
  10472. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10473. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10474. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10475. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10476. var index = _this._keys.indexOf(evt.keyCode);
  10477. if (index === -1) {
  10478. _this._keys.push(evt.keyCode);
  10479. }
  10480. if (!noPreventDefault) {
  10481. evt.preventDefault();
  10482. }
  10483. }
  10484. };
  10485. this._onKeyUp = function (evt) {
  10486. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10487. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10488. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10489. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10490. var index = _this._keys.indexOf(evt.keyCode);
  10491. if (index >= 0) {
  10492. _this._keys.splice(index, 1);
  10493. }
  10494. if (!noPreventDefault) {
  10495. evt.preventDefault();
  10496. }
  10497. }
  10498. };
  10499. this._onLostFocus = function () {
  10500. _this._keys = [];
  10501. };
  10502. this._reset = function () {
  10503. _this._keys = [];
  10504. previousPosition = null;
  10505. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10506. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10507. };
  10508. }
  10509. element.addEventListener("mousedown", this._onMouseDown, false);
  10510. element.addEventListener("mouseup", this._onMouseUp, false);
  10511. element.addEventListener("mouseout", this._onMouseOut, false);
  10512. element.addEventListener("mousemove", this._onMouseMove, false);
  10513. BABYLON.Tools.RegisterTopRootEvents([
  10514. { name: "keydown", handler: this._onKeyDown },
  10515. { name: "keyup", handler: this._onKeyUp },
  10516. { name: "blur", handler: this._onLostFocus }
  10517. ]);
  10518. };
  10519. FreeCamera.prototype.detachControl = function (element) {
  10520. if (this._attachedElement != element) {
  10521. return;
  10522. }
  10523. element.removeEventListener("mousedown", this._onMouseDown);
  10524. element.removeEventListener("mouseup", this._onMouseUp);
  10525. element.removeEventListener("mouseout", this._onMouseOut);
  10526. element.removeEventListener("mousemove", this._onMouseMove);
  10527. BABYLON.Tools.UnregisterTopRootEvents([
  10528. { name: "keydown", handler: this._onKeyDown },
  10529. { name: "keyup", handler: this._onKeyUp },
  10530. { name: "blur", handler: this._onLostFocus }
  10531. ]);
  10532. this._attachedElement = null;
  10533. if (this._reset) {
  10534. this._reset();
  10535. }
  10536. };
  10537. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10538. var globalPosition;
  10539. if (this.parent) {
  10540. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10541. }
  10542. else {
  10543. globalPosition = this.position;
  10544. }
  10545. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10546. this._collider.radius = this.ellipsoid;
  10547. //no need for clone, as long as gravity is not on.
  10548. var actualVelocity = velocity;
  10549. //add gravity to the velocity to prevent the dual-collision checking
  10550. if (this.applyGravity) {
  10551. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10552. actualVelocity = velocity.add(this.getScene().gravity);
  10553. }
  10554. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10555. };
  10556. FreeCamera.prototype._checkInputs = function () {
  10557. if (!this._localDirection) {
  10558. this._localDirection = BABYLON.Vector3.Zero();
  10559. this._transformedDirection = BABYLON.Vector3.Zero();
  10560. }
  10561. // Keyboard
  10562. for (var index = 0; index < this._keys.length; index++) {
  10563. var keyCode = this._keys[index];
  10564. var speed = this._computeLocalCameraSpeed();
  10565. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10566. this._localDirection.copyFromFloats(-speed, 0, 0);
  10567. }
  10568. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10569. this._localDirection.copyFromFloats(0, 0, speed);
  10570. }
  10571. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10572. this._localDirection.copyFromFloats(speed, 0, 0);
  10573. }
  10574. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10575. this._localDirection.copyFromFloats(0, 0, -speed);
  10576. }
  10577. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10578. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10579. this.cameraDirection.addInPlace(this._transformedDirection);
  10580. }
  10581. _super.prototype._checkInputs.call(this);
  10582. };
  10583. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10584. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10585. };
  10586. FreeCamera.prototype._updatePosition = function () {
  10587. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10588. this._collideWithWorld(this.cameraDirection);
  10589. }
  10590. else {
  10591. this.position.addInPlace(this.cameraDirection);
  10592. }
  10593. };
  10594. return FreeCamera;
  10595. })(BABYLON.TargetCamera);
  10596. BABYLON.FreeCamera = FreeCamera;
  10597. })(BABYLON || (BABYLON = {}));
  10598. var BABYLON;
  10599. (function (BABYLON) {
  10600. var FollowCamera = (function (_super) {
  10601. __extends(FollowCamera, _super);
  10602. function FollowCamera(name, position, scene) {
  10603. _super.call(this, name, position, scene);
  10604. this.radius = 12;
  10605. this.rotationOffset = 0;
  10606. this.heightOffset = 4;
  10607. this.cameraAcceleration = 0.05;
  10608. this.maxCameraSpeed = 20;
  10609. }
  10610. FollowCamera.prototype.getRadians = function (degrees) {
  10611. return degrees * Math.PI / 180;
  10612. };
  10613. FollowCamera.prototype.follow = function (cameraTarget) {
  10614. if (!cameraTarget)
  10615. return;
  10616. var yRotation;
  10617. if (cameraTarget.rotationQuaternion) {
  10618. var rotMatrix = new BABYLON.Matrix();
  10619. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10620. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10621. }
  10622. else {
  10623. yRotation = cameraTarget.rotation.y;
  10624. }
  10625. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10626. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10627. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10628. var dx = targetX - this.position.x;
  10629. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10630. var dz = (targetZ) - this.position.z;
  10631. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10632. var vy = dy * this.cameraAcceleration;
  10633. var vz = dz * this.cameraAcceleration * 2;
  10634. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10635. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10636. }
  10637. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10638. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10639. }
  10640. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10641. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10642. }
  10643. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10644. this.setTarget(cameraTarget.position);
  10645. };
  10646. FollowCamera.prototype._checkInputs = function () {
  10647. _super.prototype._checkInputs.call(this);
  10648. this.follow(this.target);
  10649. };
  10650. return FollowCamera;
  10651. })(BABYLON.TargetCamera);
  10652. BABYLON.FollowCamera = FollowCamera;
  10653. var ArcFollowCamera = (function (_super) {
  10654. __extends(ArcFollowCamera, _super);
  10655. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10656. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10657. this.alpha = alpha;
  10658. this.beta = beta;
  10659. this.radius = radius;
  10660. this.target = target;
  10661. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10662. this.follow();
  10663. }
  10664. ArcFollowCamera.prototype.follow = function () {
  10665. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10666. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10667. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10668. this.position = this.target.position.add(this._cartesianCoordinates);
  10669. this.setTarget(this.target.position);
  10670. };
  10671. ArcFollowCamera.prototype._checkInputs = function () {
  10672. _super.prototype._checkInputs.call(this);
  10673. this.follow();
  10674. };
  10675. return ArcFollowCamera;
  10676. })(BABYLON.TargetCamera);
  10677. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10678. })(BABYLON || (BABYLON = {}));
  10679. var BABYLON;
  10680. (function (BABYLON) {
  10681. // We're mainly based on the logic defined into the FreeCamera code
  10682. var TouchCamera = (function (_super) {
  10683. __extends(TouchCamera, _super);
  10684. function TouchCamera(name, position, scene) {
  10685. _super.call(this, name, position, scene);
  10686. this._offsetX = null;
  10687. this._offsetY = null;
  10688. this._pointerCount = 0;
  10689. this._pointerPressed = [];
  10690. this.angularSensibility = 200000.0;
  10691. this.moveSensibility = 500.0;
  10692. }
  10693. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10694. var _this = this;
  10695. var previousPosition;
  10696. if (this._attachedCanvas) {
  10697. return;
  10698. }
  10699. this._attachedCanvas = canvas;
  10700. if (this._onPointerDown === undefined) {
  10701. this._onPointerDown = function (evt) {
  10702. if (!noPreventDefault) {
  10703. evt.preventDefault();
  10704. }
  10705. _this._pointerPressed.push(evt.pointerId);
  10706. if (_this._pointerPressed.length !== 1) {
  10707. return;
  10708. }
  10709. previousPosition = {
  10710. x: evt.clientX,
  10711. y: evt.clientY
  10712. };
  10713. };
  10714. this._onPointerUp = function (evt) {
  10715. if (!noPreventDefault) {
  10716. evt.preventDefault();
  10717. }
  10718. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10719. if (index === -1) {
  10720. return;
  10721. }
  10722. _this._pointerPressed.splice(index, 1);
  10723. if (index != 0) {
  10724. return;
  10725. }
  10726. previousPosition = null;
  10727. _this._offsetX = null;
  10728. _this._offsetY = null;
  10729. };
  10730. this._onPointerMove = function (evt) {
  10731. if (!noPreventDefault) {
  10732. evt.preventDefault();
  10733. }
  10734. if (!previousPosition) {
  10735. return;
  10736. }
  10737. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10738. if (index != 0) {
  10739. return;
  10740. }
  10741. _this._offsetX = evt.clientX - previousPosition.x;
  10742. _this._offsetY = -(evt.clientY - previousPosition.y);
  10743. };
  10744. this._onLostFocus = function () {
  10745. _this._offsetX = null;
  10746. _this._offsetY = null;
  10747. };
  10748. }
  10749. canvas.addEventListener("pointerdown", this._onPointerDown);
  10750. canvas.addEventListener("pointerup", this._onPointerUp);
  10751. canvas.addEventListener("pointerout", this._onPointerUp);
  10752. canvas.addEventListener("pointermove", this._onPointerMove);
  10753. BABYLON.Tools.RegisterTopRootEvents([
  10754. { name: "blur", handler: this._onLostFocus }
  10755. ]);
  10756. };
  10757. TouchCamera.prototype.detachControl = function (canvas) {
  10758. if (this._attachedCanvas != canvas) {
  10759. return;
  10760. }
  10761. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10762. canvas.removeEventListener("pointerup", this._onPointerUp);
  10763. canvas.removeEventListener("pointerout", this._onPointerUp);
  10764. canvas.removeEventListener("pointermove", this._onPointerMove);
  10765. BABYLON.Tools.UnregisterTopRootEvents([
  10766. { name: "blur", handler: this._onLostFocus }
  10767. ]);
  10768. this._attachedCanvas = null;
  10769. };
  10770. TouchCamera.prototype._checkInputs = function () {
  10771. if (this._offsetX) {
  10772. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10773. if (this._pointerPressed.length > 1) {
  10774. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10775. }
  10776. else {
  10777. var speed = this._computeLocalCameraSpeed();
  10778. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10779. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10780. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10781. }
  10782. }
  10783. _super.prototype._checkInputs.call(this);
  10784. };
  10785. return TouchCamera;
  10786. })(BABYLON.FreeCamera);
  10787. BABYLON.TouchCamera = TouchCamera;
  10788. })(BABYLON || (BABYLON = {}));
  10789. var BABYLON;
  10790. (function (BABYLON) {
  10791. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10792. var ArcRotateCamera = (function (_super) {
  10793. __extends(ArcRotateCamera, _super);
  10794. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10795. var _this = this;
  10796. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10797. this.alpha = alpha;
  10798. this.beta = beta;
  10799. this.radius = radius;
  10800. this.target = target;
  10801. this.inertialAlphaOffset = 0;
  10802. this.inertialBetaOffset = 0;
  10803. this.inertialRadiusOffset = 0;
  10804. this.lowerAlphaLimit = null;
  10805. this.upperAlphaLimit = null;
  10806. this.lowerBetaLimit = 0.01;
  10807. this.upperBetaLimit = Math.PI;
  10808. this.lowerRadiusLimit = null;
  10809. this.upperRadiusLimit = null;
  10810. this.angularSensibilityX = 1000.0;
  10811. this.angularSensibilityY = 1000.0;
  10812. this.wheelPrecision = 3.0;
  10813. this.pinchPrecision = 2.0;
  10814. this.panningSensibility = 50.0;
  10815. this.inertialPanningX = 0;
  10816. this.inertialPanningY = 0;
  10817. this.keysUp = [38];
  10818. this.keysDown = [40];
  10819. this.keysLeft = [37];
  10820. this.keysRight = [39];
  10821. this.zoomOnFactor = 1;
  10822. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10823. this.pinchInwards = true;
  10824. this.allowUpsideDown = true;
  10825. this._keys = [];
  10826. this._viewMatrix = new BABYLON.Matrix();
  10827. this._isRightClick = false;
  10828. this._isCtrlPushed = false;
  10829. this.checkCollisions = false;
  10830. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10831. this._collider = new BABYLON.Collider();
  10832. this._previousPosition = BABYLON.Vector3.Zero();
  10833. this._collisionVelocity = BABYLON.Vector3.Zero();
  10834. this._newPosition = BABYLON.Vector3.Zero();
  10835. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10836. if (collidedMesh === void 0) { collidedMesh = null; }
  10837. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10838. newPosition.multiplyInPlace(_this._collider.radius);
  10839. }
  10840. if (!collidedMesh) {
  10841. _this._previousPosition.copyFrom(_this.position);
  10842. }
  10843. else {
  10844. _this.setPosition(_this.position);
  10845. if (_this.onCollide) {
  10846. _this.onCollide(collidedMesh);
  10847. }
  10848. }
  10849. // Recompute because of constraints
  10850. var cosa = Math.cos(_this.alpha);
  10851. var sina = Math.sin(_this.alpha);
  10852. var cosb = Math.cos(_this.beta);
  10853. var sinb = Math.sin(_this.beta);
  10854. var target = _this._getTargetPosition();
  10855. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10856. _this.position.copyFrom(_this._newPosition);
  10857. var up = _this.upVector;
  10858. if (_this.allowUpsideDown && _this.beta < 0) {
  10859. var up = up.clone();
  10860. up = up.negate();
  10861. }
  10862. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10863. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10864. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10865. _this._collisionTriggered = false;
  10866. };
  10867. if (!this.target) {
  10868. this.target = BABYLON.Vector3.Zero();
  10869. }
  10870. this.getViewMatrix();
  10871. }
  10872. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10873. //deprecated angularSensibility support
  10874. get: function () {
  10875. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10876. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10877. },
  10878. //deprecated angularSensibility support
  10879. set: function (value) {
  10880. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10881. this.angularSensibilityX = value;
  10882. this.angularSensibilityY = value;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. ArcRotateCamera.prototype._getTargetPosition = function () {
  10888. return this.target.position || this.target;
  10889. };
  10890. // Cache
  10891. ArcRotateCamera.prototype._initCache = function () {
  10892. _super.prototype._initCache.call(this);
  10893. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10894. this._cache.alpha = undefined;
  10895. this._cache.beta = undefined;
  10896. this._cache.radius = undefined;
  10897. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10898. };
  10899. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10900. if (!ignoreParentClass) {
  10901. _super.prototype._updateCache.call(this);
  10902. }
  10903. this._cache.target.copyFrom(this._getTargetPosition());
  10904. this._cache.alpha = this.alpha;
  10905. this._cache.beta = this.beta;
  10906. this._cache.radius = this.radius;
  10907. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10908. };
  10909. // Synchronized
  10910. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10911. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10912. return false;
  10913. return this._cache.target.equals(this._getTargetPosition())
  10914. && this._cache.alpha === this.alpha
  10915. && this._cache.beta === this.beta
  10916. && this._cache.radius === this.radius
  10917. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10918. };
  10919. // Methods
  10920. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10921. var _this = this;
  10922. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10923. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10924. var previousPinchDistance = 0;
  10925. var pointers = new BABYLON.SmartCollection();
  10926. if (this._attachedElement) {
  10927. return;
  10928. }
  10929. this._attachedElement = element;
  10930. var engine = this.getEngine();
  10931. if (this._onPointerDown === undefined) {
  10932. this._onPointerDown = function (evt) {
  10933. // Manage panning with right click
  10934. _this._isRightClick = evt.button === 2 ? true : false;
  10935. // manage pointers
  10936. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10937. cacheSoloPointer = pointers.item(evt.pointerId);
  10938. if (!noPreventDefault) {
  10939. evt.preventDefault();
  10940. }
  10941. };
  10942. this._onPointerUp = function (evt) {
  10943. cacheSoloPointer = null;
  10944. previousPinchDistance = 0;
  10945. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10946. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10947. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10948. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10949. pointers.empty();
  10950. if (!noPreventDefault) {
  10951. evt.preventDefault();
  10952. }
  10953. };
  10954. this._onContextMenu = function (evt) {
  10955. evt.preventDefault();
  10956. };
  10957. this._onPointerMove = function (evt) {
  10958. if (!noPreventDefault) {
  10959. evt.preventDefault();
  10960. }
  10961. switch (pointers.count) {
  10962. case 1:
  10963. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10964. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10965. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10966. }
  10967. else {
  10968. var offsetX = evt.clientX - cacheSoloPointer.x;
  10969. var offsetY = evt.clientY - cacheSoloPointer.y;
  10970. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10971. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10972. }
  10973. cacheSoloPointer.x = evt.clientX;
  10974. cacheSoloPointer.y = evt.clientY;
  10975. break;
  10976. case 2:
  10977. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10978. pointers.item(evt.pointerId).x = evt.clientX;
  10979. pointers.item(evt.pointerId).y = evt.clientY;
  10980. var direction = _this.pinchInwards ? 1 : -1;
  10981. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10982. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10983. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10984. if (previousPinchDistance === 0) {
  10985. previousPinchDistance = pinchSquaredDistance;
  10986. return;
  10987. }
  10988. if (pinchSquaredDistance !== previousPinchDistance) {
  10989. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10990. previousPinchDistance = pinchSquaredDistance;
  10991. }
  10992. break;
  10993. default:
  10994. if (pointers.item(evt.pointerId)) {
  10995. pointers.item(evt.pointerId).x = evt.clientX;
  10996. pointers.item(evt.pointerId).y = evt.clientY;
  10997. }
  10998. }
  10999. };
  11000. this._onMouseMove = function (evt) {
  11001. if (!engine.isPointerLock) {
  11002. return;
  11003. }
  11004. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11005. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11006. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11007. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11008. if (!noPreventDefault) {
  11009. evt.preventDefault();
  11010. }
  11011. };
  11012. this._wheel = function (event) {
  11013. var delta = 0;
  11014. if (event.wheelDelta) {
  11015. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11016. }
  11017. else if (event.detail) {
  11018. delta = -event.detail / _this.wheelPrecision;
  11019. }
  11020. if (delta)
  11021. _this.inertialRadiusOffset += delta;
  11022. if (event.preventDefault) {
  11023. if (!noPreventDefault) {
  11024. event.preventDefault();
  11025. }
  11026. }
  11027. };
  11028. this._onKeyDown = function (evt) {
  11029. _this._isCtrlPushed = evt.ctrlKey;
  11030. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11031. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11032. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11033. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11034. var index = _this._keys.indexOf(evt.keyCode);
  11035. if (index === -1) {
  11036. _this._keys.push(evt.keyCode);
  11037. }
  11038. if (evt.preventDefault) {
  11039. if (!noPreventDefault) {
  11040. evt.preventDefault();
  11041. }
  11042. }
  11043. }
  11044. };
  11045. this._onKeyUp = function (evt) {
  11046. _this._isCtrlPushed = evt.ctrlKey;
  11047. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11048. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11049. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11050. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11051. var index = _this._keys.indexOf(evt.keyCode);
  11052. if (index >= 0) {
  11053. _this._keys.splice(index, 1);
  11054. }
  11055. if (evt.preventDefault) {
  11056. if (!noPreventDefault) {
  11057. evt.preventDefault();
  11058. }
  11059. }
  11060. }
  11061. };
  11062. this._onLostFocus = function () {
  11063. _this._keys = [];
  11064. pointers.empty();
  11065. previousPinchDistance = 0;
  11066. cacheSoloPointer = null;
  11067. };
  11068. this._onGestureStart = function (e) {
  11069. if (window.MSGesture === undefined) {
  11070. return;
  11071. }
  11072. if (!_this._MSGestureHandler) {
  11073. _this._MSGestureHandler = new MSGesture();
  11074. _this._MSGestureHandler.target = element;
  11075. }
  11076. _this._MSGestureHandler.addPointer(e.pointerId);
  11077. };
  11078. this._onGesture = function (e) {
  11079. _this.radius *= e.scale;
  11080. if (e.preventDefault) {
  11081. if (!noPreventDefault) {
  11082. e.stopPropagation();
  11083. e.preventDefault();
  11084. }
  11085. }
  11086. };
  11087. this._reset = function () {
  11088. _this._keys = [];
  11089. _this.inertialAlphaOffset = 0;
  11090. _this.inertialBetaOffset = 0;
  11091. _this.inertialRadiusOffset = 0;
  11092. pointers.empty();
  11093. previousPinchDistance = 0;
  11094. cacheSoloPointer = null;
  11095. };
  11096. }
  11097. if (!useCtrlForPanning) {
  11098. element.addEventListener("contextmenu", this._onContextMenu, false);
  11099. }
  11100. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11101. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11102. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11103. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11104. element.addEventListener("mousemove", this._onMouseMove, false);
  11105. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11106. element.addEventListener("MSGestureChange", this._onGesture, false);
  11107. element.addEventListener('mousewheel', this._wheel, false);
  11108. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11109. BABYLON.Tools.RegisterTopRootEvents([
  11110. { name: "keydown", handler: this._onKeyDown },
  11111. { name: "keyup", handler: this._onKeyUp },
  11112. { name: "blur", handler: this._onLostFocus }
  11113. ]);
  11114. };
  11115. ArcRotateCamera.prototype.detachControl = function (element) {
  11116. if (this._attachedElement !== element) {
  11117. return;
  11118. }
  11119. element.removeEventListener("contextmenu", this._onContextMenu);
  11120. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11121. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11122. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11123. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11124. element.removeEventListener("mousemove", this._onMouseMove);
  11125. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11126. element.removeEventListener("MSGestureChange", this._onGesture);
  11127. element.removeEventListener('mousewheel', this._wheel);
  11128. element.removeEventListener('DOMMouseScroll', this._wheel);
  11129. BABYLON.Tools.UnregisterTopRootEvents([
  11130. { name: "keydown", handler: this._onKeyDown },
  11131. { name: "keyup", handler: this._onKeyUp },
  11132. { name: "blur", handler: this._onLostFocus }
  11133. ]);
  11134. this._MSGestureHandler = null;
  11135. this._attachedElement = null;
  11136. if (this._reset) {
  11137. this._reset();
  11138. }
  11139. };
  11140. ArcRotateCamera.prototype._checkInputs = function () {
  11141. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11142. if (this._collisionTriggered) {
  11143. return;
  11144. }
  11145. // Keyboard
  11146. for (var index = 0; index < this._keys.length; index++) {
  11147. var keyCode = this._keys[index];
  11148. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11149. this.inertialAlphaOffset -= 0.01;
  11150. }
  11151. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11152. this.inertialBetaOffset -= 0.01;
  11153. }
  11154. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11155. this.inertialAlphaOffset += 0.01;
  11156. }
  11157. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11158. this.inertialBetaOffset += 0.01;
  11159. }
  11160. }
  11161. // Inertia
  11162. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11163. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11164. this.beta += this.inertialBetaOffset;
  11165. this.radius -= this.inertialRadiusOffset;
  11166. this.inertialAlphaOffset *= this.inertia;
  11167. this.inertialBetaOffset *= this.inertia;
  11168. this.inertialRadiusOffset *= this.inertia;
  11169. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11170. this.inertialAlphaOffset = 0;
  11171. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11172. this.inertialBetaOffset = 0;
  11173. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11174. this.inertialRadiusOffset = 0;
  11175. }
  11176. // Panning inertia
  11177. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11178. if (!this._localDirection) {
  11179. this._localDirection = BABYLON.Vector3.Zero();
  11180. this._transformedDirection = BABYLON.Vector3.Zero();
  11181. }
  11182. this.inertialPanningX *= this.inertia;
  11183. this.inertialPanningY *= this.inertia;
  11184. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11185. this.inertialPanningX = 0;
  11186. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11187. this.inertialPanningY = 0;
  11188. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11189. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11190. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11191. this.target.addInPlace(this._transformedDirection);
  11192. }
  11193. // Limits
  11194. this._checkLimits();
  11195. _super.prototype._checkInputs.call(this);
  11196. };
  11197. ArcRotateCamera.prototype._checkLimits = function () {
  11198. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11199. if (this.allowUpsideDown && this.beta > Math.PI) {
  11200. this.beta = this.beta - (2 * Math.PI);
  11201. }
  11202. }
  11203. else {
  11204. if (this.beta < this.lowerBetaLimit) {
  11205. this.beta = this.lowerBetaLimit;
  11206. }
  11207. }
  11208. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11209. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11210. this.beta = this.beta + (2 * Math.PI);
  11211. }
  11212. }
  11213. else {
  11214. if (this.beta > this.upperBetaLimit) {
  11215. this.beta = this.upperBetaLimit;
  11216. }
  11217. }
  11218. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11219. this.alpha = this.lowerAlphaLimit;
  11220. }
  11221. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11222. this.alpha = this.upperAlphaLimit;
  11223. }
  11224. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11225. this.radius = this.lowerRadiusLimit;
  11226. }
  11227. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11228. this.radius = this.upperRadiusLimit;
  11229. }
  11230. };
  11231. ArcRotateCamera.prototype.setPosition = function (position) {
  11232. if (this.position.equals(position)) {
  11233. return;
  11234. }
  11235. var radiusv3 = position.subtract(this._getTargetPosition());
  11236. this.radius = radiusv3.length();
  11237. // Alpha
  11238. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11239. if (radiusv3.z < 0) {
  11240. this.alpha = 2 * Math.PI - this.alpha;
  11241. }
  11242. // Beta
  11243. this.beta = Math.acos(radiusv3.y / this.radius);
  11244. this._checkLimits();
  11245. };
  11246. ArcRotateCamera.prototype.setTarget = function (target) {
  11247. this.target = target;
  11248. };
  11249. ArcRotateCamera.prototype._getViewMatrix = function () {
  11250. // Compute
  11251. var cosa = Math.cos(this.alpha);
  11252. var sina = Math.sin(this.alpha);
  11253. var cosb = Math.cos(this.beta);
  11254. var sinb = Math.sin(this.beta);
  11255. var target = this._getTargetPosition();
  11256. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11257. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11258. this._collider.radius = this.collisionRadius;
  11259. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11260. this._collisionTriggered = true;
  11261. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11262. }
  11263. else {
  11264. this.position.copyFrom(this._newPosition);
  11265. var up = this.upVector;
  11266. if (this.allowUpsideDown && this.beta < 0) {
  11267. var up = up.clone();
  11268. up = up.negate();
  11269. }
  11270. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11271. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11272. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11273. }
  11274. return this._viewMatrix;
  11275. };
  11276. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11277. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11278. meshes = meshes || this.getScene().meshes;
  11279. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11280. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11281. this.radius = distance * this.zoomOnFactor;
  11282. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11283. };
  11284. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11285. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11286. var meshesOrMinMaxVector;
  11287. var distance;
  11288. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11289. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11290. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11291. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11292. }
  11293. else {
  11294. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11295. distance = meshesOrMinMaxVectorAndDistance.distance;
  11296. }
  11297. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11298. if (!doNotUpdateMaxZ) {
  11299. this.maxZ = distance * 2;
  11300. }
  11301. };
  11302. /**
  11303. * @override
  11304. * Override Camera.createRigCamera
  11305. */
  11306. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11307. switch (this.cameraRigMode) {
  11308. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11309. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11310. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11312. case BABYLON.Camera.RIG_MODE_VR:
  11313. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11314. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11315. }
  11316. };
  11317. /**
  11318. * @override
  11319. * Override Camera._updateRigCameras
  11320. */
  11321. ArcRotateCamera.prototype._updateRigCameras = function () {
  11322. switch (this.cameraRigMode) {
  11323. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11324. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11325. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11326. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11327. case BABYLON.Camera.RIG_MODE_VR:
  11328. var camLeft = this._rigCameras[0];
  11329. var camRight = this._rigCameras[1];
  11330. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11331. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11332. camLeft.beta = camRight.beta = this.beta;
  11333. camLeft.radius = camRight.radius = this.radius;
  11334. break;
  11335. }
  11336. _super.prototype._updateRigCameras.call(this);
  11337. };
  11338. return ArcRotateCamera;
  11339. })(BABYLON.TargetCamera);
  11340. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11341. })(BABYLON || (BABYLON = {}));
  11342. var BABYLON;
  11343. (function (BABYLON) {
  11344. var RenderingManager = (function () {
  11345. function RenderingManager(scene) {
  11346. this._renderingGroups = new Array();
  11347. this._scene = scene;
  11348. }
  11349. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11350. if (this._scene._activeParticleSystems.length === 0) {
  11351. return;
  11352. }
  11353. // Particles
  11354. var activeCamera = this._scene.activeCamera;
  11355. var beforeParticlesDate = BABYLON.Tools.Now;
  11356. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11357. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11358. if (particleSystem.renderingGroupId !== index) {
  11359. continue;
  11360. }
  11361. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11362. continue;
  11363. }
  11364. this._clearDepthBuffer();
  11365. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11366. this._scene._activeParticles += particleSystem.render();
  11367. }
  11368. }
  11369. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11370. };
  11371. RenderingManager.prototype._renderSprites = function (index) {
  11372. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11373. return;
  11374. }
  11375. // Sprites
  11376. var activeCamera = this._scene.activeCamera;
  11377. var beforeSpritessDate = BABYLON.Tools.Now;
  11378. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11379. var spriteManager = this._scene.spriteManagers[id];
  11380. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11381. this._clearDepthBuffer();
  11382. spriteManager.render();
  11383. }
  11384. }
  11385. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11386. };
  11387. RenderingManager.prototype._clearDepthBuffer = function () {
  11388. if (this._depthBufferAlreadyCleaned) {
  11389. return;
  11390. }
  11391. this._scene.getEngine().clear(0, false, true);
  11392. this._depthBufferAlreadyCleaned = true;
  11393. };
  11394. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11395. if (this._currentRenderSprites) {
  11396. this._renderSprites(this._currentIndex);
  11397. }
  11398. if (this._currentRenderParticles) {
  11399. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11400. }
  11401. };
  11402. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11403. this._currentActiveMeshes = activeMeshes;
  11404. this._currentRenderParticles = renderParticles;
  11405. this._currentRenderSprites = renderSprites;
  11406. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11407. this._depthBufferAlreadyCleaned = false;
  11408. var renderingGroup = this._renderingGroups[index];
  11409. var needToStepBack = false;
  11410. this._currentIndex = index;
  11411. if (renderingGroup) {
  11412. this._clearDepthBuffer();
  11413. if (!renderingGroup.onBeforeTransparentRendering) {
  11414. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11415. }
  11416. if (!renderingGroup.render(customRenderFunction)) {
  11417. this._renderingGroups.splice(index, 1);
  11418. needToStepBack = true;
  11419. this._renderSpritesAndParticles();
  11420. }
  11421. }
  11422. else {
  11423. this._renderSpritesAndParticles();
  11424. }
  11425. if (needToStepBack) {
  11426. index--;
  11427. }
  11428. }
  11429. };
  11430. RenderingManager.prototype.reset = function () {
  11431. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11432. if (renderingGroup) {
  11433. renderingGroup.prepare();
  11434. }
  11435. });
  11436. };
  11437. RenderingManager.prototype.dispatch = function (subMesh) {
  11438. var mesh = subMesh.getMesh();
  11439. var renderingGroupId = mesh.renderingGroupId || 0;
  11440. if (!this._renderingGroups[renderingGroupId]) {
  11441. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11442. }
  11443. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11444. };
  11445. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11446. return RenderingManager;
  11447. })();
  11448. BABYLON.RenderingManager = RenderingManager;
  11449. })(BABYLON || (BABYLON = {}));
  11450. var BABYLON;
  11451. (function (BABYLON) {
  11452. var RenderingGroup = (function () {
  11453. function RenderingGroup(index, scene) {
  11454. this.index = index;
  11455. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11456. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11457. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11458. this._scene = scene;
  11459. }
  11460. RenderingGroup.prototype.render = function (customRenderFunction) {
  11461. if (customRenderFunction) {
  11462. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11463. return true;
  11464. }
  11465. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11466. if (this.onBeforeTransparentRendering) {
  11467. this.onBeforeTransparentRendering();
  11468. }
  11469. return false;
  11470. }
  11471. var engine = this._scene.getEngine();
  11472. // Opaque
  11473. var subIndex;
  11474. var submesh;
  11475. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11476. submesh = this._opaqueSubMeshes.data[subIndex];
  11477. submesh.render(false);
  11478. }
  11479. // Alpha test
  11480. engine.setAlphaTesting(true);
  11481. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11482. submesh = this._alphaTestSubMeshes.data[subIndex];
  11483. submesh.render(false);
  11484. }
  11485. engine.setAlphaTesting(false);
  11486. if (this.onBeforeTransparentRendering) {
  11487. this.onBeforeTransparentRendering();
  11488. }
  11489. // Transparent
  11490. if (this._transparentSubMeshes.length) {
  11491. // Sorting
  11492. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11493. submesh = this._transparentSubMeshes.data[subIndex];
  11494. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11495. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11496. }
  11497. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11498. sortedArray.sort(function (a, b) {
  11499. // Alpha index first
  11500. if (a._alphaIndex > b._alphaIndex) {
  11501. return 1;
  11502. }
  11503. if (a._alphaIndex < b._alphaIndex) {
  11504. return -1;
  11505. }
  11506. // Then distance to camera
  11507. if (a._distanceToCamera < b._distanceToCamera) {
  11508. return 1;
  11509. }
  11510. if (a._distanceToCamera > b._distanceToCamera) {
  11511. return -1;
  11512. }
  11513. return 0;
  11514. });
  11515. // Rendering
  11516. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11517. submesh = sortedArray[subIndex];
  11518. submesh.render(true);
  11519. }
  11520. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11521. }
  11522. return true;
  11523. };
  11524. RenderingGroup.prototype.prepare = function () {
  11525. this._opaqueSubMeshes.reset();
  11526. this._transparentSubMeshes.reset();
  11527. this._alphaTestSubMeshes.reset();
  11528. };
  11529. RenderingGroup.prototype.dispatch = function (subMesh) {
  11530. var material = subMesh.getMaterial();
  11531. var mesh = subMesh.getMesh();
  11532. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11533. this._transparentSubMeshes.push(subMesh);
  11534. }
  11535. else if (material.needAlphaTesting()) {
  11536. this._alphaTestSubMeshes.push(subMesh);
  11537. }
  11538. else {
  11539. this._opaqueSubMeshes.push(subMesh); // Opaque
  11540. }
  11541. };
  11542. return RenderingGroup;
  11543. })();
  11544. BABYLON.RenderingGroup = RenderingGroup;
  11545. })(BABYLON || (BABYLON = {}));
  11546. var BABYLON;
  11547. (function (BABYLON) {
  11548. /**
  11549. * Represents a scene to be rendered by the engine.
  11550. * @see http://doc.babylonjs.com/page.php?p=21911
  11551. */
  11552. var Scene = (function () {
  11553. /**
  11554. * @constructor
  11555. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11556. */
  11557. function Scene(engine) {
  11558. // Members
  11559. this.autoClear = true;
  11560. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11561. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11562. this.forceWireframe = false;
  11563. this.forcePointsCloud = false;
  11564. this.forceShowBoundingBoxes = false;
  11565. this.animationsEnabled = true;
  11566. this.constantlyUpdateMeshUnderPointer = false;
  11567. 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
  11568. // Fog
  11569. /**
  11570. * is fog enabled on this scene.
  11571. * @type {boolean}
  11572. */
  11573. this.fogEnabled = true;
  11574. this.fogMode = Scene.FOGMODE_NONE;
  11575. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11576. this.fogDensity = 0.1;
  11577. this.fogStart = 0;
  11578. this.fogEnd = 1000.0;
  11579. // Lights
  11580. /**
  11581. * is shadow enabled on this scene.
  11582. * @type {boolean}
  11583. */
  11584. this.shadowsEnabled = true;
  11585. /**
  11586. * is light enabled on this scene.
  11587. * @type {boolean}
  11588. */
  11589. this.lightsEnabled = true;
  11590. /**
  11591. * All of the lights added to this scene.
  11592. * @see BABYLON.Light
  11593. * @type {BABYLON.Light[]}
  11594. */
  11595. this.lights = new Array();
  11596. // Cameras
  11597. /**
  11598. * All of the cameras added to this scene.
  11599. * @see BABYLON.Camera
  11600. * @type {BABYLON.Camera[]}
  11601. */
  11602. this.cameras = new Array();
  11603. this.activeCameras = new Array();
  11604. // Meshes
  11605. /**
  11606. * All of the (abstract) meshes added to this scene.
  11607. * @see BABYLON.AbstractMesh
  11608. * @type {BABYLON.AbstractMesh[]}
  11609. */
  11610. this.meshes = new Array();
  11611. // Geometries
  11612. this._geometries = new Array();
  11613. this.materials = new Array();
  11614. this.multiMaterials = new Array();
  11615. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11616. // Textures
  11617. this.texturesEnabled = true;
  11618. this.textures = new Array();
  11619. // Particles
  11620. this.particlesEnabled = true;
  11621. this.particleSystems = new Array();
  11622. // Sprites
  11623. this.spritesEnabled = true;
  11624. this.spriteManagers = new Array();
  11625. // Layers
  11626. this.layers = new Array();
  11627. // Skeletons
  11628. this.skeletonsEnabled = true;
  11629. this.skeletons = new Array();
  11630. // Lens flares
  11631. this.lensFlaresEnabled = true;
  11632. this.lensFlareSystems = new Array();
  11633. // Collisions
  11634. this.collisionsEnabled = true;
  11635. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11636. // Postprocesses
  11637. this.postProcessesEnabled = true;
  11638. // Customs render targets
  11639. this.renderTargetsEnabled = true;
  11640. this.dumpNextRenderTargets = false;
  11641. this.customRenderTargets = new Array();
  11642. // Imported meshes
  11643. this.importedMeshesFiles = new Array();
  11644. // Probes
  11645. this.probesEnabled = true;
  11646. this.reflectionProbes = new Array();
  11647. this._actionManagers = new Array();
  11648. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11649. // Procedural textures
  11650. this.proceduralTexturesEnabled = true;
  11651. this._proceduralTextures = new Array();
  11652. this.soundTracks = new Array();
  11653. this._audioEnabled = true;
  11654. this._headphone = false;
  11655. this._totalVertices = 0;
  11656. this._activeIndices = 0;
  11657. this._activeParticles = 0;
  11658. this._lastFrameDuration = 0;
  11659. this._evaluateActiveMeshesDuration = 0;
  11660. this._renderTargetsDuration = 0;
  11661. this._particlesDuration = 0;
  11662. this._renderDuration = 0;
  11663. this._spritesDuration = 0;
  11664. this._animationRatio = 0;
  11665. this._renderId = 0;
  11666. this._executeWhenReadyTimeoutId = -1;
  11667. this._toBeDisposed = new BABYLON.SmartArray(256);
  11668. this._onReadyCallbacks = new Array();
  11669. this._pendingData = []; //ANY
  11670. this._onBeforeRenderCallbacks = new Array();
  11671. this._onAfterRenderCallbacks = new Array();
  11672. this._activeMeshes = new BABYLON.SmartArray(256);
  11673. this._processedMaterials = new BABYLON.SmartArray(256);
  11674. this._renderTargets = new BABYLON.SmartArray(256);
  11675. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11676. this._activeSkeletons = new BABYLON.SmartArray(32);
  11677. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11678. this._activeBones = 0;
  11679. this._activeAnimatables = new Array();
  11680. this._transformMatrix = BABYLON.Matrix.Zero();
  11681. this._edgesRenderers = new BABYLON.SmartArray(16);
  11682. this._uniqueIdCounter = 0;
  11683. this._engine = engine;
  11684. engine.scenes.push(this);
  11685. this._renderingManager = new BABYLON.RenderingManager(this);
  11686. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11687. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11688. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11689. if (BABYLON.OutlineRenderer) {
  11690. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11691. }
  11692. this.attachControl();
  11693. this._debugLayer = new BABYLON.DebugLayer(this);
  11694. if (BABYLON.SoundTrack) {
  11695. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11696. }
  11697. //simplification queue
  11698. if (BABYLON.SimplificationQueue) {
  11699. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11700. }
  11701. //collision coordinator initialization. For now legacy per default.
  11702. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11703. }
  11704. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11705. get: function () {
  11706. return Scene._FOGMODE_NONE;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11712. get: function () {
  11713. return Scene._FOGMODE_EXP;
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11719. get: function () {
  11720. return Scene._FOGMODE_EXP2;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11726. get: function () {
  11727. return Scene._FOGMODE_LINEAR;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Scene.prototype, "debugLayer", {
  11733. // Properties
  11734. get: function () {
  11735. return this._debugLayer;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11741. get: function () {
  11742. return this._workerCollisions;
  11743. },
  11744. set: function (enabled) {
  11745. enabled = (enabled && !!Worker);
  11746. this._workerCollisions = enabled;
  11747. if (this.collisionCoordinator) {
  11748. this.collisionCoordinator.destroy();
  11749. }
  11750. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11751. this.collisionCoordinator.init(this);
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11757. get: function () {
  11758. return this._selectionOctree;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11764. /**
  11765. * The mesh that is currently under the pointer.
  11766. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11767. */
  11768. get: function () {
  11769. return this._meshUnderPointer;
  11770. },
  11771. enumerable: true,
  11772. configurable: true
  11773. });
  11774. Object.defineProperty(Scene.prototype, "pointerX", {
  11775. /**
  11776. * Current on-screen X position of the pointer
  11777. * @return {number} X position of the pointer
  11778. */
  11779. get: function () {
  11780. return this._pointerX;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Scene.prototype, "pointerY", {
  11786. /**
  11787. * Current on-screen Y position of the pointer
  11788. * @return {number} Y position of the pointer
  11789. */
  11790. get: function () {
  11791. return this._pointerY;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Scene.prototype.getCachedMaterial = function () {
  11797. return this._cachedMaterial;
  11798. };
  11799. Scene.prototype.getBoundingBoxRenderer = function () {
  11800. return this._boundingBoxRenderer;
  11801. };
  11802. Scene.prototype.getOutlineRenderer = function () {
  11803. return this._outlineRenderer;
  11804. };
  11805. Scene.prototype.getEngine = function () {
  11806. return this._engine;
  11807. };
  11808. Scene.prototype.getTotalVertices = function () {
  11809. return this._totalVertices;
  11810. };
  11811. Scene.prototype.getActiveIndices = function () {
  11812. return this._activeIndices;
  11813. };
  11814. Scene.prototype.getActiveParticles = function () {
  11815. return this._activeParticles;
  11816. };
  11817. Scene.prototype.getActiveBones = function () {
  11818. return this._activeBones;
  11819. };
  11820. // Stats
  11821. Scene.prototype.getLastFrameDuration = function () {
  11822. return this._lastFrameDuration;
  11823. };
  11824. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11825. return this._evaluateActiveMeshesDuration;
  11826. };
  11827. Scene.prototype.getActiveMeshes = function () {
  11828. return this._activeMeshes;
  11829. };
  11830. Scene.prototype.getRenderTargetsDuration = function () {
  11831. return this._renderTargetsDuration;
  11832. };
  11833. Scene.prototype.getRenderDuration = function () {
  11834. return this._renderDuration;
  11835. };
  11836. Scene.prototype.getParticlesDuration = function () {
  11837. return this._particlesDuration;
  11838. };
  11839. Scene.prototype.getSpritesDuration = function () {
  11840. return this._spritesDuration;
  11841. };
  11842. Scene.prototype.getAnimationRatio = function () {
  11843. return this._animationRatio;
  11844. };
  11845. Scene.prototype.getRenderId = function () {
  11846. return this._renderId;
  11847. };
  11848. Scene.prototype.incrementRenderId = function () {
  11849. this._renderId++;
  11850. };
  11851. Scene.prototype._updatePointerPosition = function (evt) {
  11852. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11853. this._pointerX = evt.clientX - canvasRect.left;
  11854. this._pointerY = evt.clientY - canvasRect.top;
  11855. if (this.cameraToUseForPointers) {
  11856. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11857. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11858. }
  11859. };
  11860. // Pointers handling
  11861. Scene.prototype.attachControl = function () {
  11862. var _this = this;
  11863. var spritePredicate = function (sprite) {
  11864. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11865. };
  11866. this._onPointerMove = function (evt) {
  11867. var canvas = _this._engine.getRenderingCanvas();
  11868. _this._updatePointerPosition(evt);
  11869. // Meshes
  11870. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  11871. if (pickResult.hit && pickResult.pickedMesh) {
  11872. _this._meshUnderPointer = pickResult.pickedMesh;
  11873. _this.setPointerOverMesh(pickResult.pickedMesh);
  11874. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11875. canvas.style.cursor = "pointer";
  11876. }
  11877. else {
  11878. canvas.style.cursor = "";
  11879. }
  11880. }
  11881. else {
  11882. // Sprites
  11883. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11884. if (pickResult.hit && pickResult.pickedSprite) {
  11885. canvas.style.cursor = "pointer";
  11886. }
  11887. else {
  11888. // Restore pointer
  11889. _this.setPointerOverMesh(null);
  11890. canvas.style.cursor = "";
  11891. _this._meshUnderPointer = null;
  11892. }
  11893. }
  11894. if (_this.onPointerMove) {
  11895. _this.onPointerMove(evt, pickResult);
  11896. }
  11897. };
  11898. this._onPointerDown = function (evt) {
  11899. _this._updatePointerPosition(evt);
  11900. var predicate = null;
  11901. // Meshes
  11902. if (!_this.onPointerDown) {
  11903. predicate = function (mesh) {
  11904. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11905. };
  11906. }
  11907. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11908. if (pickResult.hit && pickResult.pickedMesh) {
  11909. if (pickResult.pickedMesh.actionManager) {
  11910. switch (evt.button) {
  11911. case 0:
  11912. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11913. break;
  11914. case 1:
  11915. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11916. break;
  11917. case 2:
  11918. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11919. break;
  11920. }
  11921. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11922. }
  11923. }
  11924. if (_this.onPointerDown) {
  11925. _this.onPointerDown(evt, pickResult);
  11926. }
  11927. // Sprites
  11928. if (_this.spriteManagers.length > 0) {
  11929. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11930. if (pickResult.hit && pickResult.pickedSprite) {
  11931. if (pickResult.pickedSprite.actionManager) {
  11932. switch (evt.button) {
  11933. case 0:
  11934. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11935. break;
  11936. case 1:
  11937. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11938. break;
  11939. case 2:
  11940. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11941. break;
  11942. }
  11943. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11944. }
  11945. }
  11946. }
  11947. };
  11948. this._onPointerUp = function (evt) {
  11949. var predicate = null;
  11950. _this._updatePointerPosition(evt);
  11951. if (!_this.onPointerUp) {
  11952. predicate = function (mesh) {
  11953. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11954. };
  11955. }
  11956. // Meshes
  11957. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11958. if (pickResult.hit && pickResult.pickedMesh) {
  11959. if (pickResult.pickedMesh.actionManager) {
  11960. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11961. }
  11962. }
  11963. if (_this.onPointerUp) {
  11964. _this.onPointerUp(evt, pickResult);
  11965. }
  11966. // Sprites
  11967. if (_this.spriteManagers.length > 0) {
  11968. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11969. if (pickResult.hit && pickResult.pickedSprite) {
  11970. if (pickResult.pickedSprite.actionManager) {
  11971. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11972. }
  11973. }
  11974. }
  11975. };
  11976. this._onKeyDown = function (evt) {
  11977. if (_this.actionManager) {
  11978. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11979. }
  11980. };
  11981. this._onKeyUp = function (evt) {
  11982. if (_this.actionManager) {
  11983. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11984. }
  11985. };
  11986. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11987. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11988. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11989. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11990. // Wheel
  11991. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11992. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11993. BABYLON.Tools.RegisterTopRootEvents([
  11994. { name: "keydown", handler: this._onKeyDown },
  11995. { name: "keyup", handler: this._onKeyUp }
  11996. ]);
  11997. };
  11998. Scene.prototype.detachControl = function () {
  11999. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12000. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12001. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12002. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12003. // Wheel
  12004. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12005. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12006. BABYLON.Tools.UnregisterTopRootEvents([
  12007. { name: "keydown", handler: this._onKeyDown },
  12008. { name: "keyup", handler: this._onKeyUp }
  12009. ]);
  12010. };
  12011. // Ready
  12012. Scene.prototype.isReady = function () {
  12013. if (this._pendingData.length > 0) {
  12014. return false;
  12015. }
  12016. var index;
  12017. for (index = 0; index < this._geometries.length; index++) {
  12018. var geometry = this._geometries[index];
  12019. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12020. return false;
  12021. }
  12022. }
  12023. for (index = 0; index < this.meshes.length; index++) {
  12024. var mesh = this.meshes[index];
  12025. if (!mesh.isReady()) {
  12026. return false;
  12027. }
  12028. var mat = mesh.material;
  12029. if (mat) {
  12030. if (!mat.isReady(mesh)) {
  12031. return false;
  12032. }
  12033. }
  12034. }
  12035. return true;
  12036. };
  12037. Scene.prototype.resetCachedMaterial = function () {
  12038. this._cachedMaterial = null;
  12039. };
  12040. Scene.prototype.registerBeforeRender = function (func) {
  12041. this._onBeforeRenderCallbacks.push(func);
  12042. };
  12043. Scene.prototype.unregisterBeforeRender = function (func) {
  12044. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12045. if (index > -1) {
  12046. this._onBeforeRenderCallbacks.splice(index, 1);
  12047. }
  12048. };
  12049. Scene.prototype.registerAfterRender = function (func) {
  12050. this._onAfterRenderCallbacks.push(func);
  12051. };
  12052. Scene.prototype.unregisterAfterRender = function (func) {
  12053. var index = this._onAfterRenderCallbacks.indexOf(func);
  12054. if (index > -1) {
  12055. this._onAfterRenderCallbacks.splice(index, 1);
  12056. }
  12057. };
  12058. Scene.prototype._addPendingData = function (data) {
  12059. this._pendingData.push(data);
  12060. };
  12061. Scene.prototype._removePendingData = function (data) {
  12062. var index = this._pendingData.indexOf(data);
  12063. if (index !== -1) {
  12064. this._pendingData.splice(index, 1);
  12065. }
  12066. };
  12067. Scene.prototype.getWaitingItemsCount = function () {
  12068. return this._pendingData.length;
  12069. };
  12070. /**
  12071. * Registers a function to be executed when the scene is ready.
  12072. * @param {Function} func - the function to be executed.
  12073. */
  12074. Scene.prototype.executeWhenReady = function (func) {
  12075. var _this = this;
  12076. this._onReadyCallbacks.push(func);
  12077. if (this._executeWhenReadyTimeoutId !== -1) {
  12078. return;
  12079. }
  12080. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12081. _this._checkIsReady();
  12082. }, 150);
  12083. };
  12084. Scene.prototype._checkIsReady = function () {
  12085. var _this = this;
  12086. if (this.isReady()) {
  12087. this._onReadyCallbacks.forEach(function (func) {
  12088. func();
  12089. });
  12090. this._onReadyCallbacks = [];
  12091. this._executeWhenReadyTimeoutId = -1;
  12092. return;
  12093. }
  12094. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12095. _this._checkIsReady();
  12096. }, 150);
  12097. };
  12098. // Animations
  12099. /**
  12100. * Will start the animation sequence of a given target
  12101. * @param target - the target
  12102. * @param {number} from - from which frame should animation start
  12103. * @param {number} to - till which frame should animation run.
  12104. * @param {boolean} [loop] - should the animation loop
  12105. * @param {number} [speedRatio] - the speed in which to run the animation
  12106. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12107. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12108. * @return {BABYLON.Animatable} the animatable object created for this animation
  12109. * @see BABYLON.Animatable
  12110. * @see http://doc.babylonjs.com/page.php?p=22081
  12111. */
  12112. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12113. if (speedRatio === void 0) { speedRatio = 1.0; }
  12114. this.stopAnimation(target);
  12115. if (!animatable) {
  12116. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12117. }
  12118. // Local animations
  12119. if (target.animations) {
  12120. animatable.appendAnimations(target, target.animations);
  12121. }
  12122. // Children animations
  12123. if (target.getAnimatables) {
  12124. var animatables = target.getAnimatables();
  12125. for (var index = 0; index < animatables.length; index++) {
  12126. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12127. }
  12128. }
  12129. return animatable;
  12130. };
  12131. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12132. if (speedRatio === undefined) {
  12133. speedRatio = 1.0;
  12134. }
  12135. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12136. return animatable;
  12137. };
  12138. Scene.prototype.getAnimatableByTarget = function (target) {
  12139. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12140. if (this._activeAnimatables[index].target === target) {
  12141. return this._activeAnimatables[index];
  12142. }
  12143. }
  12144. return null;
  12145. };
  12146. /**
  12147. * Will stop the animation of the given target
  12148. * @param target - the target
  12149. * @see beginAnimation
  12150. */
  12151. Scene.prototype.stopAnimation = function (target) {
  12152. var animatable = this.getAnimatableByTarget(target);
  12153. if (animatable) {
  12154. animatable.stop();
  12155. }
  12156. };
  12157. Scene.prototype._animate = function () {
  12158. if (!this.animationsEnabled) {
  12159. return;
  12160. }
  12161. if (!this._animationStartDate) {
  12162. this._animationStartDate = BABYLON.Tools.Now;
  12163. }
  12164. // Getting time
  12165. var now = BABYLON.Tools.Now;
  12166. var delay = now - this._animationStartDate;
  12167. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12168. this._activeAnimatables[index]._animate(delay);
  12169. }
  12170. };
  12171. // Matrix
  12172. Scene.prototype.getViewMatrix = function () {
  12173. return this._viewMatrix;
  12174. };
  12175. Scene.prototype.getProjectionMatrix = function () {
  12176. return this._projectionMatrix;
  12177. };
  12178. Scene.prototype.getTransformMatrix = function () {
  12179. return this._transformMatrix;
  12180. };
  12181. Scene.prototype.setTransformMatrix = function (view, projection) {
  12182. this._viewMatrix = view;
  12183. this._projectionMatrix = projection;
  12184. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12185. };
  12186. // Methods
  12187. Scene.prototype.addMesh = function (newMesh) {
  12188. newMesh.uniqueId = this._uniqueIdCounter++;
  12189. var position = this.meshes.push(newMesh);
  12190. //notify the collision coordinator
  12191. this.collisionCoordinator.onMeshAdded(newMesh);
  12192. if (this.onNewMeshAdded) {
  12193. this.onNewMeshAdded(newMesh, position, this);
  12194. }
  12195. };
  12196. Scene.prototype.removeMesh = function (toRemove) {
  12197. var index = this.meshes.indexOf(toRemove);
  12198. if (index !== -1) {
  12199. // Remove from the scene if mesh found
  12200. this.meshes.splice(index, 1);
  12201. }
  12202. //notify the collision coordinator
  12203. this.collisionCoordinator.onMeshRemoved(toRemove);
  12204. if (this.onMeshRemoved) {
  12205. this.onMeshRemoved(toRemove);
  12206. }
  12207. return index;
  12208. };
  12209. Scene.prototype.removeSkeleton = function (toRemove) {
  12210. var index = this.skeletons.indexOf(toRemove);
  12211. if (index !== -1) {
  12212. // Remove from the scene if mesh found
  12213. this.skeletons.splice(index, 1);
  12214. }
  12215. return index;
  12216. };
  12217. Scene.prototype.removeLight = function (toRemove) {
  12218. var index = this.lights.indexOf(toRemove);
  12219. if (index !== -1) {
  12220. // Remove from the scene if mesh found
  12221. this.lights.splice(index, 1);
  12222. }
  12223. if (this.onLightRemoved) {
  12224. this.onLightRemoved(toRemove);
  12225. }
  12226. return index;
  12227. };
  12228. Scene.prototype.removeCamera = function (toRemove) {
  12229. var index = this.cameras.indexOf(toRemove);
  12230. if (index !== -1) {
  12231. // Remove from the scene if mesh found
  12232. this.cameras.splice(index, 1);
  12233. }
  12234. // Remove from activeCameras
  12235. var index2 = this.activeCameras.indexOf(toRemove);
  12236. if (index2 !== -1) {
  12237. // Remove from the scene if mesh found
  12238. this.activeCameras.splice(index2, 1);
  12239. }
  12240. // Reset the activeCamera
  12241. if (this.activeCamera === toRemove) {
  12242. if (this.cameras.length > 0) {
  12243. this.activeCamera = this.cameras[0];
  12244. }
  12245. else {
  12246. this.activeCamera = null;
  12247. }
  12248. }
  12249. if (this.onCameraRemoved) {
  12250. this.onCameraRemoved(toRemove);
  12251. }
  12252. return index;
  12253. };
  12254. Scene.prototype.addLight = function (newLight) {
  12255. newLight.uniqueId = this._uniqueIdCounter++;
  12256. var position = this.lights.push(newLight);
  12257. if (this.onNewLightAdded) {
  12258. this.onNewLightAdded(newLight, position, this);
  12259. }
  12260. };
  12261. Scene.prototype.addCamera = function (newCamera) {
  12262. newCamera.uniqueId = this._uniqueIdCounter++;
  12263. var position = this.cameras.push(newCamera);
  12264. if (this.onNewCameraAdded) {
  12265. this.onNewCameraAdded(newCamera, position, this);
  12266. }
  12267. };
  12268. /**
  12269. * sets the active camera of the scene using its ID
  12270. * @param {string} id - the camera's ID
  12271. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12272. * @see activeCamera
  12273. */
  12274. Scene.prototype.setActiveCameraByID = function (id) {
  12275. var camera = this.getCameraByID(id);
  12276. if (camera) {
  12277. this.activeCamera = camera;
  12278. return camera;
  12279. }
  12280. return null;
  12281. };
  12282. /**
  12283. * sets the active camera of the scene using its name
  12284. * @param {string} name - the camera's name
  12285. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12286. * @see activeCamera
  12287. */
  12288. Scene.prototype.setActiveCameraByName = function (name) {
  12289. var camera = this.getCameraByName(name);
  12290. if (camera) {
  12291. this.activeCamera = camera;
  12292. return camera;
  12293. }
  12294. return null;
  12295. };
  12296. /**
  12297. * get a material using its id
  12298. * @param {string} the material's ID
  12299. * @return {BABYLON.Material|null} the material or null if none found.
  12300. */
  12301. Scene.prototype.getMaterialByID = function (id) {
  12302. for (var index = 0; index < this.materials.length; index++) {
  12303. if (this.materials[index].id === id) {
  12304. return this.materials[index];
  12305. }
  12306. }
  12307. return null;
  12308. };
  12309. /**
  12310. * get a material using its name
  12311. * @param {string} the material's name
  12312. * @return {BABYLON.Material|null} the material or null if none found.
  12313. */
  12314. Scene.prototype.getMaterialByName = function (name) {
  12315. for (var index = 0; index < this.materials.length; index++) {
  12316. if (this.materials[index].name === name) {
  12317. return this.materials[index];
  12318. }
  12319. }
  12320. return null;
  12321. };
  12322. Scene.prototype.getLensFlareSystemByName = function (name) {
  12323. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12324. if (this.lensFlareSystems[index].name === name) {
  12325. return this.lensFlareSystems[index];
  12326. }
  12327. }
  12328. return null;
  12329. };
  12330. Scene.prototype.getCameraByID = function (id) {
  12331. for (var index = 0; index < this.cameras.length; index++) {
  12332. if (this.cameras[index].id === id) {
  12333. return this.cameras[index];
  12334. }
  12335. }
  12336. return null;
  12337. };
  12338. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12339. for (var index = 0; index < this.cameras.length; index++) {
  12340. if (this.cameras[index].uniqueId === uniqueId) {
  12341. return this.cameras[index];
  12342. }
  12343. }
  12344. return null;
  12345. };
  12346. /**
  12347. * get a camera using its name
  12348. * @param {string} the camera's name
  12349. * @return {BABYLON.Camera|null} the camera or null if none found.
  12350. */
  12351. Scene.prototype.getCameraByName = function (name) {
  12352. for (var index = 0; index < this.cameras.length; index++) {
  12353. if (this.cameras[index].name === name) {
  12354. return this.cameras[index];
  12355. }
  12356. }
  12357. return null;
  12358. };
  12359. /**
  12360. * get a light node using its name
  12361. * @param {string} the light's name
  12362. * @return {BABYLON.Light|null} the light or null if none found.
  12363. */
  12364. Scene.prototype.getLightByName = function (name) {
  12365. for (var index = 0; index < this.lights.length; index++) {
  12366. if (this.lights[index].name === name) {
  12367. return this.lights[index];
  12368. }
  12369. }
  12370. return null;
  12371. };
  12372. /**
  12373. * get a light node using its ID
  12374. * @param {string} the light's id
  12375. * @return {BABYLON.Light|null} the light or null if none found.
  12376. */
  12377. Scene.prototype.getLightByID = function (id) {
  12378. for (var index = 0; index < this.lights.length; index++) {
  12379. if (this.lights[index].id === id) {
  12380. return this.lights[index];
  12381. }
  12382. }
  12383. return null;
  12384. };
  12385. /**
  12386. * get a light node using its scene-generated unique ID
  12387. * @param {number} the light's unique id
  12388. * @return {BABYLON.Light|null} the light or null if none found.
  12389. */
  12390. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12391. for (var index = 0; index < this.lights.length; index++) {
  12392. if (this.lights[index].uniqueId === uniqueId) {
  12393. return this.lights[index];
  12394. }
  12395. }
  12396. return null;
  12397. };
  12398. /**
  12399. * get a geometry using its ID
  12400. * @param {string} the geometry's id
  12401. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12402. */
  12403. Scene.prototype.getGeometryByID = function (id) {
  12404. for (var index = 0; index < this._geometries.length; index++) {
  12405. if (this._geometries[index].id === id) {
  12406. return this._geometries[index];
  12407. }
  12408. }
  12409. return null;
  12410. };
  12411. /**
  12412. * add a new geometry to this scene.
  12413. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12414. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12415. * @return {boolean} was the geometry added or not
  12416. */
  12417. Scene.prototype.pushGeometry = function (geometry, force) {
  12418. if (!force && this.getGeometryByID(geometry.id)) {
  12419. return false;
  12420. }
  12421. this._geometries.push(geometry);
  12422. //notify the collision coordinator
  12423. this.collisionCoordinator.onGeometryAdded(geometry);
  12424. if (this.onGeometryAdded) {
  12425. this.onGeometryAdded(geometry);
  12426. }
  12427. return true;
  12428. };
  12429. /**
  12430. * Removes an existing geometry
  12431. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12432. * @return {boolean} was the geometry removed or not
  12433. */
  12434. Scene.prototype.removeGeometry = function (geometry) {
  12435. var index = this._geometries.indexOf(geometry);
  12436. if (index > -1) {
  12437. this._geometries.splice(index, 1);
  12438. //notify the collision coordinator
  12439. this.collisionCoordinator.onGeometryDeleted(geometry);
  12440. if (this.onGeometryRemoved) {
  12441. this.onGeometryRemoved(geometry);
  12442. }
  12443. return true;
  12444. }
  12445. return false;
  12446. };
  12447. Scene.prototype.getGeometries = function () {
  12448. return this._geometries;
  12449. };
  12450. /**
  12451. * Get the first added mesh found of a given ID
  12452. * @param {string} id - the id to search for
  12453. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12454. */
  12455. Scene.prototype.getMeshByID = function (id) {
  12456. for (var index = 0; index < this.meshes.length; index++) {
  12457. if (this.meshes[index].id === id) {
  12458. return this.meshes[index];
  12459. }
  12460. }
  12461. return null;
  12462. };
  12463. /**
  12464. * Get a mesh with its auto-generated unique id
  12465. * @param {number} uniqueId - the unique id to search for
  12466. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12467. */
  12468. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12469. for (var index = 0; index < this.meshes.length; index++) {
  12470. if (this.meshes[index].uniqueId === uniqueId) {
  12471. return this.meshes[index];
  12472. }
  12473. }
  12474. return null;
  12475. };
  12476. /**
  12477. * Get a the last added mesh found of a given ID
  12478. * @param {string} id - the id to search for
  12479. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12480. */
  12481. Scene.prototype.getLastMeshByID = function (id) {
  12482. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12483. if (this.meshes[index].id === id) {
  12484. return this.meshes[index];
  12485. }
  12486. }
  12487. return null;
  12488. };
  12489. /**
  12490. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12491. * @param {string} id - the id to search for
  12492. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12493. */
  12494. Scene.prototype.getLastEntryByID = function (id) {
  12495. var index;
  12496. for (index = this.meshes.length - 1; index >= 0; index--) {
  12497. if (this.meshes[index].id === id) {
  12498. return this.meshes[index];
  12499. }
  12500. }
  12501. for (index = this.cameras.length - 1; index >= 0; index--) {
  12502. if (this.cameras[index].id === id) {
  12503. return this.cameras[index];
  12504. }
  12505. }
  12506. for (index = this.lights.length - 1; index >= 0; index--) {
  12507. if (this.lights[index].id === id) {
  12508. return this.lights[index];
  12509. }
  12510. }
  12511. return null;
  12512. };
  12513. Scene.prototype.getNodeByID = function (id) {
  12514. var mesh = this.getMeshByID(id);
  12515. if (mesh) {
  12516. return mesh;
  12517. }
  12518. var light = this.getLightByID(id);
  12519. if (light) {
  12520. return light;
  12521. }
  12522. return this.getCameraByID(id);
  12523. };
  12524. Scene.prototype.getNodeByName = function (name) {
  12525. var mesh = this.getMeshByName(name);
  12526. if (mesh) {
  12527. return mesh;
  12528. }
  12529. var light = this.getLightByName(name);
  12530. if (light) {
  12531. return light;
  12532. }
  12533. return this.getCameraByName(name);
  12534. };
  12535. Scene.prototype.getMeshByName = function (name) {
  12536. for (var index = 0; index < this.meshes.length; index++) {
  12537. if (this.meshes[index].name === name) {
  12538. return this.meshes[index];
  12539. }
  12540. }
  12541. return null;
  12542. };
  12543. Scene.prototype.getSoundByName = function (name) {
  12544. var index;
  12545. if (BABYLON.AudioEngine) {
  12546. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12547. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12548. return this.mainSoundTrack.soundCollection[index];
  12549. }
  12550. }
  12551. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12552. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12553. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12554. return this.soundTracks[sdIndex].soundCollection[index];
  12555. }
  12556. }
  12557. }
  12558. }
  12559. return null;
  12560. };
  12561. Scene.prototype.getLastSkeletonByID = function (id) {
  12562. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12563. if (this.skeletons[index].id === id) {
  12564. return this.skeletons[index];
  12565. }
  12566. }
  12567. return null;
  12568. };
  12569. Scene.prototype.getSkeletonById = function (id) {
  12570. for (var index = 0; index < this.skeletons.length; index++) {
  12571. if (this.skeletons[index].id === id) {
  12572. return this.skeletons[index];
  12573. }
  12574. }
  12575. return null;
  12576. };
  12577. Scene.prototype.getSkeletonByName = function (name) {
  12578. for (var index = 0; index < this.skeletons.length; index++) {
  12579. if (this.skeletons[index].name === name) {
  12580. return this.skeletons[index];
  12581. }
  12582. }
  12583. return null;
  12584. };
  12585. Scene.prototype.isActiveMesh = function (mesh) {
  12586. return (this._activeMeshes.indexOf(mesh) !== -1);
  12587. };
  12588. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12589. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12590. var material = subMesh.getMaterial();
  12591. if (mesh.showSubMeshesBoundingBox) {
  12592. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12593. }
  12594. if (material) {
  12595. // Render targets
  12596. if (material.getRenderTargetTextures) {
  12597. if (this._processedMaterials.indexOf(material) === -1) {
  12598. this._processedMaterials.push(material);
  12599. this._renderTargets.concat(material.getRenderTargetTextures());
  12600. }
  12601. }
  12602. // Dispatch
  12603. this._activeIndices += subMesh.indexCount;
  12604. this._renderingManager.dispatch(subMesh);
  12605. }
  12606. }
  12607. };
  12608. Scene.prototype._evaluateActiveMeshes = function () {
  12609. this.activeCamera._activeMeshes.reset();
  12610. this._activeMeshes.reset();
  12611. this._renderingManager.reset();
  12612. this._processedMaterials.reset();
  12613. this._activeParticleSystems.reset();
  12614. this._activeSkeletons.reset();
  12615. this._softwareSkinnedMeshes.reset();
  12616. this._boundingBoxRenderer.reset();
  12617. this._edgesRenderers.reset();
  12618. if (!this._frustumPlanes) {
  12619. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12620. }
  12621. else {
  12622. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12623. }
  12624. // Meshes
  12625. var meshes;
  12626. var len;
  12627. if (this._selectionOctree) {
  12628. var selection = this._selectionOctree.select(this._frustumPlanes);
  12629. meshes = selection.data;
  12630. len = selection.length;
  12631. }
  12632. else {
  12633. len = this.meshes.length;
  12634. meshes = this.meshes;
  12635. }
  12636. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12637. var mesh = meshes[meshIndex];
  12638. if (mesh.isBlocked) {
  12639. continue;
  12640. }
  12641. this._totalVertices += mesh.getTotalVertices();
  12642. if (!mesh.isReady() || !mesh.isEnabled()) {
  12643. continue;
  12644. }
  12645. mesh.computeWorldMatrix();
  12646. // Intersections
  12647. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12648. this._meshesForIntersections.pushNoDuplicate(mesh);
  12649. }
  12650. // Switch to current LOD
  12651. var meshLOD = mesh.getLOD(this.activeCamera);
  12652. if (!meshLOD) {
  12653. continue;
  12654. }
  12655. mesh._preActivate();
  12656. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12657. this._activeMeshes.push(mesh);
  12658. this.activeCamera._activeMeshes.push(mesh);
  12659. mesh._activate(this._renderId);
  12660. this._activeMesh(meshLOD);
  12661. }
  12662. }
  12663. // Particle systems
  12664. var beforeParticlesDate = BABYLON.Tools.Now;
  12665. if (this.particlesEnabled) {
  12666. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12667. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12668. var particleSystem = this.particleSystems[particleIndex];
  12669. if (!particleSystem.isStarted()) {
  12670. continue;
  12671. }
  12672. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12673. this._activeParticleSystems.push(particleSystem);
  12674. particleSystem.animate();
  12675. }
  12676. }
  12677. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12678. }
  12679. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12680. };
  12681. Scene.prototype._activeMesh = function (mesh) {
  12682. if (mesh.skeleton && this.skeletonsEnabled) {
  12683. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12684. if (!mesh.computeBonesUsingShaders) {
  12685. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12686. }
  12687. }
  12688. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12689. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12690. }
  12691. if (mesh._edgesRenderer) {
  12692. this._edgesRenderers.push(mesh._edgesRenderer);
  12693. }
  12694. if (mesh && mesh.subMeshes) {
  12695. // Submeshes Octrees
  12696. var len;
  12697. var subMeshes;
  12698. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12699. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12700. len = intersections.length;
  12701. subMeshes = intersections.data;
  12702. }
  12703. else {
  12704. subMeshes = mesh.subMeshes;
  12705. len = subMeshes.length;
  12706. }
  12707. for (var subIndex = 0; subIndex < len; subIndex++) {
  12708. var subMesh = subMeshes[subIndex];
  12709. this._evaluateSubMesh(subMesh, mesh);
  12710. }
  12711. }
  12712. };
  12713. Scene.prototype.updateTransformMatrix = function (force) {
  12714. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12715. };
  12716. Scene.prototype._renderForCamera = function (camera) {
  12717. var engine = this._engine;
  12718. this.activeCamera = camera;
  12719. if (!this.activeCamera)
  12720. throw new Error("Active camera not set");
  12721. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12722. // Viewport
  12723. engine.setViewport(this.activeCamera.viewport);
  12724. // Camera
  12725. this.resetCachedMaterial();
  12726. this._renderId++;
  12727. this.updateTransformMatrix();
  12728. if (this.beforeCameraRender) {
  12729. this.beforeCameraRender(this.activeCamera);
  12730. }
  12731. // Meshes
  12732. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12733. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12734. this._evaluateActiveMeshes();
  12735. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12736. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12737. // Skeletons
  12738. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12739. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12740. skeleton.prepare();
  12741. }
  12742. // Software skinning
  12743. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12744. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12745. mesh.applySkeleton(mesh.skeleton);
  12746. }
  12747. // Render targets
  12748. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12749. if (this.renderTargetsEnabled) {
  12750. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12751. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12752. var renderTarget = this._renderTargets.data[renderIndex];
  12753. if (renderTarget._shouldRender()) {
  12754. this._renderId++;
  12755. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12756. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12757. }
  12758. }
  12759. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12760. this._renderId++;
  12761. }
  12762. if (this._renderTargets.length > 0) {
  12763. engine.restoreDefaultFramebuffer();
  12764. }
  12765. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12766. // Prepare Frame
  12767. this.postProcessManager._prepareFrame();
  12768. var beforeRenderDate = BABYLON.Tools.Now;
  12769. // Backgrounds
  12770. var layerIndex;
  12771. var layer;
  12772. if (this.layers.length) {
  12773. engine.setDepthBuffer(false);
  12774. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12775. layer = this.layers[layerIndex];
  12776. if (layer.isBackground) {
  12777. layer.render();
  12778. }
  12779. }
  12780. engine.setDepthBuffer(true);
  12781. }
  12782. // Render
  12783. BABYLON.Tools.StartPerformanceCounter("Main render");
  12784. this._renderingManager.render(null, null, true, true);
  12785. BABYLON.Tools.EndPerformanceCounter("Main render");
  12786. // Bounding boxes
  12787. this._boundingBoxRenderer.render();
  12788. // Edges
  12789. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12790. this._edgesRenderers.data[edgesRendererIndex].render();
  12791. }
  12792. // Lens flares
  12793. if (this.lensFlaresEnabled) {
  12794. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12795. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12796. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12797. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12798. lensFlareSystem.render();
  12799. }
  12800. }
  12801. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12802. }
  12803. // Foregrounds
  12804. if (this.layers.length) {
  12805. engine.setDepthBuffer(false);
  12806. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12807. layer = this.layers[layerIndex];
  12808. if (!layer.isBackground) {
  12809. layer.render();
  12810. }
  12811. }
  12812. engine.setDepthBuffer(true);
  12813. }
  12814. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12815. // Finalize frame
  12816. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12817. // Update camera
  12818. this.activeCamera._updateFromScene();
  12819. // Reset some special arrays
  12820. this._renderTargets.reset();
  12821. if (this.afterCameraRender) {
  12822. this.afterCameraRender(this.activeCamera);
  12823. }
  12824. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12825. };
  12826. Scene.prototype._processSubCameras = function (camera) {
  12827. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12828. this._renderForCamera(camera);
  12829. return;
  12830. }
  12831. // rig cameras
  12832. for (var index = 0; index < camera._rigCameras.length; index++) {
  12833. this._renderForCamera(camera._rigCameras[index]);
  12834. }
  12835. this.activeCamera = camera;
  12836. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12837. // Update camera
  12838. this.activeCamera._updateFromScene();
  12839. };
  12840. Scene.prototype._checkIntersections = function () {
  12841. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12842. var sourceMesh = this._meshesForIntersections.data[index];
  12843. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12844. var action = sourceMesh.actionManager.actions[actionIndex];
  12845. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12846. var parameters = action.getTriggerParameter();
  12847. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12848. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12849. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12850. if (areIntersecting && currentIntersectionInProgress === -1) {
  12851. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12852. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12853. sourceMesh._intersectionsInProgress.push(otherMesh);
  12854. }
  12855. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12856. sourceMesh._intersectionsInProgress.push(otherMesh);
  12857. }
  12858. }
  12859. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12860. //They intersected, and now they don't.
  12861. //is this trigger an exit trigger? execute an event.
  12862. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12863. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12864. }
  12865. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12866. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12867. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12868. }
  12869. }
  12870. }
  12871. }
  12872. }
  12873. };
  12874. Scene.prototype.render = function () {
  12875. var startDate = BABYLON.Tools.Now;
  12876. this._particlesDuration = 0;
  12877. this._spritesDuration = 0;
  12878. this._activeParticles = 0;
  12879. this._renderDuration = 0;
  12880. this._renderTargetsDuration = 0;
  12881. this._evaluateActiveMeshesDuration = 0;
  12882. this._totalVertices = 0;
  12883. this._activeIndices = 0;
  12884. this._activeBones = 0;
  12885. this.getEngine().resetDrawCalls();
  12886. this._meshesForIntersections.reset();
  12887. this.resetCachedMaterial();
  12888. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12889. // Actions
  12890. if (this.actionManager) {
  12891. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12892. }
  12893. //Simplification Queue
  12894. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12895. this.simplificationQueue.executeNext();
  12896. }
  12897. // Animations
  12898. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12899. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12900. this._animate();
  12901. // Physics
  12902. if (this._physicsEngine) {
  12903. BABYLON.Tools.StartPerformanceCounter("Physics");
  12904. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12905. BABYLON.Tools.EndPerformanceCounter("Physics");
  12906. }
  12907. // Before render
  12908. if (this.beforeRender) {
  12909. this.beforeRender();
  12910. }
  12911. var callbackIndex;
  12912. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12913. this._onBeforeRenderCallbacks[callbackIndex]();
  12914. }
  12915. // Customs render targets
  12916. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12917. var engine = this.getEngine();
  12918. var currentActiveCamera = this.activeCamera;
  12919. if (this.renderTargetsEnabled) {
  12920. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12921. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12922. var renderTarget = this.customRenderTargets[customIndex];
  12923. if (renderTarget._shouldRender()) {
  12924. this._renderId++;
  12925. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12926. if (!this.activeCamera)
  12927. throw new Error("Active camera not set");
  12928. // Viewport
  12929. engine.setViewport(this.activeCamera.viewport);
  12930. // Camera
  12931. this.updateTransformMatrix();
  12932. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12933. }
  12934. }
  12935. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12936. this._renderId++;
  12937. }
  12938. if (this.customRenderTargets.length > 0) {
  12939. engine.restoreDefaultFramebuffer();
  12940. }
  12941. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12942. this.activeCamera = currentActiveCamera;
  12943. // Procedural textures
  12944. if (this.proceduralTexturesEnabled) {
  12945. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12946. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12947. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12948. if (proceduralTexture._shouldRender()) {
  12949. proceduralTexture.render();
  12950. }
  12951. }
  12952. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12953. }
  12954. // Clear
  12955. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12956. // Shadows
  12957. if (this.shadowsEnabled) {
  12958. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12959. var light = this.lights[lightIndex];
  12960. var shadowGenerator = light.getShadowGenerator();
  12961. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12962. this._renderTargets.push(shadowGenerator.getShadowMap());
  12963. }
  12964. }
  12965. }
  12966. // Depth renderer
  12967. if (this._depthRenderer) {
  12968. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12969. }
  12970. // RenderPipeline
  12971. this.postProcessRenderPipelineManager.update();
  12972. // Multi-cameras?
  12973. if (this.activeCameras.length > 0) {
  12974. var currentRenderId = this._renderId;
  12975. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12976. this._renderId = currentRenderId;
  12977. this._processSubCameras(this.activeCameras[cameraIndex]);
  12978. }
  12979. }
  12980. else {
  12981. if (!this.activeCamera) {
  12982. throw new Error("No camera defined");
  12983. }
  12984. this._processSubCameras(this.activeCamera);
  12985. }
  12986. // Intersection checks
  12987. this._checkIntersections();
  12988. // Update the audio listener attached to the camera
  12989. if (BABYLON.AudioEngine) {
  12990. this._updateAudioParameters();
  12991. }
  12992. // After render
  12993. if (this.afterRender) {
  12994. this.afterRender();
  12995. }
  12996. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12997. this._onAfterRenderCallbacks[callbackIndex]();
  12998. }
  12999. // Cleaning
  13000. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13001. this._toBeDisposed.data[index].dispose();
  13002. this._toBeDisposed[index] = null;
  13003. }
  13004. this._toBeDisposed.reset();
  13005. if (this.dumpNextRenderTargets) {
  13006. this.dumpNextRenderTargets = false;
  13007. }
  13008. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13009. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13010. };
  13011. Scene.prototype._updateAudioParameters = function () {
  13012. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13013. return;
  13014. }
  13015. var listeningCamera;
  13016. var audioEngine = BABYLON.Engine.audioEngine;
  13017. if (this.activeCameras.length > 0) {
  13018. listeningCamera = this.activeCameras[0];
  13019. }
  13020. else {
  13021. listeningCamera = this.activeCamera;
  13022. }
  13023. if (listeningCamera && audioEngine.canUseWebAudio) {
  13024. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13025. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13026. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13027. cameraDirection.normalize();
  13028. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13029. var i;
  13030. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13031. var sound = this.mainSoundTrack.soundCollection[i];
  13032. if (sound.useCustomAttenuation) {
  13033. sound.updateDistanceFromListener();
  13034. }
  13035. }
  13036. for (i = 0; i < this.soundTracks.length; i++) {
  13037. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13038. sound = this.soundTracks[i].soundCollection[j];
  13039. if (sound.useCustomAttenuation) {
  13040. sound.updateDistanceFromListener();
  13041. }
  13042. }
  13043. }
  13044. }
  13045. };
  13046. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13047. // Audio
  13048. get: function () {
  13049. return this._audioEnabled;
  13050. },
  13051. set: function (value) {
  13052. this._audioEnabled = value;
  13053. if (BABYLON.AudioEngine) {
  13054. if (this._audioEnabled) {
  13055. this._enableAudio();
  13056. }
  13057. else {
  13058. this._disableAudio();
  13059. }
  13060. }
  13061. },
  13062. enumerable: true,
  13063. configurable: true
  13064. });
  13065. Scene.prototype._disableAudio = function () {
  13066. var i;
  13067. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13068. this.mainSoundTrack.soundCollection[i].pause();
  13069. }
  13070. for (i = 0; i < this.soundTracks.length; i++) {
  13071. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13072. this.soundTracks[i].soundCollection[j].pause();
  13073. }
  13074. }
  13075. };
  13076. Scene.prototype._enableAudio = function () {
  13077. var i;
  13078. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13079. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13080. this.mainSoundTrack.soundCollection[i].play();
  13081. }
  13082. }
  13083. for (i = 0; i < this.soundTracks.length; i++) {
  13084. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13085. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13086. this.soundTracks[i].soundCollection[j].play();
  13087. }
  13088. }
  13089. }
  13090. };
  13091. Object.defineProperty(Scene.prototype, "headphone", {
  13092. get: function () {
  13093. return this._headphone;
  13094. },
  13095. set: function (value) {
  13096. this._headphone = value;
  13097. if (BABYLON.AudioEngine) {
  13098. if (this._headphone) {
  13099. this._switchAudioModeForHeadphones();
  13100. }
  13101. else {
  13102. this._switchAudioModeForNormalSpeakers();
  13103. }
  13104. }
  13105. },
  13106. enumerable: true,
  13107. configurable: true
  13108. });
  13109. Scene.prototype._switchAudioModeForHeadphones = function () {
  13110. this.mainSoundTrack.switchPanningModelToHRTF();
  13111. for (var i = 0; i < this.soundTracks.length; i++) {
  13112. this.soundTracks[i].switchPanningModelToHRTF();
  13113. }
  13114. };
  13115. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13116. this.mainSoundTrack.switchPanningModelToEqualPower();
  13117. for (var i = 0; i < this.soundTracks.length; i++) {
  13118. this.soundTracks[i].switchPanningModelToEqualPower();
  13119. }
  13120. };
  13121. Scene.prototype.enableDepthRenderer = function () {
  13122. if (this._depthRenderer) {
  13123. return this._depthRenderer;
  13124. }
  13125. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13126. return this._depthRenderer;
  13127. };
  13128. Scene.prototype.disableDepthRenderer = function () {
  13129. if (!this._depthRenderer) {
  13130. return;
  13131. }
  13132. this._depthRenderer.dispose();
  13133. this._depthRenderer = null;
  13134. };
  13135. Scene.prototype.dispose = function () {
  13136. this.beforeRender = null;
  13137. this.afterRender = null;
  13138. this.skeletons = [];
  13139. this._boundingBoxRenderer.dispose();
  13140. if (this._depthRenderer) {
  13141. this._depthRenderer.dispose();
  13142. }
  13143. // Debug layer
  13144. this.debugLayer.hide();
  13145. // Events
  13146. if (this.onDispose) {
  13147. this.onDispose();
  13148. }
  13149. this._onBeforeRenderCallbacks = [];
  13150. this._onAfterRenderCallbacks = [];
  13151. this.detachControl();
  13152. // Release sounds & sounds tracks
  13153. if (BABYLON.AudioEngine) {
  13154. this.disposeSounds();
  13155. }
  13156. // Detach cameras
  13157. var canvas = this._engine.getRenderingCanvas();
  13158. var index;
  13159. for (index = 0; index < this.cameras.length; index++) {
  13160. this.cameras[index].detachControl(canvas);
  13161. }
  13162. // Release lights
  13163. while (this.lights.length) {
  13164. this.lights[0].dispose();
  13165. }
  13166. // Release meshes
  13167. while (this.meshes.length) {
  13168. this.meshes[0].dispose(true);
  13169. }
  13170. // Release cameras
  13171. while (this.cameras.length) {
  13172. this.cameras[0].dispose();
  13173. }
  13174. // Release materials
  13175. while (this.materials.length) {
  13176. this.materials[0].dispose();
  13177. }
  13178. // Release particles
  13179. while (this.particleSystems.length) {
  13180. this.particleSystems[0].dispose();
  13181. }
  13182. // Release sprites
  13183. while (this.spriteManagers.length) {
  13184. this.spriteManagers[0].dispose();
  13185. }
  13186. // Release layers
  13187. while (this.layers.length) {
  13188. this.layers[0].dispose();
  13189. }
  13190. // Release textures
  13191. while (this.textures.length) {
  13192. this.textures[0].dispose();
  13193. }
  13194. // Post-processes
  13195. this.postProcessManager.dispose();
  13196. // Physics
  13197. if (this._physicsEngine) {
  13198. this.disablePhysicsEngine();
  13199. }
  13200. // Remove from engine
  13201. index = this._engine.scenes.indexOf(this);
  13202. if (index > -1) {
  13203. this._engine.scenes.splice(index, 1);
  13204. }
  13205. this._engine.wipeCaches();
  13206. };
  13207. // Release sounds & sounds tracks
  13208. Scene.prototype.disposeSounds = function () {
  13209. this.mainSoundTrack.dispose();
  13210. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13211. this.soundTracks[scIndex].dispose();
  13212. }
  13213. };
  13214. // Octrees
  13215. Scene.prototype.getWorldExtends = function () {
  13216. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13217. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13218. for (var index = 0; index < this.meshes.length; index++) {
  13219. var mesh = this.meshes[index];
  13220. mesh.computeWorldMatrix(true);
  13221. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13222. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13223. BABYLON.Tools.CheckExtends(minBox, min, max);
  13224. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13225. }
  13226. return {
  13227. min: min,
  13228. max: max
  13229. };
  13230. };
  13231. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13232. if (maxCapacity === void 0) { maxCapacity = 64; }
  13233. if (maxDepth === void 0) { maxDepth = 2; }
  13234. if (!this._selectionOctree) {
  13235. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13236. }
  13237. var worldExtends = this.getWorldExtends();
  13238. // Update octree
  13239. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13240. return this._selectionOctree;
  13241. };
  13242. // Picking
  13243. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13244. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13245. var engine = this._engine;
  13246. if (!camera) {
  13247. if (!this.activeCamera)
  13248. throw new Error("Active camera not set");
  13249. camera = this.activeCamera;
  13250. }
  13251. var cameraViewport = camera.viewport;
  13252. var viewport = cameraViewport.toGlobal(engine);
  13253. // Moving coordinates to local viewport world
  13254. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13255. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13256. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13257. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13258. };
  13259. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13260. var engine = this._engine;
  13261. if (!camera) {
  13262. if (!this.activeCamera)
  13263. throw new Error("Active camera not set");
  13264. camera = this.activeCamera;
  13265. }
  13266. var cameraViewport = camera.viewport;
  13267. var viewport = cameraViewport.toGlobal(engine);
  13268. var identity = BABYLON.Matrix.Identity();
  13269. // Moving coordinates to local viewport world
  13270. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13271. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13272. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13273. };
  13274. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13275. var pickingInfo = null;
  13276. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13277. var mesh = this.meshes[meshIndex];
  13278. if (predicate) {
  13279. if (!predicate(mesh)) {
  13280. continue;
  13281. }
  13282. }
  13283. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13284. continue;
  13285. }
  13286. var world = mesh.getWorldMatrix();
  13287. var ray = rayFunction(world);
  13288. var result = mesh.intersects(ray, fastCheck);
  13289. if (!result || !result.hit)
  13290. continue;
  13291. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13292. continue;
  13293. pickingInfo = result;
  13294. if (fastCheck) {
  13295. break;
  13296. }
  13297. }
  13298. return pickingInfo || new BABYLON.PickingInfo();
  13299. };
  13300. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13301. var pickingInfo = null;
  13302. camera = camera || this.activeCamera;
  13303. if (this.spriteManagers.length > 0) {
  13304. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13305. var spriteManager = this.spriteManagers[spriteIndex];
  13306. if (!spriteManager.isPickable) {
  13307. continue;
  13308. }
  13309. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13310. if (!result || !result.hit)
  13311. continue;
  13312. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13313. continue;
  13314. pickingInfo = result;
  13315. if (fastCheck) {
  13316. break;
  13317. }
  13318. }
  13319. }
  13320. return pickingInfo || new BABYLON.PickingInfo();
  13321. };
  13322. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13323. var _this = this;
  13324. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13325. /// <param name="x">X position on screen</param>
  13326. /// <param name="y">Y position on screen</param>
  13327. /// <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>
  13328. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13329. /// <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>
  13330. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13331. };
  13332. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13333. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13334. /// <param name="x">X position on screen</param>
  13335. /// <param name="y">Y position on screen</param>
  13336. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  13337. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13338. /// <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>
  13339. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13340. };
  13341. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13342. var _this = this;
  13343. return this._internalPick(function (world) {
  13344. if (!_this._pickWithRayInverseMatrix) {
  13345. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13346. }
  13347. world.invertToRef(_this._pickWithRayInverseMatrix);
  13348. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13349. }, predicate, fastCheck);
  13350. };
  13351. Scene.prototype.setPointerOverMesh = function (mesh) {
  13352. if (this._pointerOverMesh === mesh) {
  13353. return;
  13354. }
  13355. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13356. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13357. }
  13358. this._pointerOverMesh = mesh;
  13359. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13360. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13361. }
  13362. };
  13363. Scene.prototype.getPointerOverMesh = function () {
  13364. return this._pointerOverMesh;
  13365. };
  13366. // Physics
  13367. Scene.prototype.getPhysicsEngine = function () {
  13368. return this._physicsEngine;
  13369. };
  13370. /**
  13371. * Enables physics to the current scene
  13372. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13373. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13374. * @return {boolean} was the physics engine initialized
  13375. */
  13376. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13377. if (this._physicsEngine) {
  13378. return true;
  13379. }
  13380. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13381. if (!this._physicsEngine.isSupported()) {
  13382. this._physicsEngine = null;
  13383. return false;
  13384. }
  13385. this._physicsEngine._initialize(gravity);
  13386. return true;
  13387. };
  13388. Scene.prototype.disablePhysicsEngine = function () {
  13389. if (!this._physicsEngine) {
  13390. return;
  13391. }
  13392. this._physicsEngine.dispose();
  13393. this._physicsEngine = undefined;
  13394. };
  13395. Scene.prototype.isPhysicsEnabled = function () {
  13396. return this._physicsEngine !== undefined;
  13397. };
  13398. /**
  13399. * Sets the gravity of the physics engine (and NOT of the scene)
  13400. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13401. */
  13402. Scene.prototype.setGravity = function (gravity) {
  13403. if (!this._physicsEngine) {
  13404. return;
  13405. }
  13406. this._physicsEngine._setGravity(gravity);
  13407. };
  13408. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13409. if (parts.parts) {
  13410. options = parts;
  13411. parts = parts.parts;
  13412. }
  13413. if (!this._physicsEngine) {
  13414. return null;
  13415. }
  13416. for (var index = 0; index < parts.length; index++) {
  13417. var mesh = parts[index].mesh;
  13418. mesh._physicImpostor = parts[index].impostor;
  13419. mesh._physicsMass = options.mass / parts.length;
  13420. mesh._physicsFriction = options.friction;
  13421. mesh._physicRestitution = options.restitution;
  13422. }
  13423. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13424. };
  13425. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13426. for (var index = 0; index < compound.parts.length; index++) {
  13427. var mesh = compound.parts[index].mesh;
  13428. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13429. this._physicsEngine._unregisterMesh(mesh);
  13430. }
  13431. };
  13432. // Misc.
  13433. Scene.prototype.createDefaultCameraOrLight = function () {
  13434. // Light
  13435. if (this.lights.length === 0) {
  13436. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13437. }
  13438. // Camera
  13439. if (!this.activeCamera) {
  13440. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13441. // Compute position
  13442. var worldExtends = this.getWorldExtends();
  13443. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13444. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13445. camera.setTarget(worldCenter);
  13446. this.activeCamera = camera;
  13447. }
  13448. };
  13449. // Tags
  13450. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13451. if (tagsQuery === undefined) {
  13452. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13453. return list;
  13454. }
  13455. var listByTags = [];
  13456. forEach = forEach || (function (item) { return; });
  13457. for (var i in list) {
  13458. var item = list[i];
  13459. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13460. listByTags.push(item);
  13461. forEach(item);
  13462. }
  13463. }
  13464. return listByTags;
  13465. };
  13466. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13467. return this._getByTags(this.meshes, tagsQuery, forEach);
  13468. };
  13469. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13470. return this._getByTags(this.cameras, tagsQuery, forEach);
  13471. };
  13472. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13473. return this._getByTags(this.lights, tagsQuery, forEach);
  13474. };
  13475. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13476. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13477. };
  13478. // Statics
  13479. Scene._FOGMODE_NONE = 0;
  13480. Scene._FOGMODE_EXP = 1;
  13481. Scene._FOGMODE_EXP2 = 2;
  13482. Scene._FOGMODE_LINEAR = 3;
  13483. Scene.MinDeltaTime = 1.0;
  13484. Scene.MaxDeltaTime = 1000.0;
  13485. return Scene;
  13486. })();
  13487. BABYLON.Scene = Scene;
  13488. })(BABYLON || (BABYLON = {}));
  13489. var BABYLON;
  13490. (function (BABYLON) {
  13491. var VertexBuffer = (function () {
  13492. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13493. if (engine instanceof BABYLON.Mesh) {
  13494. this._engine = engine.getScene().getEngine();
  13495. }
  13496. else {
  13497. this._engine = engine;
  13498. }
  13499. this._updatable = updatable;
  13500. this._data = data;
  13501. if (!postponeInternalCreation) {
  13502. this.create();
  13503. }
  13504. this._kind = kind;
  13505. if (stride) {
  13506. this._strideSize = stride;
  13507. return;
  13508. }
  13509. // Deduce stride from kind
  13510. switch (kind) {
  13511. case VertexBuffer.PositionKind:
  13512. this._strideSize = 3;
  13513. break;
  13514. case VertexBuffer.NormalKind:
  13515. this._strideSize = 3;
  13516. break;
  13517. case VertexBuffer.UVKind:
  13518. case VertexBuffer.UV2Kind:
  13519. case VertexBuffer.UV3Kind:
  13520. case VertexBuffer.UV4Kind:
  13521. case VertexBuffer.UV5Kind:
  13522. case VertexBuffer.UV6Kind:
  13523. this._strideSize = 2;
  13524. break;
  13525. case VertexBuffer.ColorKind:
  13526. this._strideSize = 4;
  13527. break;
  13528. case VertexBuffer.MatricesIndicesKind:
  13529. case VertexBuffer.MatricesIndicesExtraKind:
  13530. this._strideSize = 4;
  13531. break;
  13532. case VertexBuffer.MatricesWeightsKind:
  13533. case VertexBuffer.MatricesWeightsExtraKind:
  13534. this._strideSize = 4;
  13535. break;
  13536. }
  13537. }
  13538. // Properties
  13539. VertexBuffer.prototype.isUpdatable = function () {
  13540. return this._updatable;
  13541. };
  13542. VertexBuffer.prototype.getData = function () {
  13543. return this._data;
  13544. };
  13545. VertexBuffer.prototype.getBuffer = function () {
  13546. return this._buffer;
  13547. };
  13548. VertexBuffer.prototype.getStrideSize = function () {
  13549. return this._strideSize;
  13550. };
  13551. // Methods
  13552. VertexBuffer.prototype.create = function (data) {
  13553. if (!data && this._buffer) {
  13554. return; // nothing to do
  13555. }
  13556. data = data || this._data;
  13557. if (!this._buffer) {
  13558. if (this._updatable) {
  13559. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13560. }
  13561. else {
  13562. this._buffer = this._engine.createVertexBuffer(data);
  13563. }
  13564. }
  13565. if (this._updatable) {
  13566. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13567. this._data = data;
  13568. }
  13569. };
  13570. VertexBuffer.prototype.update = function (data) {
  13571. this.create(data);
  13572. };
  13573. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13574. if (!this._buffer) {
  13575. return;
  13576. }
  13577. if (this._updatable) {
  13578. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13579. this._data = null;
  13580. }
  13581. };
  13582. VertexBuffer.prototype.dispose = function () {
  13583. if (!this._buffer) {
  13584. return;
  13585. }
  13586. if (this._engine._releaseBuffer(this._buffer)) {
  13587. this._buffer = null;
  13588. }
  13589. };
  13590. Object.defineProperty(VertexBuffer, "PositionKind", {
  13591. get: function () {
  13592. return VertexBuffer._PositionKind;
  13593. },
  13594. enumerable: true,
  13595. configurable: true
  13596. });
  13597. Object.defineProperty(VertexBuffer, "NormalKind", {
  13598. get: function () {
  13599. return VertexBuffer._NormalKind;
  13600. },
  13601. enumerable: true,
  13602. configurable: true
  13603. });
  13604. Object.defineProperty(VertexBuffer, "UVKind", {
  13605. get: function () {
  13606. return VertexBuffer._UVKind;
  13607. },
  13608. enumerable: true,
  13609. configurable: true
  13610. });
  13611. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13612. get: function () {
  13613. return VertexBuffer._UV2Kind;
  13614. },
  13615. enumerable: true,
  13616. configurable: true
  13617. });
  13618. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13619. get: function () {
  13620. return VertexBuffer._UV3Kind;
  13621. },
  13622. enumerable: true,
  13623. configurable: true
  13624. });
  13625. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13626. get: function () {
  13627. return VertexBuffer._UV4Kind;
  13628. },
  13629. enumerable: true,
  13630. configurable: true
  13631. });
  13632. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13633. get: function () {
  13634. return VertexBuffer._UV5Kind;
  13635. },
  13636. enumerable: true,
  13637. configurable: true
  13638. });
  13639. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13640. get: function () {
  13641. return VertexBuffer._UV6Kind;
  13642. },
  13643. enumerable: true,
  13644. configurable: true
  13645. });
  13646. Object.defineProperty(VertexBuffer, "ColorKind", {
  13647. get: function () {
  13648. return VertexBuffer._ColorKind;
  13649. },
  13650. enumerable: true,
  13651. configurable: true
  13652. });
  13653. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13654. get: function () {
  13655. return VertexBuffer._MatricesIndicesKind;
  13656. },
  13657. enumerable: true,
  13658. configurable: true
  13659. });
  13660. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13661. get: function () {
  13662. return VertexBuffer._MatricesWeightsKind;
  13663. },
  13664. enumerable: true,
  13665. configurable: true
  13666. });
  13667. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  13668. get: function () {
  13669. return VertexBuffer._MatricesIndicesExtraKind;
  13670. },
  13671. enumerable: true,
  13672. configurable: true
  13673. });
  13674. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  13675. get: function () {
  13676. return VertexBuffer._MatricesWeightsExtraKind;
  13677. },
  13678. enumerable: true,
  13679. configurable: true
  13680. });
  13681. // Enums
  13682. VertexBuffer._PositionKind = "position";
  13683. VertexBuffer._NormalKind = "normal";
  13684. VertexBuffer._UVKind = "uv";
  13685. VertexBuffer._UV2Kind = "uv2";
  13686. VertexBuffer._UV3Kind = "uv3";
  13687. VertexBuffer._UV4Kind = "uv4";
  13688. VertexBuffer._UV5Kind = "uv5";
  13689. VertexBuffer._UV6Kind = "uv6";
  13690. VertexBuffer._ColorKind = "color";
  13691. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13692. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13693. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  13694. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  13695. return VertexBuffer;
  13696. })();
  13697. BABYLON.VertexBuffer = VertexBuffer;
  13698. })(BABYLON || (BABYLON = {}));
  13699. var BABYLON;
  13700. (function (BABYLON) {
  13701. /**
  13702. * Creates an instance based on a source mesh.
  13703. */
  13704. var InstancedMesh = (function (_super) {
  13705. __extends(InstancedMesh, _super);
  13706. function InstancedMesh(name, source) {
  13707. _super.call(this, name, source.getScene());
  13708. source.instances.push(this);
  13709. this._sourceMesh = source;
  13710. this.position.copyFrom(source.position);
  13711. this.rotation.copyFrom(source.rotation);
  13712. this.scaling.copyFrom(source.scaling);
  13713. if (source.rotationQuaternion) {
  13714. this.rotationQuaternion = source.rotationQuaternion.clone();
  13715. }
  13716. this.infiniteDistance = source.infiniteDistance;
  13717. this.setPivotMatrix(source.getPivotMatrix());
  13718. this.refreshBoundingInfo();
  13719. this._syncSubMeshes();
  13720. }
  13721. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13722. // Methods
  13723. get: function () {
  13724. return this._sourceMesh.receiveShadows;
  13725. },
  13726. enumerable: true,
  13727. configurable: true
  13728. });
  13729. Object.defineProperty(InstancedMesh.prototype, "material", {
  13730. get: function () {
  13731. return this._sourceMesh.material;
  13732. },
  13733. enumerable: true,
  13734. configurable: true
  13735. });
  13736. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13737. get: function () {
  13738. return this._sourceMesh.visibility;
  13739. },
  13740. enumerable: true,
  13741. configurable: true
  13742. });
  13743. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13744. get: function () {
  13745. return this._sourceMesh.skeleton;
  13746. },
  13747. enumerable: true,
  13748. configurable: true
  13749. });
  13750. InstancedMesh.prototype.getTotalVertices = function () {
  13751. return this._sourceMesh.getTotalVertices();
  13752. };
  13753. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13754. get: function () {
  13755. return this._sourceMesh;
  13756. },
  13757. enumerable: true,
  13758. configurable: true
  13759. });
  13760. InstancedMesh.prototype.getVerticesData = function (kind) {
  13761. return this._sourceMesh.getVerticesData(kind);
  13762. };
  13763. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13764. return this._sourceMesh.isVerticesDataPresent(kind);
  13765. };
  13766. InstancedMesh.prototype.getIndices = function () {
  13767. return this._sourceMesh.getIndices();
  13768. };
  13769. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13770. get: function () {
  13771. return this._sourceMesh._positions;
  13772. },
  13773. enumerable: true,
  13774. configurable: true
  13775. });
  13776. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13777. var meshBB = this._sourceMesh.getBoundingInfo();
  13778. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13779. this._updateBoundingInfo();
  13780. };
  13781. InstancedMesh.prototype._preActivate = function () {
  13782. if (this._currentLOD) {
  13783. this._currentLOD._preActivate();
  13784. }
  13785. };
  13786. InstancedMesh.prototype._activate = function (renderId) {
  13787. if (this._currentLOD) {
  13788. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13789. }
  13790. };
  13791. InstancedMesh.prototype.getLOD = function (camera) {
  13792. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13793. if (this._currentLOD === this.sourceMesh) {
  13794. return this;
  13795. }
  13796. return this._currentLOD;
  13797. };
  13798. InstancedMesh.prototype._syncSubMeshes = function () {
  13799. this.releaseSubMeshes();
  13800. if (this._sourceMesh.subMeshes) {
  13801. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13802. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13803. }
  13804. }
  13805. };
  13806. InstancedMesh.prototype._generatePointsArray = function () {
  13807. return this._sourceMesh._generatePointsArray();
  13808. };
  13809. // Clone
  13810. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13811. var result = this._sourceMesh.createInstance(name);
  13812. // Deep copy
  13813. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13814. // Bounding info
  13815. this.refreshBoundingInfo();
  13816. // Parent
  13817. if (newParent) {
  13818. result.parent = newParent;
  13819. }
  13820. if (!doNotCloneChildren) {
  13821. // Children
  13822. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13823. var mesh = this.getScene().meshes[index];
  13824. if (mesh.parent === this) {
  13825. mesh.clone(mesh.name, result);
  13826. }
  13827. }
  13828. }
  13829. result.computeWorldMatrix(true);
  13830. return result;
  13831. };
  13832. // Dispoe
  13833. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13834. // Remove from mesh
  13835. var index = this._sourceMesh.instances.indexOf(this);
  13836. this._sourceMesh.instances.splice(index, 1);
  13837. _super.prototype.dispose.call(this, doNotRecurse);
  13838. };
  13839. return InstancedMesh;
  13840. })(BABYLON.AbstractMesh);
  13841. BABYLON.InstancedMesh = InstancedMesh;
  13842. })(BABYLON || (BABYLON = {}));
  13843. var BABYLON;
  13844. (function (BABYLON) {
  13845. var _InstancesBatch = (function () {
  13846. function _InstancesBatch() {
  13847. this.mustReturn = false;
  13848. this.visibleInstances = new Array();
  13849. this.renderSelf = new Array();
  13850. }
  13851. return _InstancesBatch;
  13852. })();
  13853. BABYLON._InstancesBatch = _InstancesBatch;
  13854. var Mesh = (function (_super) {
  13855. __extends(Mesh, _super);
  13856. /**
  13857. * @constructor
  13858. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13859. * @param {Scene} scene - The scene to add this mesh to.
  13860. * @param {Node} parent - The parent of this mesh, if it has one
  13861. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13862. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13863. * When false, achieved by calling a clone(), also passing False.
  13864. * This will make creation of children, recursive.
  13865. */
  13866. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13867. if (parent === void 0) { parent = null; }
  13868. _super.call(this, name, scene);
  13869. // Members
  13870. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13871. this.instances = new Array();
  13872. this._LODLevels = new Array();
  13873. this._onBeforeRenderCallbacks = new Array();
  13874. this._onAfterRenderCallbacks = new Array();
  13875. this._visibleInstances = {};
  13876. this._renderIdForInstances = new Array();
  13877. this._batchCache = new _InstancesBatch();
  13878. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13879. this._sideOrientation = Mesh._DEFAULTSIDE;
  13880. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13881. if (source) {
  13882. // Geometry
  13883. if (source._geometry) {
  13884. source._geometry.applyToMesh(this);
  13885. }
  13886. // Deep copy
  13887. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13888. this.id = name + "." + source.id;
  13889. // Material
  13890. this.material = source.material;
  13891. var index;
  13892. if (!doNotCloneChildren) {
  13893. // Children
  13894. for (index = 0; index < scene.meshes.length; index++) {
  13895. var mesh = scene.meshes[index];
  13896. if (mesh.parent === source) {
  13897. // doNotCloneChildren is always going to be False
  13898. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13899. }
  13900. }
  13901. }
  13902. // Particles
  13903. for (index = 0; index < scene.particleSystems.length; index++) {
  13904. var system = scene.particleSystems[index];
  13905. if (system.emitter === source) {
  13906. system.clone(system.name, this);
  13907. }
  13908. }
  13909. this.computeWorldMatrix(true);
  13910. }
  13911. // Parent
  13912. if (parent !== null) {
  13913. this.parent = parent;
  13914. }
  13915. }
  13916. Object.defineProperty(Mesh, "FRONTSIDE", {
  13917. get: function () {
  13918. return Mesh._FRONTSIDE;
  13919. },
  13920. enumerable: true,
  13921. configurable: true
  13922. });
  13923. Object.defineProperty(Mesh, "BACKSIDE", {
  13924. get: function () {
  13925. return Mesh._BACKSIDE;
  13926. },
  13927. enumerable: true,
  13928. configurable: true
  13929. });
  13930. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13931. get: function () {
  13932. return Mesh._DOUBLESIDE;
  13933. },
  13934. enumerable: true,
  13935. configurable: true
  13936. });
  13937. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13938. get: function () {
  13939. return Mesh._DEFAULTSIDE;
  13940. },
  13941. enumerable: true,
  13942. configurable: true
  13943. });
  13944. Object.defineProperty(Mesh, "NO_CAP", {
  13945. get: function () {
  13946. return Mesh._NO_CAP;
  13947. },
  13948. enumerable: true,
  13949. configurable: true
  13950. });
  13951. Object.defineProperty(Mesh, "CAP_START", {
  13952. get: function () {
  13953. return Mesh._CAP_START;
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. Object.defineProperty(Mesh, "CAP_END", {
  13959. get: function () {
  13960. return Mesh._CAP_END;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. Object.defineProperty(Mesh, "CAP_ALL", {
  13966. get: function () {
  13967. return Mesh._CAP_ALL;
  13968. },
  13969. enumerable: true,
  13970. configurable: true
  13971. });
  13972. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13973. // Methods
  13974. get: function () {
  13975. return this._LODLevels.length > 0;
  13976. },
  13977. enumerable: true,
  13978. configurable: true
  13979. });
  13980. Mesh.prototype._sortLODLevels = function () {
  13981. this._LODLevels.sort(function (a, b) {
  13982. if (a.distance < b.distance) {
  13983. return 1;
  13984. }
  13985. if (a.distance > b.distance) {
  13986. return -1;
  13987. }
  13988. return 0;
  13989. });
  13990. };
  13991. /**
  13992. * Add a mesh as LOD level triggered at the given distance.
  13993. * @param {number} distance - the distance from the center of the object to show this level
  13994. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13995. * @return {BABYLON.Mesh} this mesh (for chaining)
  13996. */
  13997. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13998. if (mesh && mesh._masterMesh) {
  13999. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14000. return this;
  14001. }
  14002. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14003. this._LODLevels.push(level);
  14004. if (mesh) {
  14005. mesh._masterMesh = this;
  14006. }
  14007. this._sortLODLevels();
  14008. return this;
  14009. };
  14010. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14011. for (var index = 0; index < this._LODLevels.length; index++) {
  14012. var level = this._LODLevels[index];
  14013. if (level.distance === distance) {
  14014. return level.mesh;
  14015. }
  14016. }
  14017. return null;
  14018. };
  14019. /**
  14020. * Remove a mesh from the LOD array
  14021. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14022. * @return {BABYLON.Mesh} this mesh (for chaining)
  14023. */
  14024. Mesh.prototype.removeLODLevel = function (mesh) {
  14025. for (var index = 0; index < this._LODLevels.length; index++) {
  14026. if (this._LODLevels[index].mesh === mesh) {
  14027. this._LODLevels.splice(index, 1);
  14028. if (mesh) {
  14029. mesh._masterMesh = null;
  14030. }
  14031. }
  14032. }
  14033. this._sortLODLevels();
  14034. return this;
  14035. };
  14036. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14037. if (!this._LODLevels || this._LODLevels.length === 0) {
  14038. return this;
  14039. }
  14040. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14041. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14042. if (this.onLODLevelSelection) {
  14043. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14044. }
  14045. return this;
  14046. }
  14047. for (var index = 0; index < this._LODLevels.length; index++) {
  14048. var level = this._LODLevels[index];
  14049. if (level.distance < distanceToCamera) {
  14050. if (level.mesh) {
  14051. level.mesh._preActivate();
  14052. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14053. }
  14054. if (this.onLODLevelSelection) {
  14055. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14056. }
  14057. return level.mesh;
  14058. }
  14059. }
  14060. if (this.onLODLevelSelection) {
  14061. this.onLODLevelSelection(distanceToCamera, this, this);
  14062. }
  14063. return this;
  14064. };
  14065. Object.defineProperty(Mesh.prototype, "geometry", {
  14066. get: function () {
  14067. return this._geometry;
  14068. },
  14069. enumerable: true,
  14070. configurable: true
  14071. });
  14072. Mesh.prototype.getTotalVertices = function () {
  14073. if (!this._geometry) {
  14074. return 0;
  14075. }
  14076. return this._geometry.getTotalVertices();
  14077. };
  14078. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14079. if (!this._geometry) {
  14080. return null;
  14081. }
  14082. return this._geometry.getVerticesData(kind, copyWhenShared);
  14083. };
  14084. Mesh.prototype.getVertexBuffer = function (kind) {
  14085. if (!this._geometry) {
  14086. return undefined;
  14087. }
  14088. return this._geometry.getVertexBuffer(kind);
  14089. };
  14090. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14091. if (!this._geometry) {
  14092. if (this._delayInfo) {
  14093. return this._delayInfo.indexOf(kind) !== -1;
  14094. }
  14095. return false;
  14096. }
  14097. return this._geometry.isVerticesDataPresent(kind);
  14098. };
  14099. Mesh.prototype.getVerticesDataKinds = function () {
  14100. if (!this._geometry) {
  14101. var result = [];
  14102. if (this._delayInfo) {
  14103. for (var kind in this._delayInfo) {
  14104. result.push(kind);
  14105. }
  14106. }
  14107. return result;
  14108. }
  14109. return this._geometry.getVerticesDataKinds();
  14110. };
  14111. Mesh.prototype.getTotalIndices = function () {
  14112. if (!this._geometry) {
  14113. return 0;
  14114. }
  14115. return this._geometry.getTotalIndices();
  14116. };
  14117. Mesh.prototype.getIndices = function (copyWhenShared) {
  14118. if (!this._geometry) {
  14119. return [];
  14120. }
  14121. return this._geometry.getIndices(copyWhenShared);
  14122. };
  14123. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14124. get: function () {
  14125. return this._masterMesh !== null && this._masterMesh !== undefined;
  14126. },
  14127. enumerable: true,
  14128. configurable: true
  14129. });
  14130. Mesh.prototype.isReady = function () {
  14131. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14132. return false;
  14133. }
  14134. return _super.prototype.isReady.call(this);
  14135. };
  14136. Mesh.prototype.isDisposed = function () {
  14137. return this._isDisposed;
  14138. };
  14139. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14140. get: function () {
  14141. return this._sideOrientation;
  14142. },
  14143. set: function (sideO) {
  14144. this._sideOrientation = sideO;
  14145. },
  14146. enumerable: true,
  14147. configurable: true
  14148. });
  14149. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14150. get: function () {
  14151. return this._areNormalsFrozen;
  14152. },
  14153. enumerable: true,
  14154. configurable: true
  14155. });
  14156. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14157. Mesh.prototype.freezeNormals = function () {
  14158. this._areNormalsFrozen = true;
  14159. };
  14160. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14161. Mesh.prototype.unfreezeNormals = function () {
  14162. this._areNormalsFrozen = false;
  14163. };
  14164. // Methods
  14165. Mesh.prototype._preActivate = function () {
  14166. var sceneRenderId = this.getScene().getRenderId();
  14167. if (this._preActivateId === sceneRenderId) {
  14168. return;
  14169. }
  14170. this._preActivateId = sceneRenderId;
  14171. this._visibleInstances = null;
  14172. };
  14173. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14174. if (!this._visibleInstances) {
  14175. this._visibleInstances = {};
  14176. this._visibleInstances.defaultRenderId = renderId;
  14177. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14178. }
  14179. if (!this._visibleInstances[renderId]) {
  14180. this._visibleInstances[renderId] = new Array();
  14181. }
  14182. this._visibleInstances[renderId].push(instance);
  14183. };
  14184. Mesh.prototype.refreshBoundingInfo = function () {
  14185. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14186. if (data) {
  14187. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14188. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14189. }
  14190. if (this.subMeshes) {
  14191. for (var index = 0; index < this.subMeshes.length; index++) {
  14192. this.subMeshes[index].refreshBoundingInfo();
  14193. }
  14194. }
  14195. this._updateBoundingInfo();
  14196. };
  14197. Mesh.prototype._createGlobalSubMesh = function () {
  14198. var totalVertices = this.getTotalVertices();
  14199. if (!totalVertices || !this.getIndices()) {
  14200. return null;
  14201. }
  14202. this.releaseSubMeshes();
  14203. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14204. };
  14205. Mesh.prototype.subdivide = function (count) {
  14206. if (count < 1) {
  14207. return;
  14208. }
  14209. var totalIndices = this.getTotalIndices();
  14210. var subdivisionSize = (totalIndices / count) | 0;
  14211. var offset = 0;
  14212. // Ensure that subdivisionSize is a multiple of 3
  14213. while (subdivisionSize % 3 !== 0) {
  14214. subdivisionSize++;
  14215. }
  14216. this.releaseSubMeshes();
  14217. for (var index = 0; index < count; index++) {
  14218. if (offset >= totalIndices) {
  14219. break;
  14220. }
  14221. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14222. offset += subdivisionSize;
  14223. }
  14224. this.synchronizeInstances();
  14225. };
  14226. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14227. if (!this._geometry) {
  14228. var vertexData = new BABYLON.VertexData();
  14229. vertexData.set(data, kind);
  14230. var scene = this.getScene();
  14231. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14232. }
  14233. else {
  14234. this._geometry.setVerticesData(kind, data, updatable, stride);
  14235. }
  14236. };
  14237. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14238. if (!this._geometry) {
  14239. return;
  14240. }
  14241. if (!makeItUnique) {
  14242. this._geometry.updateVerticesData(kind, data, updateExtends);
  14243. }
  14244. else {
  14245. this.makeGeometryUnique();
  14246. this.updateVerticesData(kind, data, updateExtends, false);
  14247. }
  14248. };
  14249. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14250. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14251. if (!this._geometry) {
  14252. return;
  14253. }
  14254. if (!makeItUnique) {
  14255. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14256. }
  14257. else {
  14258. this.makeGeometryUnique();
  14259. this.updateVerticesDataDirectly(kind, data, offset, false);
  14260. }
  14261. };
  14262. // Mesh positions update function :
  14263. // updates the mesh positions according to the positionFunction returned values.
  14264. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14265. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14266. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14267. if (computeNormals === void 0) { computeNormals = true; }
  14268. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14269. positionFunction(positions);
  14270. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14271. if (computeNormals) {
  14272. var indices = this.getIndices();
  14273. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14274. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14275. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14276. }
  14277. };
  14278. Mesh.prototype.makeGeometryUnique = function () {
  14279. if (!this._geometry) {
  14280. return;
  14281. }
  14282. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14283. geometry.applyToMesh(this);
  14284. };
  14285. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14286. if (!this._geometry) {
  14287. var vertexData = new BABYLON.VertexData();
  14288. vertexData.indices = indices;
  14289. var scene = this.getScene();
  14290. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14291. }
  14292. else {
  14293. this._geometry.setIndices(indices, totalVertices);
  14294. }
  14295. };
  14296. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14297. var engine = this.getScene().getEngine();
  14298. // Wireframe
  14299. var indexToBind;
  14300. switch (fillMode) {
  14301. case BABYLON.Material.PointFillMode:
  14302. indexToBind = null;
  14303. break;
  14304. case BABYLON.Material.WireFrameFillMode:
  14305. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14306. break;
  14307. default:
  14308. case BABYLON.Material.TriangleFillMode:
  14309. indexToBind = this._geometry.getIndexBuffer();
  14310. break;
  14311. }
  14312. // VBOs
  14313. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14314. };
  14315. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14316. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14317. return;
  14318. }
  14319. var engine = this.getScene().getEngine();
  14320. // Draw order
  14321. switch (fillMode) {
  14322. case BABYLON.Material.PointFillMode:
  14323. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14324. break;
  14325. case BABYLON.Material.WireFrameFillMode:
  14326. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14327. break;
  14328. default:
  14329. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14330. }
  14331. };
  14332. Mesh.prototype.registerBeforeRender = function (func) {
  14333. this._onBeforeRenderCallbacks.push(func);
  14334. };
  14335. Mesh.prototype.unregisterBeforeRender = function (func) {
  14336. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14337. if (index > -1) {
  14338. this._onBeforeRenderCallbacks.splice(index, 1);
  14339. }
  14340. };
  14341. Mesh.prototype.registerAfterRender = function (func) {
  14342. this._onAfterRenderCallbacks.push(func);
  14343. };
  14344. Mesh.prototype.unregisterAfterRender = function (func) {
  14345. var index = this._onAfterRenderCallbacks.indexOf(func);
  14346. if (index > -1) {
  14347. this._onAfterRenderCallbacks.splice(index, 1);
  14348. }
  14349. };
  14350. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14351. var scene = this.getScene();
  14352. this._batchCache.mustReturn = false;
  14353. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14354. this._batchCache.visibleInstances[subMeshId] = null;
  14355. if (this._visibleInstances) {
  14356. var currentRenderId = scene.getRenderId();
  14357. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14358. var selfRenderId = this._renderId;
  14359. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14360. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14361. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14362. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14363. }
  14364. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14365. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14366. this._batchCache.mustReturn = true;
  14367. return this._batchCache;
  14368. }
  14369. if (currentRenderId !== selfRenderId) {
  14370. this._batchCache.renderSelf[subMeshId] = false;
  14371. }
  14372. }
  14373. this._renderIdForInstances[subMeshId] = currentRenderId;
  14374. }
  14375. return this._batchCache;
  14376. };
  14377. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14378. var visibleInstances = batch.visibleInstances[subMesh._id];
  14379. var matricesCount = visibleInstances.length + 1;
  14380. var bufferSize = matricesCount * 16 * 4;
  14381. while (this._instancesBufferSize < bufferSize) {
  14382. this._instancesBufferSize *= 2;
  14383. }
  14384. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14385. if (this._worldMatricesInstancesBuffer) {
  14386. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14387. }
  14388. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14389. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14390. }
  14391. var offset = 0;
  14392. var instancesCount = 0;
  14393. var world = this.getWorldMatrix();
  14394. if (batch.renderSelf[subMesh._id]) {
  14395. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14396. offset += 16;
  14397. instancesCount++;
  14398. }
  14399. if (visibleInstances) {
  14400. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14401. var instance = visibleInstances[instanceIndex];
  14402. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14403. offset += 16;
  14404. instancesCount++;
  14405. }
  14406. }
  14407. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14408. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14409. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14410. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14411. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14412. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14413. this._draw(subMesh, fillMode, instancesCount);
  14414. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14415. };
  14416. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14417. var scene = this.getScene();
  14418. var engine = scene.getEngine();
  14419. if (hardwareInstancedRendering) {
  14420. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14421. }
  14422. else {
  14423. if (batch.renderSelf[subMesh._id]) {
  14424. // Draw
  14425. if (onBeforeDraw) {
  14426. onBeforeDraw(false, this.getWorldMatrix());
  14427. }
  14428. this._draw(subMesh, fillMode);
  14429. }
  14430. if (batch.visibleInstances[subMesh._id]) {
  14431. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14432. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14433. // World
  14434. var world = instance.getWorldMatrix();
  14435. if (onBeforeDraw) {
  14436. onBeforeDraw(true, world);
  14437. }
  14438. // Draw
  14439. this._draw(subMesh, fillMode);
  14440. }
  14441. }
  14442. }
  14443. };
  14444. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14445. var scene = this.getScene();
  14446. // Managing instances
  14447. var batch = this._getInstancesRenderList(subMesh._id);
  14448. if (batch.mustReturn) {
  14449. return;
  14450. }
  14451. // Checking geometry state
  14452. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14453. return;
  14454. }
  14455. var callbackIndex;
  14456. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14457. this._onBeforeRenderCallbacks[callbackIndex](this);
  14458. }
  14459. var engine = scene.getEngine();
  14460. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14461. // Material
  14462. var effectiveMaterial = subMesh.getMaterial();
  14463. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14464. return;
  14465. }
  14466. // Outline - step 1
  14467. var savedDepthWrite = engine.getDepthWrite();
  14468. if (this.renderOutline) {
  14469. engine.setDepthWrite(false);
  14470. scene.getOutlineRenderer().render(subMesh, batch);
  14471. engine.setDepthWrite(savedDepthWrite);
  14472. }
  14473. effectiveMaterial._preBind();
  14474. var effect = effectiveMaterial.getEffect();
  14475. // Bind
  14476. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14477. this._bind(subMesh, effect, fillMode);
  14478. var world = this.getWorldMatrix();
  14479. effectiveMaterial.bind(world, this);
  14480. // Alpha mode
  14481. if (enableAlphaMode) {
  14482. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14483. }
  14484. // Draw
  14485. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14486. if (isInstance) {
  14487. effectiveMaterial.bindOnlyWorldMatrix(world);
  14488. }
  14489. });
  14490. // Unbind
  14491. effectiveMaterial.unbind();
  14492. // Outline - step 2
  14493. if (this.renderOutline && savedDepthWrite) {
  14494. engine.setDepthWrite(true);
  14495. engine.setColorWrite(false);
  14496. scene.getOutlineRenderer().render(subMesh, batch);
  14497. engine.setColorWrite(true);
  14498. }
  14499. // Overlay
  14500. if (this.renderOverlay) {
  14501. var currentMode = engine.getAlphaMode();
  14502. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14503. scene.getOutlineRenderer().render(subMesh, batch, true);
  14504. engine.setAlphaMode(currentMode);
  14505. }
  14506. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14507. this._onAfterRenderCallbacks[callbackIndex](this);
  14508. }
  14509. };
  14510. Mesh.prototype.getEmittedParticleSystems = function () {
  14511. var results = new Array();
  14512. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14513. var particleSystem = this.getScene().particleSystems[index];
  14514. if (particleSystem.emitter === this) {
  14515. results.push(particleSystem);
  14516. }
  14517. }
  14518. return results;
  14519. };
  14520. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14521. var results = new Array();
  14522. var descendants = this.getDescendants();
  14523. descendants.push(this);
  14524. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14525. var particleSystem = this.getScene().particleSystems[index];
  14526. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14527. results.push(particleSystem);
  14528. }
  14529. }
  14530. return results;
  14531. };
  14532. Mesh.prototype.getChildren = function () {
  14533. var results = [];
  14534. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14535. var mesh = this.getScene().meshes[index];
  14536. if (mesh.parent === this) {
  14537. results.push(mesh);
  14538. }
  14539. }
  14540. return results;
  14541. };
  14542. Mesh.prototype._checkDelayState = function () {
  14543. var _this = this;
  14544. var that = this;
  14545. var scene = this.getScene();
  14546. if (this._geometry) {
  14547. this._geometry.load(scene);
  14548. }
  14549. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14550. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14551. scene._addPendingData(that);
  14552. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14553. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14554. if (data instanceof ArrayBuffer) {
  14555. _this._delayLoadingFunction(data, _this);
  14556. }
  14557. else {
  14558. _this._delayLoadingFunction(JSON.parse(data), _this);
  14559. }
  14560. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14561. scene._removePendingData(_this);
  14562. }, function () { }, scene.database, getBinaryData);
  14563. }
  14564. };
  14565. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14566. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14567. return false;
  14568. }
  14569. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14570. return false;
  14571. }
  14572. this._checkDelayState();
  14573. return true;
  14574. };
  14575. Mesh.prototype.setMaterialByID = function (id) {
  14576. var materials = this.getScene().materials;
  14577. var index;
  14578. for (index = 0; index < materials.length; index++) {
  14579. if (materials[index].id === id) {
  14580. this.material = materials[index];
  14581. return;
  14582. }
  14583. }
  14584. // Multi
  14585. var multiMaterials = this.getScene().multiMaterials;
  14586. for (index = 0; index < multiMaterials.length; index++) {
  14587. if (multiMaterials[index].id === id) {
  14588. this.material = multiMaterials[index];
  14589. return;
  14590. }
  14591. }
  14592. };
  14593. Mesh.prototype.getAnimatables = function () {
  14594. var results = [];
  14595. if (this.material) {
  14596. results.push(this.material);
  14597. }
  14598. if (this.skeleton) {
  14599. results.push(this.skeleton);
  14600. }
  14601. return results;
  14602. };
  14603. // Geometry
  14604. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14605. // Position
  14606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14607. return;
  14608. }
  14609. this._resetPointsArrayCache();
  14610. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14611. var temp = [];
  14612. var index;
  14613. for (index = 0; index < data.length; index += 3) {
  14614. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14615. }
  14616. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14617. // Normals
  14618. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14619. return;
  14620. }
  14621. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14622. temp = [];
  14623. for (index = 0; index < data.length; index += 3) {
  14624. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14625. }
  14626. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14627. // flip faces?
  14628. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14629. this.flipFaces();
  14630. }
  14631. };
  14632. // Will apply current transform to mesh and reset world matrix
  14633. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14634. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14635. this.scaling.copyFromFloats(1, 1, 1);
  14636. this.position.copyFromFloats(0, 0, 0);
  14637. this.rotation.copyFromFloats(0, 0, 0);
  14638. //only if quaternion is already set
  14639. if (this.rotationQuaternion) {
  14640. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14641. }
  14642. this._worldMatrix = BABYLON.Matrix.Identity();
  14643. };
  14644. // Cache
  14645. Mesh.prototype._resetPointsArrayCache = function () {
  14646. this._positions = null;
  14647. };
  14648. Mesh.prototype._generatePointsArray = function () {
  14649. if (this._positions)
  14650. return true;
  14651. this._positions = [];
  14652. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14653. if (!data) {
  14654. return false;
  14655. }
  14656. for (var index = 0; index < data.length; index += 3) {
  14657. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14658. }
  14659. return true;
  14660. };
  14661. // Clone
  14662. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14663. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14664. };
  14665. // Dispose
  14666. Mesh.prototype.dispose = function (doNotRecurse) {
  14667. if (this._geometry) {
  14668. this._geometry.releaseForMesh(this, true);
  14669. }
  14670. // Instances
  14671. if (this._worldMatricesInstancesBuffer) {
  14672. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14673. this._worldMatricesInstancesBuffer = null;
  14674. }
  14675. while (this.instances.length) {
  14676. this.instances[0].dispose();
  14677. }
  14678. _super.prototype.dispose.call(this, doNotRecurse);
  14679. };
  14680. // Geometric tools
  14681. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14682. var _this = this;
  14683. var scene = this.getScene();
  14684. var onload = function (img) {
  14685. // Getting height map data
  14686. var canvas = document.createElement("canvas");
  14687. var context = canvas.getContext("2d");
  14688. var heightMapWidth = img.width;
  14689. var heightMapHeight = img.height;
  14690. canvas.width = heightMapWidth;
  14691. canvas.height = heightMapHeight;
  14692. context.drawImage(img, 0, 0);
  14693. // Create VertexData from map data
  14694. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14695. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14696. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14697. //execute success callback, if set
  14698. if (onSuccess) {
  14699. onSuccess(_this);
  14700. }
  14701. };
  14702. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14703. };
  14704. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14705. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14706. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14707. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14708. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14709. return;
  14710. }
  14711. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14712. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14713. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14714. var position = BABYLON.Vector3.Zero();
  14715. var normal = BABYLON.Vector3.Zero();
  14716. var uv = BABYLON.Vector2.Zero();
  14717. for (var index = 0; index < positions.length; index += 3) {
  14718. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14719. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14720. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14721. // Compute height
  14722. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14723. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14724. var pos = (u + v * heightMapWidth) * 4;
  14725. var r = buffer[pos] / 255.0;
  14726. var g = buffer[pos + 1] / 255.0;
  14727. var b = buffer[pos + 2] / 255.0;
  14728. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14729. normal.normalize();
  14730. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14731. position = position.add(normal);
  14732. position.toArray(positions, index);
  14733. }
  14734. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14735. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14736. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14737. };
  14738. Mesh.prototype.convertToFlatShadedMesh = function () {
  14739. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14740. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14741. var kinds = this.getVerticesDataKinds();
  14742. var vbs = [];
  14743. var data = [];
  14744. var newdata = [];
  14745. var updatableNormals = false;
  14746. var kindIndex;
  14747. var kind;
  14748. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14749. kind = kinds[kindIndex];
  14750. var vertexBuffer = this.getVertexBuffer(kind);
  14751. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14752. updatableNormals = vertexBuffer.isUpdatable();
  14753. kinds.splice(kindIndex, 1);
  14754. kindIndex--;
  14755. continue;
  14756. }
  14757. vbs[kind] = vertexBuffer;
  14758. data[kind] = vbs[kind].getData();
  14759. newdata[kind] = [];
  14760. }
  14761. // Save previous submeshes
  14762. var previousSubmeshes = this.subMeshes.slice(0);
  14763. var indices = this.getIndices();
  14764. var totalIndices = this.getTotalIndices();
  14765. // Generating unique vertices per face
  14766. var index;
  14767. for (index = 0; index < totalIndices; index++) {
  14768. var vertexIndex = indices[index];
  14769. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14770. kind = kinds[kindIndex];
  14771. var stride = vbs[kind].getStrideSize();
  14772. for (var offset = 0; offset < stride; offset++) {
  14773. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14774. }
  14775. }
  14776. }
  14777. // Updating faces & normal
  14778. var normals = [];
  14779. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14780. for (index = 0; index < totalIndices; index += 3) {
  14781. indices[index] = index;
  14782. indices[index + 1] = index + 1;
  14783. indices[index + 2] = index + 2;
  14784. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14785. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14786. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14787. var p1p2 = p1.subtract(p2);
  14788. var p3p2 = p3.subtract(p2);
  14789. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14790. // Store same normals for every vertex
  14791. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14792. normals.push(normal.x);
  14793. normals.push(normal.y);
  14794. normals.push(normal.z);
  14795. }
  14796. }
  14797. this.setIndices(indices);
  14798. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14799. // Updating vertex buffers
  14800. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14801. kind = kinds[kindIndex];
  14802. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14803. }
  14804. // Updating submeshes
  14805. this.releaseSubMeshes();
  14806. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14807. var previousOne = previousSubmeshes[submeshIndex];
  14808. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14809. }
  14810. this.synchronizeInstances();
  14811. };
  14812. // will inverse faces orientations, and invert normals too if specified
  14813. Mesh.prototype.flipFaces = function (flipNormals) {
  14814. if (flipNormals === void 0) { flipNormals = false; }
  14815. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14816. var i;
  14817. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14818. for (i = 0; i < vertex_data.normals.length; i++) {
  14819. vertex_data.normals[i] *= -1;
  14820. }
  14821. }
  14822. var temp;
  14823. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14824. // reassign indices
  14825. temp = vertex_data.indices[i + 1];
  14826. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14827. vertex_data.indices[i + 2] = temp;
  14828. }
  14829. vertex_data.applyToMesh(this);
  14830. };
  14831. // Instances
  14832. Mesh.prototype.createInstance = function (name) {
  14833. return new BABYLON.InstancedMesh(name, this);
  14834. };
  14835. Mesh.prototype.synchronizeInstances = function () {
  14836. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14837. var instance = this.instances[instanceIndex];
  14838. instance._syncSubMeshes();
  14839. }
  14840. };
  14841. /**
  14842. * Simplify the mesh according to the given array of settings.
  14843. * Function will return immediately and will simplify async.
  14844. * @param settings a collection of simplification settings.
  14845. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14846. * @param type the type of simplification to run.
  14847. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14848. */
  14849. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14850. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14851. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14852. this.getScene().simplificationQueue.addTask({
  14853. settings: settings,
  14854. parallelProcessing: parallelProcessing,
  14855. mesh: this,
  14856. simplificationType: simplificationType,
  14857. successCallback: successCallback
  14858. });
  14859. };
  14860. /**
  14861. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14862. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14863. * This should be used together with the simplification to avoid disappearing triangles.
  14864. * @param successCallback an optional success callback to be called after the optimization finished.
  14865. */
  14866. Mesh.prototype.optimizeIndices = function (successCallback) {
  14867. var _this = this;
  14868. var indices = this.getIndices();
  14869. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14870. var vectorPositions = [];
  14871. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14872. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14873. }
  14874. var dupes = [];
  14875. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14876. var realPos = vectorPositions.length - 1 - iteration;
  14877. var testedPosition = vectorPositions[realPos];
  14878. for (var j = 0; j < realPos; ++j) {
  14879. var againstPosition = vectorPositions[j];
  14880. if (testedPosition.equals(againstPosition)) {
  14881. dupes[realPos] = j;
  14882. break;
  14883. }
  14884. }
  14885. }, function () {
  14886. for (var i = 0; i < indices.length; ++i) {
  14887. indices[i] = dupes[indices[i]] || indices[i];
  14888. }
  14889. //indices are now reordered
  14890. var originalSubMeshes = _this.subMeshes.slice(0);
  14891. _this.setIndices(indices);
  14892. _this.subMeshes = originalSubMeshes;
  14893. if (successCallback) {
  14894. successCallback(_this);
  14895. }
  14896. });
  14897. };
  14898. // Statics
  14899. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14900. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14901. pathArray: pathArray,
  14902. closeArray: closeArray,
  14903. closePath: closePath,
  14904. offset: offset,
  14905. updatable: updatable,
  14906. sideOrientation: sideOrientation,
  14907. instance: instance
  14908. }, scene);
  14909. };
  14910. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14911. var options = {
  14912. radius: radius,
  14913. tessellation: tessellation,
  14914. sideOrientation: sideOrientation,
  14915. updatable: updatable
  14916. };
  14917. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14918. };
  14919. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14920. var options = {
  14921. size: size,
  14922. sideOrientation: sideOrientation,
  14923. updatable: updatable
  14924. };
  14925. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14926. };
  14927. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14928. var options = {
  14929. segments: segments,
  14930. diameterX: diameter,
  14931. diameterY: diameter,
  14932. diameterZ: diameter,
  14933. sideOrientation: sideOrientation,
  14934. updatable: updatable
  14935. };
  14936. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14937. };
  14938. // Cylinder and cone
  14939. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14940. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14941. if (scene !== undefined) {
  14942. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  14943. updatable = scene;
  14944. }
  14945. scene = subdivisions;
  14946. subdivisions = 1;
  14947. }
  14948. var options = {
  14949. height: height,
  14950. diameterTop: diameterTop,
  14951. diameterBottom: diameterBottom,
  14952. tessellation: tessellation,
  14953. subdivisions: subdivisions,
  14954. sideOrientation: sideOrientation,
  14955. updatable: updatable
  14956. };
  14957. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14958. };
  14959. // Torus (Code from SharpDX.org)
  14960. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14961. var options = {
  14962. diameter: diameter,
  14963. thickness: thickness,
  14964. tessellation: tessellation,
  14965. sideOrientation: sideOrientation,
  14966. updatable: updatable
  14967. };
  14968. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14969. };
  14970. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14971. var options = {
  14972. radius: radius,
  14973. tube: tube,
  14974. radialSegments: radialSegments,
  14975. tubularSegments: tubularSegments,
  14976. p: p,
  14977. q: q,
  14978. sideOrientation: sideOrientation,
  14979. updatable: updatable
  14980. };
  14981. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14982. };
  14983. // Lines
  14984. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14985. var options = {
  14986. points: points,
  14987. updatable: updatable,
  14988. instance: instance
  14989. };
  14990. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14991. };
  14992. // Dashed Lines
  14993. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14994. var options = {
  14995. points: points,
  14996. dashSize: dashSize,
  14997. gapSize: gapSize,
  14998. dashNb: dashNb,
  14999. updatable: updatable
  15000. };
  15001. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  15002. };
  15003. // Extrusion
  15004. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  15005. var options = {
  15006. shape: shape,
  15007. path: path,
  15008. scale: scale,
  15009. rotation: rotation,
  15010. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15011. sideOrientation: sideOrientation,
  15012. instance: instance,
  15013. updatable: updatable
  15014. };
  15015. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  15016. };
  15017. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  15018. var options = {
  15019. shape: shape,
  15020. path: path,
  15021. scaleFunction: scaleFunction,
  15022. rotationFunction: rotationFunction,
  15023. ribbonCloseArray: ribbonCloseArray,
  15024. ribbonClosePath: ribbonClosePath,
  15025. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  15026. sideOrientation: sideOrientation,
  15027. instance: instance,
  15028. updatable: updatable
  15029. };
  15030. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  15031. };
  15032. // Lathe
  15033. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15034. var options = {
  15035. shape: shape,
  15036. radius: radius,
  15037. tessellation: tessellation,
  15038. sideOrientation: sideOrientation,
  15039. updatable: updatable
  15040. };
  15041. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  15042. };
  15043. // Plane & ground
  15044. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15045. var options = {
  15046. size: size,
  15047. width: size,
  15048. height: size,
  15049. sideOrientation: sideOrientation,
  15050. updatable: updatable
  15051. };
  15052. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  15053. };
  15054. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15055. var options = {
  15056. width: width,
  15057. height: height,
  15058. subdivisions: subdivisions,
  15059. updatable: updatable
  15060. };
  15061. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  15062. };
  15063. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15064. var options = {
  15065. xmin: xmin,
  15066. zmin: zmin,
  15067. xmax: xmax,
  15068. zmax: zmax,
  15069. subdivisions: subdivisions,
  15070. precision: precision,
  15071. updatable: updatable
  15072. };
  15073. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  15074. };
  15075. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15076. var options = {
  15077. width: width,
  15078. height: height,
  15079. subdivisions: subdivisions,
  15080. minHeight: minHeight,
  15081. maxHeight: maxHeight,
  15082. updatable: updatable,
  15083. onReady: onReady
  15084. };
  15085. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  15086. };
  15087. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  15088. var options = {
  15089. path: path,
  15090. radius: radius,
  15091. tessellation: tessellation,
  15092. radiusFunction: radiusFunction,
  15093. arc: 1,
  15094. cap: cap,
  15095. updatable: updatable,
  15096. sideOrientation: sideOrientation,
  15097. instance: instance
  15098. };
  15099. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  15100. };
  15101. Mesh.CreatePolyhedron = function (name, options, scene) {
  15102. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  15103. };
  15104. Mesh.CreateIcoSphere = function (name, options, scene) {
  15105. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  15106. };
  15107. // Decals
  15108. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15109. var options = {
  15110. position: position,
  15111. normal: normal,
  15112. size: size,
  15113. angle: angle
  15114. };
  15115. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  15116. };
  15117. // Skeletons
  15118. /**
  15119. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15120. */
  15121. Mesh.prototype.setPositionsForCPUSkinning = function () {
  15122. var source;
  15123. if (!this._sourcePositions) {
  15124. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15125. this._sourcePositions = new Float32Array(source);
  15126. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  15127. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  15128. }
  15129. }
  15130. return this._sourcePositions;
  15131. };
  15132. /**
  15133. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  15134. */
  15135. Mesh.prototype.setNormalsForCPUSkinning = function () {
  15136. var source;
  15137. if (!this._sourceNormals) {
  15138. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15139. this._sourceNormals = new Float32Array(source);
  15140. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  15141. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  15142. }
  15143. }
  15144. return this._sourceNormals;
  15145. };
  15146. /**
  15147. * Update the vertex buffers by applying transformation from the bones
  15148. * @param {skeleton} skeleton to apply
  15149. */
  15150. Mesh.prototype.applySkeleton = function (skeleton) {
  15151. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15152. return this;
  15153. }
  15154. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15155. return this;
  15156. }
  15157. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  15158. return this;
  15159. }
  15160. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  15161. return this;
  15162. }
  15163. if (!this._sourcePositions) {
  15164. this.setPositionsForCPUSkinning();
  15165. }
  15166. if (!this._sourceNormals) {
  15167. this.setNormalsForCPUSkinning();
  15168. }
  15169. // positionsData checks for not being Float32Array will only pass at most once
  15170. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15171. if (!(positionsData instanceof Float32Array)) {
  15172. positionsData = new Float32Array(positionsData);
  15173. }
  15174. // normalsData checks for not being Float32Array will only pass at most once
  15175. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15176. if (!(normalsData instanceof Float32Array)) {
  15177. normalsData = new Float32Array(normalsData);
  15178. }
  15179. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  15180. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  15181. var needExtras = this.numBoneInfluencers > 4;
  15182. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  15183. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  15184. var skeletonMatrices = skeleton.getTransformMatrices();
  15185. var tempVector3 = BABYLON.Vector3.Zero();
  15186. var finalMatrix = new BABYLON.Matrix();
  15187. var tempMatrix = new BABYLON.Matrix();
  15188. var matWeightIdx = 0;
  15189. var inf;
  15190. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  15191. var weight;
  15192. for (inf = 0; inf < 4; inf++) {
  15193. weight = matricesWeightsData[matWeightIdx + inf];
  15194. if (weight > 0) {
  15195. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15196. finalMatrix.addToSelf(tempMatrix);
  15197. }
  15198. else
  15199. break;
  15200. }
  15201. if (needExtras) {
  15202. for (inf = 0; inf < 4; inf++) {
  15203. weight = matricesWeightsExtraData[matWeightIdx + inf];
  15204. if (weight > 0) {
  15205. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  15206. finalMatrix.addToSelf(tempMatrix);
  15207. }
  15208. else
  15209. break;
  15210. }
  15211. }
  15212. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15213. tempVector3.toArray(positionsData, index);
  15214. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15215. tempVector3.toArray(normalsData, index);
  15216. finalMatrix.reset();
  15217. }
  15218. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15219. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15220. return this;
  15221. };
  15222. // Tools
  15223. Mesh.MinMax = function (meshes) {
  15224. var minVector = null;
  15225. var maxVector = null;
  15226. for (var i in meshes) {
  15227. var mesh = meshes[i];
  15228. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15229. if (!minVector) {
  15230. minVector = boundingBox.minimumWorld;
  15231. maxVector = boundingBox.maximumWorld;
  15232. continue;
  15233. }
  15234. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15235. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15236. }
  15237. return {
  15238. min: minVector,
  15239. max: maxVector
  15240. };
  15241. };
  15242. Mesh.Center = function (meshesOrMinMaxVector) {
  15243. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15244. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15245. };
  15246. /**
  15247. * Merge the array of meshes into a single mesh for performance reasons.
  15248. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15249. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15250. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15251. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15252. */
  15253. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15254. if (disposeSource === void 0) { disposeSource = true; }
  15255. var index;
  15256. if (!allow32BitsIndices) {
  15257. var totalVertices = 0;
  15258. // Counting vertices
  15259. for (index = 0; index < meshes.length; index++) {
  15260. if (meshes[index]) {
  15261. totalVertices += meshes[index].getTotalVertices();
  15262. if (totalVertices > 65536) {
  15263. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15264. return null;
  15265. }
  15266. }
  15267. }
  15268. }
  15269. // Merge
  15270. var vertexData;
  15271. var otherVertexData;
  15272. var source;
  15273. for (index = 0; index < meshes.length; index++) {
  15274. if (meshes[index]) {
  15275. meshes[index].computeWorldMatrix(true);
  15276. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15277. otherVertexData.transform(meshes[index].getWorldMatrix());
  15278. if (vertexData) {
  15279. vertexData.merge(otherVertexData);
  15280. }
  15281. else {
  15282. vertexData = otherVertexData;
  15283. source = meshes[index];
  15284. }
  15285. }
  15286. }
  15287. if (!meshSubclass) {
  15288. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15289. }
  15290. vertexData.applyToMesh(meshSubclass);
  15291. // Setting properties
  15292. meshSubclass.material = source.material;
  15293. meshSubclass.checkCollisions = source.checkCollisions;
  15294. // Cleaning
  15295. if (disposeSource) {
  15296. for (index = 0; index < meshes.length; index++) {
  15297. if (meshes[index]) {
  15298. meshes[index].dispose();
  15299. }
  15300. }
  15301. }
  15302. return meshSubclass;
  15303. };
  15304. // Consts
  15305. Mesh._FRONTSIDE = 0;
  15306. Mesh._BACKSIDE = 1;
  15307. Mesh._DOUBLESIDE = 2;
  15308. Mesh._DEFAULTSIDE = 0;
  15309. Mesh._NO_CAP = 0;
  15310. Mesh._CAP_START = 1;
  15311. Mesh._CAP_END = 2;
  15312. Mesh._CAP_ALL = 3;
  15313. return Mesh;
  15314. })(BABYLON.AbstractMesh);
  15315. BABYLON.Mesh = Mesh;
  15316. })(BABYLON || (BABYLON = {}));
  15317. var BABYLON;
  15318. (function (BABYLON) {
  15319. var SubMesh = (function () {
  15320. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15321. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15322. this.materialIndex = materialIndex;
  15323. this.verticesStart = verticesStart;
  15324. this.verticesCount = verticesCount;
  15325. this.indexStart = indexStart;
  15326. this.indexCount = indexCount;
  15327. this._renderId = 0;
  15328. this._mesh = mesh;
  15329. this._renderingMesh = renderingMesh || mesh;
  15330. mesh.subMeshes.push(this);
  15331. this._trianglePlanes = [];
  15332. this._id = mesh.subMeshes.length - 1;
  15333. if (createBoundingBox) {
  15334. this.refreshBoundingInfo();
  15335. mesh.computeWorldMatrix(true);
  15336. }
  15337. }
  15338. SubMesh.prototype.getBoundingInfo = function () {
  15339. return this._boundingInfo;
  15340. };
  15341. SubMesh.prototype.getMesh = function () {
  15342. return this._mesh;
  15343. };
  15344. SubMesh.prototype.getRenderingMesh = function () {
  15345. return this._renderingMesh;
  15346. };
  15347. SubMesh.prototype.getMaterial = function () {
  15348. var rootMaterial = this._renderingMesh.material;
  15349. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15350. var multiMaterial = rootMaterial;
  15351. return multiMaterial.getSubMaterial(this.materialIndex);
  15352. }
  15353. if (!rootMaterial) {
  15354. return this._mesh.getScene().defaultMaterial;
  15355. }
  15356. return rootMaterial;
  15357. };
  15358. // Methods
  15359. SubMesh.prototype.refreshBoundingInfo = function () {
  15360. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15361. if (!data) {
  15362. this._boundingInfo = this._mesh._boundingInfo;
  15363. return;
  15364. }
  15365. var indices = this._renderingMesh.getIndices();
  15366. var extend;
  15367. //is this the only submesh?
  15368. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15369. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15370. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15371. }
  15372. else {
  15373. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15374. }
  15375. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15376. };
  15377. SubMesh.prototype._checkCollision = function (collider) {
  15378. return this._boundingInfo._checkCollision(collider);
  15379. };
  15380. SubMesh.prototype.updateBoundingInfo = function (world) {
  15381. if (!this._boundingInfo) {
  15382. this.refreshBoundingInfo();
  15383. }
  15384. this._boundingInfo._update(world);
  15385. };
  15386. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15387. return this._boundingInfo.isInFrustum(frustumPlanes);
  15388. };
  15389. SubMesh.prototype.render = function (enableAlphaMode) {
  15390. this._renderingMesh.render(this, enableAlphaMode);
  15391. };
  15392. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15393. if (!this._linesIndexBuffer) {
  15394. var linesIndices = [];
  15395. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15396. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15397. }
  15398. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15399. this.linesIndexCount = linesIndices.length;
  15400. }
  15401. return this._linesIndexBuffer;
  15402. };
  15403. SubMesh.prototype.canIntersects = function (ray) {
  15404. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15405. };
  15406. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15407. var intersectInfo = null;
  15408. // Triangles test
  15409. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15410. var p0 = positions[indices[index]];
  15411. var p1 = positions[indices[index + 1]];
  15412. var p2 = positions[indices[index + 2]];
  15413. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15414. if (currentIntersectInfo) {
  15415. if (currentIntersectInfo.distance < 0) {
  15416. continue;
  15417. }
  15418. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15419. intersectInfo = currentIntersectInfo;
  15420. intersectInfo.faceId = index / 3;
  15421. if (fastCheck) {
  15422. break;
  15423. }
  15424. }
  15425. }
  15426. }
  15427. return intersectInfo;
  15428. };
  15429. // Clone
  15430. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15431. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15432. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15433. return result;
  15434. };
  15435. // Dispose
  15436. SubMesh.prototype.dispose = function () {
  15437. if (this._linesIndexBuffer) {
  15438. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15439. this._linesIndexBuffer = null;
  15440. }
  15441. // Remove from mesh
  15442. var index = this._mesh.subMeshes.indexOf(this);
  15443. this._mesh.subMeshes.splice(index, 1);
  15444. };
  15445. // Statics
  15446. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15447. var minVertexIndex = Number.MAX_VALUE;
  15448. var maxVertexIndex = -Number.MAX_VALUE;
  15449. renderingMesh = renderingMesh || mesh;
  15450. var indices = renderingMesh.getIndices();
  15451. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15452. var vertexIndex = indices[index];
  15453. if (vertexIndex < minVertexIndex)
  15454. minVertexIndex = vertexIndex;
  15455. if (vertexIndex > maxVertexIndex)
  15456. maxVertexIndex = vertexIndex;
  15457. }
  15458. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15459. };
  15460. return SubMesh;
  15461. })();
  15462. BABYLON.SubMesh = SubMesh;
  15463. })(BABYLON || (BABYLON = {}));
  15464. var BABYLON;
  15465. (function (BABYLON) {
  15466. var MeshBuilder = (function () {
  15467. function MeshBuilder() {
  15468. }
  15469. MeshBuilder.CreateBox = function (name, options, scene) {
  15470. var box = new BABYLON.Mesh(name, scene);
  15471. var vertexData = BABYLON.VertexData.CreateBox(options);
  15472. vertexData.applyToMesh(box, options.updatable);
  15473. return box;
  15474. };
  15475. MeshBuilder.CreateSphere = function (name, options, scene) {
  15476. var sphere = new BABYLON.Mesh(name, scene);
  15477. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15478. vertexData.applyToMesh(sphere, options.updatable);
  15479. return sphere;
  15480. };
  15481. MeshBuilder.CreateDisc = function (name, options, scene) {
  15482. var disc = new BABYLON.Mesh(name, scene);
  15483. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15484. vertexData.applyToMesh(disc, options.updatable);
  15485. return disc;
  15486. };
  15487. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  15488. var sphere = new BABYLON.Mesh(name, scene);
  15489. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  15490. vertexData.applyToMesh(sphere, options.updatable);
  15491. return sphere;
  15492. };
  15493. ;
  15494. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15495. var pathArray = options.pathArray;
  15496. var closeArray = options.closeArray;
  15497. var closePath = options.closePath;
  15498. var offset = options.offset;
  15499. var sideOrientation = options.sideOrientation;
  15500. var instance = options.instance;
  15501. var updatable = options.updatable;
  15502. if (instance) {
  15503. // positionFunction : ribbon case
  15504. // only pathArray and sideOrientation parameters are taken into account for positions update
  15505. var positionFunction = function (positions) {
  15506. var minlg = pathArray[0].length;
  15507. var i = 0;
  15508. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15509. for (var si = 1; si <= ns; si++) {
  15510. for (var p = 0; p < pathArray.length; p++) {
  15511. var path = pathArray[p];
  15512. var l = path.length;
  15513. minlg = (minlg < l) ? minlg : l;
  15514. var j = 0;
  15515. while (j < minlg) {
  15516. positions[i] = path[j].x;
  15517. positions[i + 1] = path[j].y;
  15518. positions[i + 2] = path[j].z;
  15519. j++;
  15520. i += 3;
  15521. }
  15522. if (instance._closePath) {
  15523. positions[i] = path[0].x;
  15524. positions[i + 1] = path[0].y;
  15525. positions[i + 2] = path[0].z;
  15526. i += 3;
  15527. }
  15528. }
  15529. }
  15530. };
  15531. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15532. positionFunction(positions);
  15533. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15534. if (!(instance.areNormalsFrozen)) {
  15535. var indices = instance.getIndices();
  15536. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15537. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15538. if (instance._closePath) {
  15539. var indexFirst = 0;
  15540. var indexLast = 0;
  15541. for (var p = 0; p < pathArray.length; p++) {
  15542. indexFirst = instance._idx[p] * 3;
  15543. if (p + 1 < pathArray.length) {
  15544. indexLast = (instance._idx[p + 1] - 1) * 3;
  15545. }
  15546. else {
  15547. indexLast = normals.length - 3;
  15548. }
  15549. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15550. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15551. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15552. normals[indexLast] = normals[indexFirst];
  15553. normals[indexLast + 1] = normals[indexFirst + 1];
  15554. normals[indexLast + 2] = normals[indexFirst + 2];
  15555. }
  15556. }
  15557. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15558. }
  15559. return instance;
  15560. }
  15561. else {
  15562. var ribbon = new BABYLON.Mesh(name, scene);
  15563. ribbon.sideOrientation = sideOrientation;
  15564. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15565. if (closePath) {
  15566. ribbon._idx = vertexData._idx;
  15567. }
  15568. ribbon._closePath = closePath;
  15569. ribbon._closeArray = closeArray;
  15570. vertexData.applyToMesh(ribbon, updatable);
  15571. return ribbon;
  15572. }
  15573. };
  15574. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15575. var cylinder = new BABYLON.Mesh(name, scene);
  15576. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15577. vertexData.applyToMesh(cylinder, options.updatable);
  15578. return cylinder;
  15579. };
  15580. MeshBuilder.CreateTorus = function (name, options, scene) {
  15581. var torus = new BABYLON.Mesh(name, scene);
  15582. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15583. vertexData.applyToMesh(torus, options.updatable);
  15584. return torus;
  15585. };
  15586. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15587. var torusKnot = new BABYLON.Mesh(name, scene);
  15588. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15589. vertexData.applyToMesh(torusKnot, options.updatable);
  15590. return torusKnot;
  15591. };
  15592. MeshBuilder.CreateLines = function (name, options, scene) {
  15593. var instance = options.instance;
  15594. var points = options.points;
  15595. if (instance) {
  15596. var positionFunction = function (positions) {
  15597. var i = 0;
  15598. for (var p = 0; p < points.length; p++) {
  15599. positions[i] = points[p].x;
  15600. positions[i + 1] = points[p].y;
  15601. positions[i + 2] = points[p].z;
  15602. i += 3;
  15603. }
  15604. };
  15605. instance.updateMeshPositions(positionFunction, false);
  15606. return instance;
  15607. }
  15608. // lines creation
  15609. var lines = new BABYLON.LinesMesh(name, scene);
  15610. var vertexData = BABYLON.VertexData.CreateLines(options);
  15611. vertexData.applyToMesh(lines, options.updatable);
  15612. return lines;
  15613. };
  15614. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15615. var points = options.points;
  15616. var instance = options.instance;
  15617. var gapSize = options.gapSize;
  15618. var dashNb = options.dashNb;
  15619. var dashSize = options.dashSize;
  15620. if (instance) {
  15621. var positionFunction = function (positions) {
  15622. var curvect = BABYLON.Vector3.Zero();
  15623. var nbSeg = positions.length / 6;
  15624. var lg = 0;
  15625. var nb = 0;
  15626. var shft = 0;
  15627. var dashshft = 0;
  15628. var curshft = 0;
  15629. var p = 0;
  15630. var i = 0;
  15631. var j = 0;
  15632. for (i = 0; i < points.length - 1; i++) {
  15633. points[i + 1].subtractToRef(points[i], curvect);
  15634. lg += curvect.length();
  15635. }
  15636. shft = lg / nbSeg;
  15637. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15638. for (i = 0; i < points.length - 1; i++) {
  15639. points[i + 1].subtractToRef(points[i], curvect);
  15640. nb = Math.floor(curvect.length() / shft);
  15641. curvect.normalize();
  15642. j = 0;
  15643. while (j < nb && p < positions.length) {
  15644. curshft = shft * j;
  15645. positions[p] = points[i].x + curshft * curvect.x;
  15646. positions[p + 1] = points[i].y + curshft * curvect.y;
  15647. positions[p + 2] = points[i].z + curshft * curvect.z;
  15648. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15649. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15650. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15651. p += 6;
  15652. j++;
  15653. }
  15654. }
  15655. while (p < positions.length) {
  15656. positions[p] = points[i].x;
  15657. positions[p + 1] = points[i].y;
  15658. positions[p + 2] = points[i].z;
  15659. p += 3;
  15660. }
  15661. };
  15662. instance.updateMeshPositions(positionFunction, false);
  15663. return instance;
  15664. }
  15665. // dashed lines creation
  15666. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15667. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15668. vertexData.applyToMesh(dashedLines, options.updatable);
  15669. dashedLines.dashSize = dashSize;
  15670. dashedLines.gapSize = gapSize;
  15671. return dashedLines;
  15672. };
  15673. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15674. var path = options.path;
  15675. var shape = options.shape;
  15676. var scale = options.scale || 1;
  15677. var rotation = options.rotation || 0;
  15678. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15679. var updatable = options.updatable;
  15680. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15681. var instance = options.instance;
  15682. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15683. };
  15684. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15685. var path = options.path;
  15686. var shape = options.shape;
  15687. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15688. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15689. var ribbonCloseArray = options.ribbonCloseArray || false;
  15690. var ribbonClosePath = options.ribbonClosePath || false;
  15691. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15692. var updatable = options.updatable;
  15693. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15694. var instance = options.instance;
  15695. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15696. };
  15697. MeshBuilder.CreateLathe = function (name, options, scene) {
  15698. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15699. var closed = (options.closed === undefined) ? true : options.closed;
  15700. var shape = options.shape;
  15701. var radius = options.radius || 1;
  15702. var tessellation = options.tessellation || 64;
  15703. var updatable = options.updatable;
  15704. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15705. var pi2 = Math.PI * 2;
  15706. var shapeLathe = new Array();
  15707. // first rotatable point
  15708. var i = 0;
  15709. while (shape[i].x === 0) {
  15710. i++;
  15711. }
  15712. var pt = shape[i];
  15713. for (i = 0; i < shape.length; i++) {
  15714. shapeLathe.push(shape[i].subtract(pt));
  15715. }
  15716. // circle path
  15717. var step = pi2 / tessellation * arc;
  15718. var rotated;
  15719. var path = new Array();
  15720. ;
  15721. for (i = 0; i <= tessellation; i++) {
  15722. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15723. path.push(rotated);
  15724. }
  15725. if (closed) {
  15726. path.push(path[0]);
  15727. }
  15728. // extrusion
  15729. var scaleFunction = function () { return 1; };
  15730. var rotateFunction = function () { return 0; };
  15731. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15732. return lathe;
  15733. };
  15734. MeshBuilder.CreatePlane = function (name, options, scene) {
  15735. var plane = new BABYLON.Mesh(name, scene);
  15736. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15737. vertexData.applyToMesh(plane, options.updatable);
  15738. if (options.sourcePlane) {
  15739. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15740. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15741. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15742. plane.rotate(vectorProduct, product);
  15743. }
  15744. return plane;
  15745. };
  15746. MeshBuilder.CreateGround = function (name, options, scene) {
  15747. var ground = new BABYLON.GroundMesh(name, scene);
  15748. ground._setReady(false);
  15749. ground._subdivisions = options.subdivisions || 1;
  15750. var vertexData = BABYLON.VertexData.CreateGround(options);
  15751. vertexData.applyToMesh(ground, options.updatable);
  15752. ground._setReady(true);
  15753. return ground;
  15754. };
  15755. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15756. var tiledGround = new BABYLON.Mesh(name, scene);
  15757. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15758. vertexData.applyToMesh(tiledGround, options.updatable);
  15759. return tiledGround;
  15760. };
  15761. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15762. var width = options.width || 10;
  15763. var height = options.height || 10;
  15764. var subdivisions = options.subdivisions || 1;
  15765. var minHeight = options.minHeight;
  15766. var maxHeight = options.maxHeight || 10;
  15767. var updatable = options.updatable;
  15768. var onReady = options.onReady;
  15769. var ground = new BABYLON.GroundMesh(name, scene);
  15770. ground._subdivisions = subdivisions;
  15771. ground._setReady(false);
  15772. var onload = function (img) {
  15773. // Getting height map data
  15774. var canvas = document.createElement("canvas");
  15775. var context = canvas.getContext("2d");
  15776. var bufferWidth = img.width;
  15777. var bufferHeight = img.height;
  15778. canvas.width = bufferWidth;
  15779. canvas.height = bufferHeight;
  15780. context.drawImage(img, 0, 0);
  15781. // Create VertexData from map data
  15782. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15783. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15784. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15785. width: width, height: height,
  15786. subdivisions: subdivisions,
  15787. minHeight: minHeight, maxHeight: maxHeight,
  15788. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15789. });
  15790. vertexData.applyToMesh(ground, updatable);
  15791. ground._setReady(true);
  15792. //execute ready callback, if set
  15793. if (onReady) {
  15794. onReady(ground);
  15795. }
  15796. };
  15797. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15798. return ground;
  15799. };
  15800. MeshBuilder.CreateTube = function (name, options, scene) {
  15801. var path = options.path;
  15802. var radius = options.radius || 1;
  15803. var tessellation = options.tessellation || 64;
  15804. var radiusFunction = options.radiusFunction;
  15805. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15806. var updatable = options.updatable;
  15807. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15808. var instance = options.instance;
  15809. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15810. // tube geometry
  15811. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15812. var tangents = path3D.getTangents();
  15813. var normals = path3D.getNormals();
  15814. var distances = path3D.getDistances();
  15815. var pi2 = Math.PI * 2;
  15816. var step = pi2 / tessellation * arc;
  15817. var returnRadius = function () { return radius; };
  15818. var radiusFunctionFinal = radiusFunction || returnRadius;
  15819. var circlePath;
  15820. var rad;
  15821. var normal;
  15822. var rotated;
  15823. var rotationMatrix = BABYLON.Matrix.Zero();
  15824. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15825. for (var i = 0; i < path.length; i++) {
  15826. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15827. circlePath = Array(); // current circle array
  15828. normal = normals[i]; // current normal
  15829. for (var t = 0; t < tessellation; t++) {
  15830. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15831. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15832. circlePath.push(rotated);
  15833. }
  15834. circlePaths[index] = circlePath;
  15835. index++;
  15836. }
  15837. // cap
  15838. var capPath = function (nbPoints, pathIndex) {
  15839. var pointCap = Array();
  15840. for (var i = 0; i < nbPoints; i++) {
  15841. pointCap.push(path[pathIndex]);
  15842. }
  15843. return pointCap;
  15844. };
  15845. switch (cap) {
  15846. case BABYLON.Mesh.NO_CAP:
  15847. break;
  15848. case BABYLON.Mesh.CAP_START:
  15849. circlePaths[0] = capPath(tessellation, 0);
  15850. circlePaths[1] = circlePaths[2].slice(0);
  15851. break;
  15852. case BABYLON.Mesh.CAP_END:
  15853. circlePaths[index] = circlePaths[index - 1].slice(0);
  15854. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15855. break;
  15856. case BABYLON.Mesh.CAP_ALL:
  15857. circlePaths[0] = capPath(tessellation, 0);
  15858. circlePaths[1] = circlePaths[2].slice(0);
  15859. circlePaths[index] = circlePaths[index - 1].slice(0);
  15860. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15861. break;
  15862. default:
  15863. break;
  15864. }
  15865. return circlePaths;
  15866. };
  15867. var path3D;
  15868. var pathArray;
  15869. if (instance) {
  15870. var arc = options.arc || instance.arc;
  15871. path3D = (instance.path3D).update(path);
  15872. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15873. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15874. instance.path3D = path3D;
  15875. instance.pathArray = pathArray;
  15876. instance.arc = arc;
  15877. return instance;
  15878. }
  15879. // tube creation
  15880. path3D = new BABYLON.Path3D(path);
  15881. var newPathArray = new Array();
  15882. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15883. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15884. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15885. tube.pathArray = pathArray;
  15886. tube.path3D = path3D;
  15887. tube.tessellation = tessellation;
  15888. tube.cap = cap;
  15889. tube.arc = options.arc;
  15890. return tube;
  15891. };
  15892. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15893. var polyhedron = new BABYLON.Mesh(name, scene);
  15894. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15895. vertexData.applyToMesh(polyhedron, options.updatable);
  15896. return polyhedron;
  15897. };
  15898. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15899. var indices = sourceMesh.getIndices();
  15900. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15901. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15902. var position = options.position || BABYLON.Vector3.Zero();
  15903. var normal = options.normal || BABYLON.Vector3.Up();
  15904. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15905. var angle = options.angle || 0;
  15906. // Getting correct rotation
  15907. if (!normal) {
  15908. var target = new BABYLON.Vector3(0, 0, 1);
  15909. var camera = sourceMesh.getScene().activeCamera;
  15910. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15911. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15912. }
  15913. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15914. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15915. var pitch = Math.atan2(normal.y, len);
  15916. // Matrix
  15917. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15918. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15919. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15920. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15921. var vertexData = new BABYLON.VertexData();
  15922. vertexData.indices = [];
  15923. vertexData.positions = [];
  15924. vertexData.normals = [];
  15925. vertexData.uvs = [];
  15926. var currentVertexDataIndex = 0;
  15927. var extractDecalVector3 = function (indexId) {
  15928. var vertexId = indices[indexId];
  15929. var result = new BABYLON.PositionNormalVertex();
  15930. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15931. // Send vector to decal local world
  15932. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15933. // Get normal
  15934. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15935. return result;
  15936. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15937. var clip = function (vertices, axis) {
  15938. if (vertices.length === 0) {
  15939. return vertices;
  15940. }
  15941. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15942. var clipVertices = function (v0, v1) {
  15943. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15944. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15945. };
  15946. var result = new Array();
  15947. for (var index = 0; index < vertices.length; index += 3) {
  15948. var v1Out;
  15949. var v2Out;
  15950. var v3Out;
  15951. var total = 0;
  15952. var nV1, nV2, nV3, nV4;
  15953. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15954. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15955. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15956. v1Out = d1 > 0;
  15957. v2Out = d2 > 0;
  15958. v3Out = d3 > 0;
  15959. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15960. switch (total) {
  15961. case 0:
  15962. result.push(vertices[index]);
  15963. result.push(vertices[index + 1]);
  15964. result.push(vertices[index + 2]);
  15965. break;
  15966. case 1:
  15967. if (v1Out) {
  15968. nV1 = vertices[index + 1];
  15969. nV2 = vertices[index + 2];
  15970. nV3 = clipVertices(vertices[index], nV1);
  15971. nV4 = clipVertices(vertices[index], nV2);
  15972. }
  15973. if (v2Out) {
  15974. nV1 = vertices[index];
  15975. nV2 = vertices[index + 2];
  15976. nV3 = clipVertices(vertices[index + 1], nV1);
  15977. nV4 = clipVertices(vertices[index + 1], nV2);
  15978. result.push(nV3);
  15979. result.push(nV2.clone());
  15980. result.push(nV1.clone());
  15981. result.push(nV2.clone());
  15982. result.push(nV3.clone());
  15983. result.push(nV4);
  15984. break;
  15985. }
  15986. if (v3Out) {
  15987. nV1 = vertices[index];
  15988. nV2 = vertices[index + 1];
  15989. nV3 = clipVertices(vertices[index + 2], nV1);
  15990. nV4 = clipVertices(vertices[index + 2], nV2);
  15991. }
  15992. result.push(nV1.clone());
  15993. result.push(nV2.clone());
  15994. result.push(nV3);
  15995. result.push(nV4);
  15996. result.push(nV3.clone());
  15997. result.push(nV2.clone());
  15998. break;
  15999. case 2:
  16000. if (!v1Out) {
  16001. nV1 = vertices[index].clone();
  16002. nV2 = clipVertices(nV1, vertices[index + 1]);
  16003. nV3 = clipVertices(nV1, vertices[index + 2]);
  16004. result.push(nV1);
  16005. result.push(nV2);
  16006. result.push(nV3);
  16007. }
  16008. if (!v2Out) {
  16009. nV1 = vertices[index + 1].clone();
  16010. nV2 = clipVertices(nV1, vertices[index + 2]);
  16011. nV3 = clipVertices(nV1, vertices[index]);
  16012. result.push(nV1);
  16013. result.push(nV2);
  16014. result.push(nV3);
  16015. }
  16016. if (!v3Out) {
  16017. nV1 = vertices[index + 2].clone();
  16018. nV2 = clipVertices(nV1, vertices[index]);
  16019. nV3 = clipVertices(nV1, vertices[index + 1]);
  16020. result.push(nV1);
  16021. result.push(nV2);
  16022. result.push(nV3);
  16023. }
  16024. break;
  16025. case 3:
  16026. break;
  16027. }
  16028. }
  16029. return result;
  16030. };
  16031. for (var index = 0; index < indices.length; index += 3) {
  16032. var faceVertices = new Array();
  16033. faceVertices.push(extractDecalVector3(index));
  16034. faceVertices.push(extractDecalVector3(index + 1));
  16035. faceVertices.push(extractDecalVector3(index + 2));
  16036. // Clip
  16037. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16038. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16039. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16040. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16041. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16042. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16043. if (faceVertices.length === 0) {
  16044. continue;
  16045. }
  16046. // Add UVs and get back to world
  16047. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16048. var vertex = faceVertices[vIndex];
  16049. vertexData.indices.push(currentVertexDataIndex);
  16050. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16051. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16052. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16053. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16054. currentVertexDataIndex++;
  16055. }
  16056. }
  16057. // Return mesh
  16058. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  16059. vertexData.applyToMesh(decal);
  16060. decal.position = position.clone();
  16061. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16062. return decal;
  16063. };
  16064. // Privates
  16065. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  16066. // extrusion geometry
  16067. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  16068. var tangents = path3D.getTangents();
  16069. var normals = path3D.getNormals();
  16070. var binormals = path3D.getBinormals();
  16071. var distances = path3D.getDistances();
  16072. var angle = 0;
  16073. var returnScale = function () { return scale; };
  16074. var returnRotation = function () { return rotation; };
  16075. var rotate = custom ? rotateFunction : returnRotation;
  16076. var scl = custom ? scaleFunction : returnScale;
  16077. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16078. var rotationMatrix = BABYLON.Matrix.Zero();
  16079. for (var i = 0; i < curve.length; i++) {
  16080. var shapePath = new Array();
  16081. var angleStep = rotate(i, distances[i]);
  16082. var scaleRatio = scl(i, distances[i]);
  16083. for (var p = 0; p < shape.length; p++) {
  16084. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  16085. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  16086. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  16087. shapePath.push(rotated);
  16088. }
  16089. shapePaths[index] = shapePath;
  16090. angle += angleStep;
  16091. index++;
  16092. }
  16093. // cap
  16094. var capPath = function (shapePath) {
  16095. var pointCap = Array();
  16096. var barycenter = BABYLON.Vector3.Zero();
  16097. var i;
  16098. for (i = 0; i < shapePath.length; i++) {
  16099. barycenter.addInPlace(shapePath[i]);
  16100. }
  16101. barycenter.scaleInPlace(1 / shapePath.length);
  16102. for (i = 0; i < shapePath.length; i++) {
  16103. pointCap.push(barycenter);
  16104. }
  16105. return pointCap;
  16106. };
  16107. switch (cap) {
  16108. case BABYLON.Mesh.NO_CAP:
  16109. break;
  16110. case BABYLON.Mesh.CAP_START:
  16111. shapePaths[0] = capPath(shapePaths[2]);
  16112. shapePaths[1] = shapePaths[2].slice(0);
  16113. break;
  16114. case BABYLON.Mesh.CAP_END:
  16115. shapePaths[index] = shapePaths[index - 1];
  16116. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16117. break;
  16118. case BABYLON.Mesh.CAP_ALL:
  16119. shapePaths[0] = capPath(shapePaths[2]);
  16120. shapePaths[1] = shapePaths[2].slice(0);
  16121. shapePaths[index] = shapePaths[index - 1];
  16122. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  16123. break;
  16124. default:
  16125. break;
  16126. }
  16127. return shapePaths;
  16128. };
  16129. var path3D;
  16130. var pathArray;
  16131. if (instance) {
  16132. path3D = (instance.path3D).update(curve);
  16133. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  16134. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  16135. return instance;
  16136. }
  16137. // extruded shape creation
  16138. path3D = new BABYLON.Path3D(curve);
  16139. var newShapePaths = new Array();
  16140. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16141. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  16142. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  16143. extrudedGeneric.pathArray = pathArray;
  16144. extrudedGeneric.path3D = path3D;
  16145. extrudedGeneric.cap = cap;
  16146. return extrudedGeneric;
  16147. };
  16148. return MeshBuilder;
  16149. })();
  16150. BABYLON.MeshBuilder = MeshBuilder;
  16151. })(BABYLON || (BABYLON = {}));
  16152. var BABYLON;
  16153. (function (BABYLON) {
  16154. var BaseTexture = (function () {
  16155. function BaseTexture(scene) {
  16156. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16157. this.hasAlpha = false;
  16158. this.getAlphaFromRGB = false;
  16159. this.level = 1;
  16160. this.isCube = false;
  16161. this.isRenderTarget = false;
  16162. this.animations = new Array();
  16163. this.coordinatesIndex = 0;
  16164. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16165. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16166. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16167. this.anisotropicFilteringLevel = 4;
  16168. this._scene = scene;
  16169. this._scene.textures.push(this);
  16170. }
  16171. BaseTexture.prototype.getScene = function () {
  16172. return this._scene;
  16173. };
  16174. BaseTexture.prototype.getTextureMatrix = function () {
  16175. return null;
  16176. };
  16177. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16178. return null;
  16179. };
  16180. BaseTexture.prototype.getInternalTexture = function () {
  16181. return this._texture;
  16182. };
  16183. BaseTexture.prototype.isReady = function () {
  16184. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16185. return true;
  16186. }
  16187. if (this._texture) {
  16188. return this._texture.isReady;
  16189. }
  16190. return false;
  16191. };
  16192. BaseTexture.prototype.getSize = function () {
  16193. if (this._texture._width) {
  16194. return { width: this._texture._width, height: this._texture._height };
  16195. }
  16196. if (this._texture._size) {
  16197. return { width: this._texture._size, height: this._texture._size };
  16198. }
  16199. return { width: 0, height: 0 };
  16200. };
  16201. BaseTexture.prototype.getBaseSize = function () {
  16202. if (!this.isReady())
  16203. return { width: 0, height: 0 };
  16204. if (this._texture._size) {
  16205. return { width: this._texture._size, height: this._texture._size };
  16206. }
  16207. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16208. };
  16209. BaseTexture.prototype.scale = function (ratio) {
  16210. };
  16211. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16212. get: function () {
  16213. return false;
  16214. },
  16215. enumerable: true,
  16216. configurable: true
  16217. });
  16218. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16219. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16220. for (var index = 0; index < texturesCache.length; index++) {
  16221. var texturesCacheEntry = texturesCache[index];
  16222. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16223. texturesCache.splice(index, 1);
  16224. return;
  16225. }
  16226. }
  16227. };
  16228. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16229. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16230. for (var index = 0; index < texturesCache.length; index++) {
  16231. var texturesCacheEntry = texturesCache[index];
  16232. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16233. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16234. texturesCacheEntry.references++;
  16235. return texturesCacheEntry;
  16236. }
  16237. }
  16238. }
  16239. return null;
  16240. };
  16241. BaseTexture.prototype.delayLoad = function () {
  16242. };
  16243. BaseTexture.prototype.clone = function () {
  16244. return null;
  16245. };
  16246. BaseTexture.prototype.releaseInternalTexture = function () {
  16247. if (this._texture) {
  16248. this._scene.getEngine().releaseInternalTexture(this._texture);
  16249. delete this._texture;
  16250. }
  16251. };
  16252. BaseTexture.prototype.dispose = function () {
  16253. // Animations
  16254. this.getScene().stopAnimation(this);
  16255. // Remove from scene
  16256. var index = this._scene.textures.indexOf(this);
  16257. if (index >= 0) {
  16258. this._scene.textures.splice(index, 1);
  16259. }
  16260. if (this._texture === undefined) {
  16261. return;
  16262. }
  16263. // Callback
  16264. if (this.onDispose) {
  16265. this.onDispose();
  16266. }
  16267. };
  16268. return BaseTexture;
  16269. })();
  16270. BABYLON.BaseTexture = BaseTexture;
  16271. })(BABYLON || (BABYLON = {}));
  16272. var BABYLON;
  16273. (function (BABYLON) {
  16274. var Texture = (function (_super) {
  16275. __extends(Texture, _super);
  16276. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16277. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16278. if (onLoad === void 0) { onLoad = null; }
  16279. if (onError === void 0) { onError = null; }
  16280. if (buffer === void 0) { buffer = null; }
  16281. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16282. _super.call(this, scene);
  16283. this.uOffset = 0;
  16284. this.vOffset = 0;
  16285. this.uScale = 1.0;
  16286. this.vScale = 1.0;
  16287. this.uAng = 0;
  16288. this.vAng = 0;
  16289. this.wAng = 0;
  16290. this.name = url;
  16291. this.url = url;
  16292. this._noMipmap = noMipmap;
  16293. this._invertY = invertY;
  16294. this._samplingMode = samplingMode;
  16295. this._buffer = buffer;
  16296. this._deleteBuffer = deleteBuffer;
  16297. if (!url) {
  16298. return;
  16299. }
  16300. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16301. if (!this._texture) {
  16302. if (!scene.useDelayedTextureLoading) {
  16303. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16304. if (deleteBuffer) {
  16305. delete this._buffer;
  16306. }
  16307. }
  16308. else {
  16309. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16310. }
  16311. }
  16312. else {
  16313. BABYLON.Tools.SetImmediate(function () {
  16314. if (onLoad) {
  16315. onLoad();
  16316. }
  16317. });
  16318. }
  16319. }
  16320. Texture.prototype.delayLoad = function () {
  16321. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16322. return;
  16323. }
  16324. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16325. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16326. if (!this._texture) {
  16327. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16328. if (this._deleteBuffer) {
  16329. delete this._buffer;
  16330. }
  16331. }
  16332. };
  16333. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16334. if (!this._texture) {
  16335. return;
  16336. }
  16337. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16338. };
  16339. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16340. x *= this.uScale;
  16341. y *= this.vScale;
  16342. x -= 0.5 * this.uScale;
  16343. y -= 0.5 * this.vScale;
  16344. z -= 0.5;
  16345. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16346. t.x += 0.5 * this.uScale + this.uOffset;
  16347. t.y += 0.5 * this.vScale + this.vOffset;
  16348. t.z += 0.5;
  16349. };
  16350. Texture.prototype.getTextureMatrix = function () {
  16351. if (this.uOffset === this._cachedUOffset &&
  16352. this.vOffset === this._cachedVOffset &&
  16353. this.uScale === this._cachedUScale &&
  16354. this.vScale === this._cachedVScale &&
  16355. this.uAng === this._cachedUAng &&
  16356. this.vAng === this._cachedVAng &&
  16357. this.wAng === this._cachedWAng) {
  16358. return this._cachedTextureMatrix;
  16359. }
  16360. this._cachedUOffset = this.uOffset;
  16361. this._cachedVOffset = this.vOffset;
  16362. this._cachedUScale = this.uScale;
  16363. this._cachedVScale = this.vScale;
  16364. this._cachedUAng = this.uAng;
  16365. this._cachedVAng = this.vAng;
  16366. this._cachedWAng = this.wAng;
  16367. if (!this._cachedTextureMatrix) {
  16368. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16369. this._rowGenerationMatrix = new BABYLON.Matrix();
  16370. this._t0 = BABYLON.Vector3.Zero();
  16371. this._t1 = BABYLON.Vector3.Zero();
  16372. this._t2 = BABYLON.Vector3.Zero();
  16373. }
  16374. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16375. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16376. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16377. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16378. this._t1.subtractInPlace(this._t0);
  16379. this._t2.subtractInPlace(this._t0);
  16380. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16381. this._cachedTextureMatrix.m[0] = this._t1.x;
  16382. this._cachedTextureMatrix.m[1] = this._t1.y;
  16383. this._cachedTextureMatrix.m[2] = this._t1.z;
  16384. this._cachedTextureMatrix.m[4] = this._t2.x;
  16385. this._cachedTextureMatrix.m[5] = this._t2.y;
  16386. this._cachedTextureMatrix.m[6] = this._t2.z;
  16387. this._cachedTextureMatrix.m[8] = this._t0.x;
  16388. this._cachedTextureMatrix.m[9] = this._t0.y;
  16389. this._cachedTextureMatrix.m[10] = this._t0.z;
  16390. return this._cachedTextureMatrix;
  16391. };
  16392. Texture.prototype.getReflectionTextureMatrix = function () {
  16393. if (this.uOffset === this._cachedUOffset &&
  16394. this.vOffset === this._cachedVOffset &&
  16395. this.uScale === this._cachedUScale &&
  16396. this.vScale === this._cachedVScale &&
  16397. this.coordinatesMode === this._cachedCoordinatesMode) {
  16398. return this._cachedTextureMatrix;
  16399. }
  16400. if (!this._cachedTextureMatrix) {
  16401. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16402. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16403. }
  16404. this._cachedCoordinatesMode = this.coordinatesMode;
  16405. switch (this.coordinatesMode) {
  16406. case Texture.PLANAR_MODE:
  16407. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16408. this._cachedTextureMatrix[0] = this.uScale;
  16409. this._cachedTextureMatrix[5] = this.vScale;
  16410. this._cachedTextureMatrix[12] = this.uOffset;
  16411. this._cachedTextureMatrix[13] = this.vOffset;
  16412. break;
  16413. case Texture.PROJECTION_MODE:
  16414. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16415. this._projectionModeMatrix.m[0] = 0.5;
  16416. this._projectionModeMatrix.m[5] = -0.5;
  16417. this._projectionModeMatrix.m[10] = 0.0;
  16418. this._projectionModeMatrix.m[12] = 0.5;
  16419. this._projectionModeMatrix.m[13] = 0.5;
  16420. this._projectionModeMatrix.m[14] = 1.0;
  16421. this._projectionModeMatrix.m[15] = 1.0;
  16422. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16423. break;
  16424. default:
  16425. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16426. break;
  16427. }
  16428. return this._cachedTextureMatrix;
  16429. };
  16430. Texture.prototype.clone = function () {
  16431. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16432. // Base texture
  16433. newTexture.hasAlpha = this.hasAlpha;
  16434. newTexture.level = this.level;
  16435. newTexture.wrapU = this.wrapU;
  16436. newTexture.wrapV = this.wrapV;
  16437. newTexture.coordinatesIndex = this.coordinatesIndex;
  16438. newTexture.coordinatesMode = this.coordinatesMode;
  16439. // Texture
  16440. newTexture.uOffset = this.uOffset;
  16441. newTexture.vOffset = this.vOffset;
  16442. newTexture.uScale = this.uScale;
  16443. newTexture.vScale = this.vScale;
  16444. newTexture.uAng = this.uAng;
  16445. newTexture.vAng = this.vAng;
  16446. newTexture.wAng = this.wAng;
  16447. return newTexture;
  16448. };
  16449. // Statics
  16450. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16451. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16452. if (onLoad === void 0) { onLoad = null; }
  16453. if (onError === void 0) { onError = null; }
  16454. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16455. };
  16456. // Constants
  16457. Texture.NEAREST_SAMPLINGMODE = 1;
  16458. Texture.BILINEAR_SAMPLINGMODE = 2;
  16459. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16460. Texture.EXPLICIT_MODE = 0;
  16461. Texture.SPHERICAL_MODE = 1;
  16462. Texture.PLANAR_MODE = 2;
  16463. Texture.CUBIC_MODE = 3;
  16464. Texture.PROJECTION_MODE = 4;
  16465. Texture.SKYBOX_MODE = 5;
  16466. Texture.INVCUBIC_MODE = 6;
  16467. Texture.EQUIRECTANGULAR_MODE = 7;
  16468. Texture.CLAMP_ADDRESSMODE = 0;
  16469. Texture.WRAP_ADDRESSMODE = 1;
  16470. Texture.MIRROR_ADDRESSMODE = 2;
  16471. return Texture;
  16472. })(BABYLON.BaseTexture);
  16473. BABYLON.Texture = Texture;
  16474. })(BABYLON || (BABYLON = {}));
  16475. var BABYLON;
  16476. (function (BABYLON) {
  16477. var CubeTexture = (function (_super) {
  16478. __extends(CubeTexture, _super);
  16479. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16480. _super.call(this, scene);
  16481. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16482. this.name = rootUrl;
  16483. this.url = rootUrl;
  16484. this._noMipmap = noMipmap;
  16485. this.hasAlpha = false;
  16486. if (!rootUrl) {
  16487. return;
  16488. }
  16489. this._texture = this._getFromCache(rootUrl, noMipmap);
  16490. if (!extensions) {
  16491. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16492. }
  16493. this._extensions = extensions;
  16494. if (!this._texture) {
  16495. if (!scene.useDelayedTextureLoading) {
  16496. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16497. }
  16498. else {
  16499. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16500. }
  16501. }
  16502. this.isCube = true;
  16503. this._textureMatrix = BABYLON.Matrix.Identity();
  16504. }
  16505. CubeTexture.prototype.clone = function () {
  16506. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16507. // Base texture
  16508. newTexture.level = this.level;
  16509. newTexture.wrapU = this.wrapU;
  16510. newTexture.wrapV = this.wrapV;
  16511. newTexture.coordinatesIndex = this.coordinatesIndex;
  16512. newTexture.coordinatesMode = this.coordinatesMode;
  16513. return newTexture;
  16514. };
  16515. // Methods
  16516. CubeTexture.prototype.delayLoad = function () {
  16517. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16518. return;
  16519. }
  16520. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16521. this._texture = this._getFromCache(this.url, this._noMipmap);
  16522. if (!this._texture) {
  16523. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16524. }
  16525. };
  16526. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16527. return this._textureMatrix;
  16528. };
  16529. return CubeTexture;
  16530. })(BABYLON.BaseTexture);
  16531. BABYLON.CubeTexture = CubeTexture;
  16532. })(BABYLON || (BABYLON = {}));
  16533. var BABYLON;
  16534. (function (BABYLON) {
  16535. var RenderTargetTexture = (function (_super) {
  16536. __extends(RenderTargetTexture, _super);
  16537. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16538. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16539. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16540. if (isCube === void 0) { isCube = false; }
  16541. _super.call(this, null, scene, !generateMipMaps);
  16542. this.isCube = isCube;
  16543. this.renderList = new Array();
  16544. this.renderParticles = true;
  16545. this.renderSprites = false;
  16546. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16547. this._currentRefreshId = -1;
  16548. this._refreshRate = 1;
  16549. this.name = name;
  16550. this.isRenderTarget = true;
  16551. this._size = size;
  16552. this._generateMipMaps = generateMipMaps;
  16553. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16554. if (isCube) {
  16555. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16556. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16557. this._textureMatrix = BABYLON.Matrix.Identity();
  16558. }
  16559. else {
  16560. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16561. }
  16562. // Rendering groups
  16563. this._renderingManager = new BABYLON.RenderingManager(scene);
  16564. }
  16565. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16566. get: function () {
  16567. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16573. get: function () {
  16574. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16575. },
  16576. enumerable: true,
  16577. configurable: true
  16578. });
  16579. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16580. get: function () {
  16581. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16582. },
  16583. enumerable: true,
  16584. configurable: true
  16585. });
  16586. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16587. this._currentRefreshId = -1;
  16588. };
  16589. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16590. get: function () {
  16591. return this._refreshRate;
  16592. },
  16593. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16594. set: function (value) {
  16595. this._refreshRate = value;
  16596. this.resetRefreshCounter();
  16597. },
  16598. enumerable: true,
  16599. configurable: true
  16600. });
  16601. RenderTargetTexture.prototype._shouldRender = function () {
  16602. if (this._currentRefreshId === -1) {
  16603. this._currentRefreshId = 1;
  16604. return true;
  16605. }
  16606. if (this.refreshRate === this._currentRefreshId) {
  16607. this._currentRefreshId = 1;
  16608. return true;
  16609. }
  16610. this._currentRefreshId++;
  16611. return false;
  16612. };
  16613. RenderTargetTexture.prototype.isReady = function () {
  16614. if (!this.getScene().renderTargetsEnabled) {
  16615. return false;
  16616. }
  16617. return _super.prototype.isReady.call(this);
  16618. };
  16619. RenderTargetTexture.prototype.getRenderSize = function () {
  16620. return this._size;
  16621. };
  16622. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16623. get: function () {
  16624. return true;
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. RenderTargetTexture.prototype.scale = function (ratio) {
  16630. var newSize = this._size * ratio;
  16631. this.resize(newSize, this._generateMipMaps);
  16632. };
  16633. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16634. if (this.isCube) {
  16635. return this._textureMatrix;
  16636. }
  16637. return _super.prototype.getReflectionTextureMatrix.call(this);
  16638. };
  16639. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16640. this.releaseInternalTexture();
  16641. if (this.isCube) {
  16642. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16643. }
  16644. else {
  16645. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16646. }
  16647. };
  16648. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16649. var scene = this.getScene();
  16650. if (this._waitingRenderList) {
  16651. this.renderList = [];
  16652. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16653. var id = this._waitingRenderList[index];
  16654. this.renderList.push(scene.getMeshByID(id));
  16655. }
  16656. delete this._waitingRenderList;
  16657. }
  16658. if (this.renderList && this.renderList.length === 0) {
  16659. return;
  16660. }
  16661. // Prepare renderingManager
  16662. this._renderingManager.reset();
  16663. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16664. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16665. var mesh = currentRenderList[meshIndex];
  16666. if (mesh) {
  16667. if (!mesh.isReady()) {
  16668. // Reset _currentRefreshId
  16669. this.resetRefreshCounter();
  16670. continue;
  16671. }
  16672. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16673. mesh._activate(scene.getRenderId());
  16674. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16675. var subMesh = mesh.subMeshes[subIndex];
  16676. scene._activeIndices += subMesh.indexCount;
  16677. this._renderingManager.dispatch(subMesh);
  16678. }
  16679. }
  16680. }
  16681. }
  16682. if (this.isCube) {
  16683. for (var face = 0; face < 6; face++) {
  16684. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16685. }
  16686. }
  16687. else {
  16688. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16689. }
  16690. if (this.onAfterUnbind) {
  16691. this.onAfterUnbind();
  16692. }
  16693. scene.resetCachedMaterial();
  16694. };
  16695. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16696. var scene = this.getScene();
  16697. var engine = scene.getEngine();
  16698. // Bind
  16699. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16700. if (this.isCube) {
  16701. engine.bindFramebuffer(this._texture, faceIndex);
  16702. }
  16703. else {
  16704. engine.bindFramebuffer(this._texture);
  16705. }
  16706. }
  16707. if (this.onBeforeRender) {
  16708. this.onBeforeRender(faceIndex);
  16709. }
  16710. // Clear
  16711. if (this.onClear) {
  16712. this.onClear(engine);
  16713. }
  16714. else {
  16715. engine.clear(scene.clearColor, true, true);
  16716. }
  16717. if (!this._doNotChangeAspectRatio) {
  16718. scene.updateTransformMatrix(true);
  16719. }
  16720. // Render
  16721. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16722. if (useCameraPostProcess) {
  16723. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16724. }
  16725. if (!this._doNotChangeAspectRatio) {
  16726. scene.updateTransformMatrix(true);
  16727. }
  16728. if (this.onAfterRender) {
  16729. this.onAfterRender(faceIndex);
  16730. }
  16731. // Dump ?
  16732. if (dumpForDebug) {
  16733. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16734. }
  16735. // Unbind
  16736. if (!this.isCube || faceIndex === 5) {
  16737. if (this.isCube) {
  16738. if (faceIndex === 5) {
  16739. engine.generateMipMapsForCubemap(this._texture);
  16740. }
  16741. }
  16742. engine.unBindFramebuffer(this._texture, this.isCube);
  16743. }
  16744. };
  16745. RenderTargetTexture.prototype.clone = function () {
  16746. var textureSize = this.getSize();
  16747. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16748. // Base texture
  16749. newTexture.hasAlpha = this.hasAlpha;
  16750. newTexture.level = this.level;
  16751. // RenderTarget Texture
  16752. newTexture.coordinatesMode = this.coordinatesMode;
  16753. newTexture.renderList = this.renderList.slice(0);
  16754. return newTexture;
  16755. };
  16756. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16757. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16758. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16759. return RenderTargetTexture;
  16760. })(BABYLON.Texture);
  16761. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16762. })(BABYLON || (BABYLON = {}));
  16763. var BABYLON;
  16764. (function (BABYLON) {
  16765. var ProceduralTexture = (function (_super) {
  16766. __extends(ProceduralTexture, _super);
  16767. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16768. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16769. _super.call(this, null, scene, !generateMipMaps);
  16770. this.isEnabled = true;
  16771. this._currentRefreshId = -1;
  16772. this._refreshRate = 1;
  16773. this._vertexDeclaration = [2];
  16774. this._vertexStrideSize = 2 * 4;
  16775. this._uniforms = new Array();
  16776. this._samplers = new Array();
  16777. this._textures = new Array();
  16778. this._floats = new Array();
  16779. this._floatsArrays = {};
  16780. this._colors3 = new Array();
  16781. this._colors4 = new Array();
  16782. this._vectors2 = new Array();
  16783. this._vectors3 = new Array();
  16784. this._matrices = new Array();
  16785. this._fallbackTextureUsed = false;
  16786. scene._proceduralTextures.push(this);
  16787. this.name = name;
  16788. this.isRenderTarget = true;
  16789. this._size = size;
  16790. this._generateMipMaps = generateMipMaps;
  16791. this.setFragment(fragment);
  16792. this._fallbackTexture = fallbackTexture;
  16793. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16794. // VBO
  16795. var vertices = [];
  16796. vertices.push(1, 1);
  16797. vertices.push(-1, 1);
  16798. vertices.push(-1, -1);
  16799. vertices.push(1, -1);
  16800. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16801. // Indices
  16802. var indices = [];
  16803. indices.push(0);
  16804. indices.push(1);
  16805. indices.push(2);
  16806. indices.push(0);
  16807. indices.push(2);
  16808. indices.push(3);
  16809. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16810. }
  16811. ProceduralTexture.prototype.reset = function () {
  16812. if (this._effect === undefined) {
  16813. return;
  16814. }
  16815. var engine = this.getScene().getEngine();
  16816. engine._releaseEffect(this._effect);
  16817. };
  16818. ProceduralTexture.prototype.isReady = function () {
  16819. var _this = this;
  16820. var engine = this.getScene().getEngine();
  16821. var shaders;
  16822. if (!this._fragment) {
  16823. return false;
  16824. }
  16825. if (this._fallbackTextureUsed) {
  16826. return true;
  16827. }
  16828. if (this._fragment.fragmentElement !== undefined) {
  16829. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16830. }
  16831. else {
  16832. shaders = { vertex: "procedural", fragment: this._fragment };
  16833. }
  16834. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16835. _this.releaseInternalTexture();
  16836. if (_this._fallbackTexture) {
  16837. _this._texture = _this._fallbackTexture._texture;
  16838. _this._texture.references++;
  16839. }
  16840. _this._fallbackTextureUsed = true;
  16841. });
  16842. return this._effect.isReady();
  16843. };
  16844. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16845. this._currentRefreshId = -1;
  16846. };
  16847. ProceduralTexture.prototype.setFragment = function (fragment) {
  16848. this._fragment = fragment;
  16849. };
  16850. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16851. get: function () {
  16852. return this._refreshRate;
  16853. },
  16854. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16855. set: function (value) {
  16856. this._refreshRate = value;
  16857. this.resetRefreshCounter();
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. ProceduralTexture.prototype._shouldRender = function () {
  16863. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16864. return false;
  16865. }
  16866. if (this._fallbackTextureUsed) {
  16867. return false;
  16868. }
  16869. if (this._currentRefreshId === -1) {
  16870. this._currentRefreshId = 1;
  16871. return true;
  16872. }
  16873. if (this.refreshRate === this._currentRefreshId) {
  16874. this._currentRefreshId = 1;
  16875. return true;
  16876. }
  16877. this._currentRefreshId++;
  16878. return false;
  16879. };
  16880. ProceduralTexture.prototype.getRenderSize = function () {
  16881. return this._size;
  16882. };
  16883. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16884. if (this._fallbackTextureUsed) {
  16885. return;
  16886. }
  16887. this.releaseInternalTexture();
  16888. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16889. };
  16890. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16891. if (this._uniforms.indexOf(uniformName) === -1) {
  16892. this._uniforms.push(uniformName);
  16893. }
  16894. };
  16895. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16896. if (this._samplers.indexOf(name) === -1) {
  16897. this._samplers.push(name);
  16898. }
  16899. this._textures[name] = texture;
  16900. return this;
  16901. };
  16902. ProceduralTexture.prototype.setFloat = function (name, value) {
  16903. this._checkUniform(name);
  16904. this._floats[name] = value;
  16905. return this;
  16906. };
  16907. ProceduralTexture.prototype.setFloats = function (name, value) {
  16908. this._checkUniform(name);
  16909. this._floatsArrays[name] = value;
  16910. return this;
  16911. };
  16912. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16913. this._checkUniform(name);
  16914. this._colors3[name] = value;
  16915. return this;
  16916. };
  16917. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16918. this._checkUniform(name);
  16919. this._colors4[name] = value;
  16920. return this;
  16921. };
  16922. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16923. this._checkUniform(name);
  16924. this._vectors2[name] = value;
  16925. return this;
  16926. };
  16927. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16928. this._checkUniform(name);
  16929. this._vectors3[name] = value;
  16930. return this;
  16931. };
  16932. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16933. this._checkUniform(name);
  16934. this._matrices[name] = value;
  16935. return this;
  16936. };
  16937. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16938. var scene = this.getScene();
  16939. var engine = scene.getEngine();
  16940. engine.bindFramebuffer(this._texture);
  16941. // Clear
  16942. engine.clear(scene.clearColor, true, true);
  16943. // Render
  16944. engine.enableEffect(this._effect);
  16945. engine.setState(false);
  16946. // Texture
  16947. for (var name in this._textures) {
  16948. this._effect.setTexture(name, this._textures[name]);
  16949. }
  16950. // Float
  16951. for (name in this._floats) {
  16952. this._effect.setFloat(name, this._floats[name]);
  16953. }
  16954. // Floats
  16955. for (name in this._floatsArrays) {
  16956. this._effect.setArray(name, this._floatsArrays[name]);
  16957. }
  16958. // Color3
  16959. for (name in this._colors3) {
  16960. this._effect.setColor3(name, this._colors3[name]);
  16961. }
  16962. // Color4
  16963. for (name in this._colors4) {
  16964. var color = this._colors4[name];
  16965. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16966. }
  16967. // Vector2
  16968. for (name in this._vectors2) {
  16969. this._effect.setVector2(name, this._vectors2[name]);
  16970. }
  16971. // Vector3
  16972. for (name in this._vectors3) {
  16973. this._effect.setVector3(name, this._vectors3[name]);
  16974. }
  16975. // Matrix
  16976. for (name in this._matrices) {
  16977. this._effect.setMatrix(name, this._matrices[name]);
  16978. }
  16979. // VBOs
  16980. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16981. // Draw order
  16982. engine.draw(true, 0, 6);
  16983. // Unbind
  16984. engine.unBindFramebuffer(this._texture);
  16985. };
  16986. ProceduralTexture.prototype.clone = function () {
  16987. var textureSize = this.getSize();
  16988. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16989. // Base texture
  16990. newTexture.hasAlpha = this.hasAlpha;
  16991. newTexture.level = this.level;
  16992. // RenderTarget Texture
  16993. newTexture.coordinatesMode = this.coordinatesMode;
  16994. return newTexture;
  16995. };
  16996. ProceduralTexture.prototype.dispose = function () {
  16997. var index = this.getScene()._proceduralTextures.indexOf(this);
  16998. if (index >= 0) {
  16999. this.getScene()._proceduralTextures.splice(index, 1);
  17000. }
  17001. _super.prototype.dispose.call(this);
  17002. };
  17003. return ProceduralTexture;
  17004. })(BABYLON.Texture);
  17005. BABYLON.ProceduralTexture = ProceduralTexture;
  17006. })(BABYLON || (BABYLON = {}));
  17007. var BABYLON;
  17008. (function (BABYLON) {
  17009. var MirrorTexture = (function (_super) {
  17010. __extends(MirrorTexture, _super);
  17011. function MirrorTexture(name, size, scene, generateMipMaps) {
  17012. var _this = this;
  17013. _super.call(this, name, size, scene, generateMipMaps, true);
  17014. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17015. this._transformMatrix = BABYLON.Matrix.Zero();
  17016. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17017. this.onBeforeRender = function () {
  17018. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17019. _this._savedViewMatrix = scene.getViewMatrix();
  17020. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17021. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17022. scene.clipPlane = _this.mirrorPlane;
  17023. scene.getEngine().cullBackFaces = false;
  17024. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  17025. };
  17026. this.onAfterRender = function () {
  17027. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17028. scene.getEngine().cullBackFaces = true;
  17029. scene._mirroredCameraPosition = null;
  17030. delete scene.clipPlane;
  17031. };
  17032. }
  17033. MirrorTexture.prototype.clone = function () {
  17034. var textureSize = this.getSize();
  17035. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17036. // Base texture
  17037. newTexture.hasAlpha = this.hasAlpha;
  17038. newTexture.level = this.level;
  17039. // Mirror Texture
  17040. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17041. newTexture.renderList = this.renderList.slice(0);
  17042. return newTexture;
  17043. };
  17044. return MirrorTexture;
  17045. })(BABYLON.RenderTargetTexture);
  17046. BABYLON.MirrorTexture = MirrorTexture;
  17047. })(BABYLON || (BABYLON = {}));
  17048. var BABYLON;
  17049. (function (BABYLON) {
  17050. var DynamicTexture = (function (_super) {
  17051. __extends(DynamicTexture, _super);
  17052. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17054. _super.call(this, null, scene, !generateMipMaps);
  17055. this.name = name;
  17056. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17057. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17058. this._generateMipMaps = generateMipMaps;
  17059. if (options.getContext) {
  17060. this._canvas = options;
  17061. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17062. }
  17063. else {
  17064. this._canvas = document.createElement("canvas");
  17065. if (options.width) {
  17066. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17067. }
  17068. else {
  17069. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17070. }
  17071. }
  17072. var textureSize = this.getSize();
  17073. this._canvas.width = textureSize.width;
  17074. this._canvas.height = textureSize.height;
  17075. this._context = this._canvas.getContext("2d");
  17076. }
  17077. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17078. get: function () {
  17079. return true;
  17080. },
  17081. enumerable: true,
  17082. configurable: true
  17083. });
  17084. DynamicTexture.prototype.scale = function (ratio) {
  17085. var textureSize = this.getSize();
  17086. textureSize.width *= ratio;
  17087. textureSize.height *= ratio;
  17088. this._canvas.width = textureSize.width;
  17089. this._canvas.height = textureSize.height;
  17090. this.releaseInternalTexture();
  17091. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17092. };
  17093. DynamicTexture.prototype.getContext = function () {
  17094. return this._context;
  17095. };
  17096. DynamicTexture.prototype.clear = function () {
  17097. var size = this.getSize();
  17098. this._context.fillRect(0, 0, size.width, size.height);
  17099. };
  17100. DynamicTexture.prototype.update = function (invertY) {
  17101. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17102. };
  17103. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17104. if (update === void 0) { update = true; }
  17105. var size = this.getSize();
  17106. if (clearColor) {
  17107. this._context.fillStyle = clearColor;
  17108. this._context.fillRect(0, 0, size.width, size.height);
  17109. }
  17110. this._context.font = font;
  17111. if (x === null) {
  17112. var textSize = this._context.measureText(text);
  17113. x = (size.width - textSize.width) / 2;
  17114. }
  17115. this._context.fillStyle = color;
  17116. this._context.fillText(text, x, y);
  17117. if (update) {
  17118. this.update(invertY);
  17119. }
  17120. };
  17121. DynamicTexture.prototype.clone = function () {
  17122. var textureSize = this.getSize();
  17123. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17124. // Base texture
  17125. newTexture.hasAlpha = this.hasAlpha;
  17126. newTexture.level = this.level;
  17127. // Dynamic Texture
  17128. newTexture.wrapU = this.wrapU;
  17129. newTexture.wrapV = this.wrapV;
  17130. return newTexture;
  17131. };
  17132. return DynamicTexture;
  17133. })(BABYLON.Texture);
  17134. BABYLON.DynamicTexture = DynamicTexture;
  17135. })(BABYLON || (BABYLON = {}));
  17136. var BABYLON;
  17137. (function (BABYLON) {
  17138. var VideoTexture = (function (_super) {
  17139. __extends(VideoTexture, _super);
  17140. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17141. var _this = this;
  17142. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17143. if (invertY === void 0) { invertY = false; }
  17144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17145. _super.call(this, null, scene, !generateMipMaps, invertY);
  17146. this._autoLaunch = true;
  17147. this.name = name;
  17148. this.video = document.createElement("video");
  17149. this.video.autoplay = false;
  17150. this.video.loop = true;
  17151. this.video.addEventListener("canplaythrough", function () {
  17152. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  17153. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17154. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17155. }
  17156. else {
  17157. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17158. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17159. generateMipMaps = false;
  17160. }
  17161. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17162. _this._texture.isReady = true;
  17163. });
  17164. urls.forEach(function (url) {
  17165. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17166. var source = document.createElement("source");
  17167. source.src = url;
  17168. _this.video.appendChild(source);
  17169. });
  17170. this._lastUpdate = BABYLON.Tools.Now;
  17171. }
  17172. VideoTexture.prototype.update = function () {
  17173. if (this._autoLaunch) {
  17174. this._autoLaunch = false;
  17175. this.video.play();
  17176. }
  17177. var now = BABYLON.Tools.Now;
  17178. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17179. return false;
  17180. }
  17181. this._lastUpdate = now;
  17182. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17183. return true;
  17184. };
  17185. return VideoTexture;
  17186. })(BABYLON.Texture);
  17187. BABYLON.VideoTexture = VideoTexture;
  17188. })(BABYLON || (BABYLON = {}));
  17189. var BABYLON;
  17190. (function (BABYLON) {
  17191. var CustomProceduralTexture = (function (_super) {
  17192. __extends(CustomProceduralTexture, _super);
  17193. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17194. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17195. this._animate = true;
  17196. this._time = 0;
  17197. this._texturePath = texturePath;
  17198. //Try to load json
  17199. this.loadJson(texturePath);
  17200. this.refreshRate = 1;
  17201. }
  17202. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17203. var _this = this;
  17204. var that = this;
  17205. function noConfigFile() {
  17206. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17207. try {
  17208. that.setFragment(that._texturePath);
  17209. }
  17210. catch (ex) {
  17211. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17212. }
  17213. }
  17214. var configFileUrl = jsonUrl + "/config.json";
  17215. var xhr = new XMLHttpRequest();
  17216. xhr.open("GET", configFileUrl, true);
  17217. xhr.addEventListener("load", function () {
  17218. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17219. try {
  17220. _this._config = JSON.parse(xhr.response);
  17221. _this.updateShaderUniforms();
  17222. _this.updateTextures();
  17223. _this.setFragment(_this._texturePath + "/custom");
  17224. _this._animate = _this._config.animate;
  17225. _this.refreshRate = _this._config.refreshrate;
  17226. }
  17227. catch (ex) {
  17228. noConfigFile();
  17229. }
  17230. }
  17231. else {
  17232. noConfigFile();
  17233. }
  17234. }, false);
  17235. xhr.addEventListener("error", function () {
  17236. noConfigFile();
  17237. }, false);
  17238. try {
  17239. xhr.send();
  17240. }
  17241. catch (ex) {
  17242. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17243. }
  17244. };
  17245. CustomProceduralTexture.prototype.isReady = function () {
  17246. if (!_super.prototype.isReady.call(this)) {
  17247. return false;
  17248. }
  17249. for (var name in this._textures) {
  17250. var texture = this._textures[name];
  17251. if (!texture.isReady()) {
  17252. return false;
  17253. }
  17254. }
  17255. return true;
  17256. };
  17257. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17258. if (this._animate) {
  17259. this._time += this.getScene().getAnimationRatio() * 0.03;
  17260. this.updateShaderUniforms();
  17261. }
  17262. _super.prototype.render.call(this, useCameraPostProcess);
  17263. };
  17264. CustomProceduralTexture.prototype.updateTextures = function () {
  17265. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17266. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17267. }
  17268. };
  17269. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17270. if (this._config) {
  17271. for (var j = 0; j < this._config.uniforms.length; j++) {
  17272. var uniform = this._config.uniforms[j];
  17273. switch (uniform.type) {
  17274. case "float":
  17275. this.setFloat(uniform.name, uniform.value);
  17276. break;
  17277. case "color3":
  17278. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17279. break;
  17280. case "color4":
  17281. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17282. break;
  17283. case "vector2":
  17284. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17285. break;
  17286. case "vector3":
  17287. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17288. break;
  17289. }
  17290. }
  17291. }
  17292. this.setFloat("time", this._time);
  17293. };
  17294. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17295. get: function () {
  17296. return this._animate;
  17297. },
  17298. set: function (value) {
  17299. this._animate = value;
  17300. },
  17301. enumerable: true,
  17302. configurable: true
  17303. });
  17304. return CustomProceduralTexture;
  17305. })(BABYLON.ProceduralTexture);
  17306. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17307. })(BABYLON || (BABYLON = {}));
  17308. var BABYLON;
  17309. (function (BABYLON) {
  17310. var WoodProceduralTexture = (function (_super) {
  17311. __extends(WoodProceduralTexture, _super);
  17312. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17313. _super.call(this, name, size, "woodtexture", scene, fallbackTexture, generateMipMaps);
  17314. this._ampScale = 100.0;
  17315. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17316. this.updateShaderUniforms();
  17317. this.refreshRate = 0;
  17318. }
  17319. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17320. this.setFloat("ampScale", this._ampScale);
  17321. this.setColor3("woodColor", this._woodColor);
  17322. };
  17323. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17324. get: function () {
  17325. return this._ampScale;
  17326. },
  17327. set: function (value) {
  17328. this._ampScale = value;
  17329. this.updateShaderUniforms();
  17330. },
  17331. enumerable: true,
  17332. configurable: true
  17333. });
  17334. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17335. get: function () {
  17336. return this._woodColor;
  17337. },
  17338. set: function (value) {
  17339. this._woodColor = value;
  17340. this.updateShaderUniforms();
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. return WoodProceduralTexture;
  17346. })(BABYLON.ProceduralTexture);
  17347. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17348. var FireProceduralTexture = (function (_super) {
  17349. __extends(FireProceduralTexture, _super);
  17350. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17351. _super.call(this, name, size, "firetexture", scene, fallbackTexture, generateMipMaps);
  17352. this._time = 0.0;
  17353. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17354. this._autoGenerateTime = true;
  17355. this._alphaThreshold = 0.5;
  17356. this._fireColors = FireProceduralTexture.RedFireColors;
  17357. this.updateShaderUniforms();
  17358. this.refreshRate = 1;
  17359. }
  17360. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17361. this.setFloat("time", this._time);
  17362. this.setVector2("speed", this._speed);
  17363. this.setColor3("c1", this._fireColors[0]);
  17364. this.setColor3("c2", this._fireColors[1]);
  17365. this.setColor3("c3", this._fireColors[2]);
  17366. this.setColor3("c4", this._fireColors[3]);
  17367. this.setColor3("c5", this._fireColors[4]);
  17368. this.setColor3("c6", this._fireColors[5]);
  17369. this.setFloat("alphaThreshold", this._alphaThreshold);
  17370. };
  17371. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17372. if (this._autoGenerateTime) {
  17373. this._time += this.getScene().getAnimationRatio() * 0.03;
  17374. this.updateShaderUniforms();
  17375. }
  17376. _super.prototype.render.call(this, useCameraPostProcess);
  17377. };
  17378. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17379. get: function () {
  17380. return [
  17381. new BABYLON.Color3(0.5, 0.0, 1.0),
  17382. new BABYLON.Color3(0.9, 0.0, 1.0),
  17383. new BABYLON.Color3(0.2, 0.0, 1.0),
  17384. new BABYLON.Color3(1.0, 0.9, 1.0),
  17385. new BABYLON.Color3(0.1, 0.1, 1.0),
  17386. new BABYLON.Color3(0.9, 0.9, 1.0)
  17387. ];
  17388. },
  17389. enumerable: true,
  17390. configurable: true
  17391. });
  17392. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17393. get: function () {
  17394. return [
  17395. new BABYLON.Color3(0.5, 1.0, 0.0),
  17396. new BABYLON.Color3(0.5, 1.0, 0.0),
  17397. new BABYLON.Color3(0.3, 0.4, 0.0),
  17398. new BABYLON.Color3(0.5, 1.0, 0.0),
  17399. new BABYLON.Color3(0.2, 0.0, 0.0),
  17400. new BABYLON.Color3(0.5, 1.0, 0.0)
  17401. ];
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17407. get: function () {
  17408. return [
  17409. new BABYLON.Color3(0.5, 0.0, 0.1),
  17410. new BABYLON.Color3(0.9, 0.0, 0.0),
  17411. new BABYLON.Color3(0.2, 0.0, 0.0),
  17412. new BABYLON.Color3(1.0, 0.9, 0.0),
  17413. new BABYLON.Color3(0.1, 0.1, 0.1),
  17414. new BABYLON.Color3(0.9, 0.9, 0.9)
  17415. ];
  17416. },
  17417. enumerable: true,
  17418. configurable: true
  17419. });
  17420. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17421. get: function () {
  17422. return [
  17423. new BABYLON.Color3(0.1, 0.0, 0.5),
  17424. new BABYLON.Color3(0.0, 0.0, 0.5),
  17425. new BABYLON.Color3(0.1, 0.0, 0.2),
  17426. new BABYLON.Color3(0.0, 0.0, 1.0),
  17427. new BABYLON.Color3(0.1, 0.2, 0.3),
  17428. new BABYLON.Color3(0.0, 0.2, 0.9)
  17429. ];
  17430. },
  17431. enumerable: true,
  17432. configurable: true
  17433. });
  17434. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17435. get: function () {
  17436. return this._fireColors;
  17437. },
  17438. set: function (value) {
  17439. this._fireColors = value;
  17440. this.updateShaderUniforms();
  17441. },
  17442. enumerable: true,
  17443. configurable: true
  17444. });
  17445. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17446. get: function () {
  17447. return this._time;
  17448. },
  17449. set: function (value) {
  17450. this._time = value;
  17451. this.updateShaderUniforms();
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17457. get: function () {
  17458. return this._speed;
  17459. },
  17460. set: function (value) {
  17461. this._speed = value;
  17462. this.updateShaderUniforms();
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17468. get: function () {
  17469. return this._alphaThreshold;
  17470. },
  17471. set: function (value) {
  17472. this._alphaThreshold = value;
  17473. this.updateShaderUniforms();
  17474. },
  17475. enumerable: true,
  17476. configurable: true
  17477. });
  17478. return FireProceduralTexture;
  17479. })(BABYLON.ProceduralTexture);
  17480. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17481. var CloudProceduralTexture = (function (_super) {
  17482. __extends(CloudProceduralTexture, _super);
  17483. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17484. _super.call(this, name, size, "cloudtexture", scene, fallbackTexture, generateMipMaps);
  17485. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17486. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17487. this.updateShaderUniforms();
  17488. this.refreshRate = 0;
  17489. }
  17490. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17491. this.setColor4("skyColor", this._skyColor);
  17492. this.setColor4("cloudColor", this._cloudColor);
  17493. };
  17494. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17495. get: function () {
  17496. return this._skyColor;
  17497. },
  17498. set: function (value) {
  17499. this._skyColor = value;
  17500. this.updateShaderUniforms();
  17501. },
  17502. enumerable: true,
  17503. configurable: true
  17504. });
  17505. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17506. get: function () {
  17507. return this._cloudColor;
  17508. },
  17509. set: function (value) {
  17510. this._cloudColor = value;
  17511. this.updateShaderUniforms();
  17512. },
  17513. enumerable: true,
  17514. configurable: true
  17515. });
  17516. return CloudProceduralTexture;
  17517. })(BABYLON.ProceduralTexture);
  17518. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17519. var GrassProceduralTexture = (function (_super) {
  17520. __extends(GrassProceduralTexture, _super);
  17521. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17522. _super.call(this, name, size, "grasstexture", scene, fallbackTexture, generateMipMaps);
  17523. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17524. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17525. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17526. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17527. this._grassColors = [
  17528. new BABYLON.Color3(0.29, 0.38, 0.02),
  17529. new BABYLON.Color3(0.36, 0.49, 0.09),
  17530. new BABYLON.Color3(0.51, 0.6, 0.28)
  17531. ];
  17532. this.updateShaderUniforms();
  17533. this.refreshRate = 0;
  17534. }
  17535. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17536. this.setColor3("herb1Color", this._grassColors[0]);
  17537. this.setColor3("herb2Color", this._grassColors[1]);
  17538. this.setColor3("herb3Color", this._grassColors[2]);
  17539. this.setColor3("groundColor", this._groundColor);
  17540. };
  17541. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17542. get: function () {
  17543. return this._grassColors;
  17544. },
  17545. set: function (value) {
  17546. this._grassColors = value;
  17547. this.updateShaderUniforms();
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17553. get: function () {
  17554. return this._groundColor;
  17555. },
  17556. set: function (value) {
  17557. this.groundColor = value;
  17558. this.updateShaderUniforms();
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. return GrassProceduralTexture;
  17564. })(BABYLON.ProceduralTexture);
  17565. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17566. var RoadProceduralTexture = (function (_super) {
  17567. __extends(RoadProceduralTexture, _super);
  17568. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17569. _super.call(this, name, size, "roadtexture", scene, fallbackTexture, generateMipMaps);
  17570. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17571. this.updateShaderUniforms();
  17572. this.refreshRate = 0;
  17573. }
  17574. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17575. this.setColor3("roadColor", this._roadColor);
  17576. };
  17577. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17578. get: function () {
  17579. return this._roadColor;
  17580. },
  17581. set: function (value) {
  17582. this._roadColor = value;
  17583. this.updateShaderUniforms();
  17584. },
  17585. enumerable: true,
  17586. configurable: true
  17587. });
  17588. return RoadProceduralTexture;
  17589. })(BABYLON.ProceduralTexture);
  17590. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17591. var BrickProceduralTexture = (function (_super) {
  17592. __extends(BrickProceduralTexture, _super);
  17593. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17594. _super.call(this, name, size, "bricktexture", scene, fallbackTexture, generateMipMaps);
  17595. this._numberOfBricksHeight = 15;
  17596. this._numberOfBricksWidth = 5;
  17597. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17598. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17599. this.updateShaderUniforms();
  17600. this.refreshRate = 0;
  17601. }
  17602. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17603. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17604. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17605. this.setColor3("brickColor", this._brickColor);
  17606. this.setColor3("jointColor", this._jointColor);
  17607. };
  17608. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17609. get: function () {
  17610. return this._numberOfBricksHeight;
  17611. },
  17612. set: function (value) {
  17613. this._numberOfBricksHeight = value;
  17614. this.updateShaderUniforms();
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17620. get: function () {
  17621. return this._numberOfBricksWidth;
  17622. },
  17623. set: function (value) {
  17624. this._numberOfBricksWidth = value;
  17625. this.updateShaderUniforms();
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17631. get: function () {
  17632. return this._jointColor;
  17633. },
  17634. set: function (value) {
  17635. this._jointColor = value;
  17636. this.updateShaderUniforms();
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17642. get: function () {
  17643. return this._brickColor;
  17644. },
  17645. set: function (value) {
  17646. this._brickColor = value;
  17647. this.updateShaderUniforms();
  17648. },
  17649. enumerable: true,
  17650. configurable: true
  17651. });
  17652. return BrickProceduralTexture;
  17653. })(BABYLON.ProceduralTexture);
  17654. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17655. var MarbleProceduralTexture = (function (_super) {
  17656. __extends(MarbleProceduralTexture, _super);
  17657. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17658. _super.call(this, name, size, "marbletexture", scene, fallbackTexture, generateMipMaps);
  17659. this._numberOfTilesHeight = 3;
  17660. this._numberOfTilesWidth = 3;
  17661. this._amplitude = 9.0;
  17662. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17663. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17664. this.updateShaderUniforms();
  17665. this.refreshRate = 0;
  17666. }
  17667. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17668. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17669. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17670. this.setFloat("amplitude", this._amplitude);
  17671. this.setColor3("marbleColor", this._marbleColor);
  17672. this.setColor3("jointColor", this._jointColor);
  17673. };
  17674. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17675. get: function () {
  17676. return this._numberOfTilesHeight;
  17677. },
  17678. set: function (value) {
  17679. this._numberOfTilesHeight = value;
  17680. this.updateShaderUniforms();
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17686. get: function () {
  17687. return this._numberOfTilesWidth;
  17688. },
  17689. set: function (value) {
  17690. this._numberOfTilesWidth = value;
  17691. this.updateShaderUniforms();
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17697. get: function () {
  17698. return this._jointColor;
  17699. },
  17700. set: function (value) {
  17701. this._jointColor = value;
  17702. this.updateShaderUniforms();
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17708. get: function () {
  17709. return this._marbleColor;
  17710. },
  17711. set: function (value) {
  17712. this._marbleColor = value;
  17713. this.updateShaderUniforms();
  17714. },
  17715. enumerable: true,
  17716. configurable: true
  17717. });
  17718. return MarbleProceduralTexture;
  17719. })(BABYLON.ProceduralTexture);
  17720. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17721. })(BABYLON || (BABYLON = {}));
  17722. var BABYLON;
  17723. (function (BABYLON) {
  17724. var EffectFallbacks = (function () {
  17725. function EffectFallbacks() {
  17726. this._defines = {};
  17727. this._currentRank = 32;
  17728. this._maxRank = -1;
  17729. }
  17730. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17731. if (!this._defines[rank]) {
  17732. if (rank < this._currentRank) {
  17733. this._currentRank = rank;
  17734. }
  17735. if (rank > this._maxRank) {
  17736. this._maxRank = rank;
  17737. }
  17738. this._defines[rank] = new Array();
  17739. }
  17740. this._defines[rank].push(define);
  17741. };
  17742. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  17743. this._meshRank = rank;
  17744. this._mesh = mesh;
  17745. if (rank > this._maxRank) {
  17746. this._maxRank = rank;
  17747. }
  17748. };
  17749. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17750. get: function () {
  17751. return this._currentRank <= this._maxRank;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17757. var currentFallbacks = this._defines[this._currentRank];
  17758. for (var index = 0; index < currentFallbacks.length; index++) {
  17759. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17760. }
  17761. if (this._mesh && this._currentRank === this._meshRank) {
  17762. this._mesh.computeBonesUsingShaders = false;
  17763. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  17764. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  17765. }
  17766. this._currentRank++;
  17767. return currentDefines;
  17768. };
  17769. return EffectFallbacks;
  17770. })();
  17771. BABYLON.EffectFallbacks = EffectFallbacks;
  17772. var Effect = (function () {
  17773. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17774. var _this = this;
  17775. this._isReady = false;
  17776. this._compilationError = "";
  17777. this._valueCache = [];
  17778. this._engine = engine;
  17779. this.name = baseName;
  17780. this.defines = defines;
  17781. this._uniformsNames = uniformsNames.concat(samplers);
  17782. this._samplers = samplers;
  17783. this._attributesNames = attributesNames;
  17784. this.onError = onError;
  17785. this.onCompiled = onCompiled;
  17786. var vertexSource;
  17787. var fragmentSource;
  17788. if (baseName.vertexElement) {
  17789. vertexSource = document.getElementById(baseName.vertexElement);
  17790. if (!vertexSource) {
  17791. vertexSource = baseName.vertexElement;
  17792. }
  17793. }
  17794. else {
  17795. vertexSource = baseName.vertex || baseName;
  17796. }
  17797. if (baseName.fragmentElement) {
  17798. fragmentSource = document.getElementById(baseName.fragmentElement);
  17799. if (!fragmentSource) {
  17800. fragmentSource = baseName.fragmentElement;
  17801. }
  17802. }
  17803. else {
  17804. fragmentSource = baseName.fragment || baseName;
  17805. }
  17806. this._loadVertexShader(vertexSource, function (vertexCode) {
  17807. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17808. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17809. });
  17810. });
  17811. }
  17812. // Properties
  17813. Effect.prototype.isReady = function () {
  17814. return this._isReady;
  17815. };
  17816. Effect.prototype.getProgram = function () {
  17817. return this._program;
  17818. };
  17819. Effect.prototype.getAttributesNames = function () {
  17820. return this._attributesNames;
  17821. };
  17822. Effect.prototype.getAttributeLocation = function (index) {
  17823. return this._attributes[index];
  17824. };
  17825. Effect.prototype.getAttributeLocationByName = function (name) {
  17826. var index = this._attributesNames.indexOf(name);
  17827. return this._attributes[index];
  17828. };
  17829. Effect.prototype.getAttributesCount = function () {
  17830. return this._attributes.length;
  17831. };
  17832. Effect.prototype.getUniformIndex = function (uniformName) {
  17833. return this._uniformsNames.indexOf(uniformName);
  17834. };
  17835. Effect.prototype.getUniform = function (uniformName) {
  17836. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17837. };
  17838. Effect.prototype.getSamplers = function () {
  17839. return this._samplers;
  17840. };
  17841. Effect.prototype.getCompilationError = function () {
  17842. return this._compilationError;
  17843. };
  17844. // Methods
  17845. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17846. // DOM element ?
  17847. if (vertex instanceof HTMLElement) {
  17848. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17849. callback(vertexCode);
  17850. return;
  17851. }
  17852. // Is in local store ?
  17853. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17854. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17855. return;
  17856. }
  17857. var vertexShaderUrl;
  17858. if (vertex[0] === "." || vertex[0] === "/") {
  17859. vertexShaderUrl = vertex;
  17860. }
  17861. else {
  17862. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17863. }
  17864. // Vertex shader
  17865. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17866. };
  17867. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17868. // DOM element ?
  17869. if (fragment instanceof HTMLElement) {
  17870. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17871. callback(fragmentCode);
  17872. return;
  17873. }
  17874. // Is in local store ?
  17875. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17876. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17877. return;
  17878. }
  17879. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17880. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17881. return;
  17882. }
  17883. var fragmentShaderUrl;
  17884. if (fragment[0] === "." || fragment[0] === "/") {
  17885. fragmentShaderUrl = fragment;
  17886. }
  17887. else {
  17888. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17889. }
  17890. // Fragment shader
  17891. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17892. };
  17893. Effect.prototype._dumpShadersName = function () {
  17894. if (this.name.vertexElement) {
  17895. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17896. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17897. }
  17898. else if (this.name.vertex) {
  17899. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17900. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17901. }
  17902. else {
  17903. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17904. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17905. }
  17906. };
  17907. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17908. try {
  17909. var engine = this._engine;
  17910. if (!engine.getCaps().highPrecisionShaderSupported) {
  17911. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17912. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17913. }
  17914. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17915. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17916. this._attributes = engine.getAttributes(this._program, attributesNames);
  17917. for (var index = 0; index < this._samplers.length; index++) {
  17918. var sampler = this.getUniform(this._samplers[index]);
  17919. if (sampler == null) {
  17920. this._samplers.splice(index, 1);
  17921. index--;
  17922. }
  17923. }
  17924. engine.bindSamplers(this);
  17925. this._isReady = true;
  17926. if (this.onCompiled) {
  17927. this.onCompiled(this);
  17928. }
  17929. }
  17930. catch (e) {
  17931. // Is it a problem with precision?
  17932. if (e.message.indexOf("highp") !== -1) {
  17933. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17934. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17935. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17936. return;
  17937. }
  17938. // Let's go through fallbacks then
  17939. if (fallbacks && fallbacks.isMoreFallbacks) {
  17940. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  17941. this._dumpShadersName();
  17942. defines = fallbacks.reduce(defines);
  17943. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17944. }
  17945. else {
  17946. BABYLON.Tools.Error("Unable to compile effect: ");
  17947. this._dumpShadersName();
  17948. BABYLON.Tools.Error("Defines: " + defines);
  17949. BABYLON.Tools.Error("Error: " + e.message);
  17950. this._compilationError = e.message;
  17951. if (this.onError) {
  17952. this.onError(this, this._compilationError);
  17953. }
  17954. }
  17955. }
  17956. };
  17957. Object.defineProperty(Effect.prototype, "isSupported", {
  17958. get: function () {
  17959. return this._compilationError === "";
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Effect.prototype._bindTexture = function (channel, texture) {
  17965. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17966. };
  17967. Effect.prototype.setTexture = function (channel, texture) {
  17968. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17969. };
  17970. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17971. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17972. };
  17973. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17974. if (!this._valueCache[uniformName]) {
  17975. this._valueCache[uniformName] = new BABYLON.Matrix();
  17976. }
  17977. for (var index = 0; index < 16; index++) {
  17978. this._valueCache[uniformName].m[index] = matrix.m[index];
  17979. }
  17980. };
  17981. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17982. if (!this._valueCache[uniformName]) {
  17983. this._valueCache[uniformName] = [x, y];
  17984. return;
  17985. }
  17986. this._valueCache[uniformName][0] = x;
  17987. this._valueCache[uniformName][1] = y;
  17988. };
  17989. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17990. if (!this._valueCache[uniformName]) {
  17991. this._valueCache[uniformName] = [x, y, z];
  17992. return;
  17993. }
  17994. this._valueCache[uniformName][0] = x;
  17995. this._valueCache[uniformName][1] = y;
  17996. this._valueCache[uniformName][2] = z;
  17997. };
  17998. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17999. if (!this._valueCache[uniformName]) {
  18000. this._valueCache[uniformName] = [x, y, z, w];
  18001. return;
  18002. }
  18003. this._valueCache[uniformName][0] = x;
  18004. this._valueCache[uniformName][1] = y;
  18005. this._valueCache[uniformName][2] = z;
  18006. this._valueCache[uniformName][3] = w;
  18007. };
  18008. Effect.prototype.setArray = function (uniformName, array) {
  18009. this._engine.setArray(this.getUniform(uniformName), array);
  18010. return this;
  18011. };
  18012. Effect.prototype.setArray2 = function (uniformName, array) {
  18013. this._engine.setArray2(this.getUniform(uniformName), array);
  18014. return this;
  18015. };
  18016. Effect.prototype.setArray3 = function (uniformName, array) {
  18017. this._engine.setArray3(this.getUniform(uniformName), array);
  18018. return this;
  18019. };
  18020. Effect.prototype.setArray4 = function (uniformName, array) {
  18021. this._engine.setArray4(this.getUniform(uniformName), array);
  18022. return this;
  18023. };
  18024. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18025. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18026. return this;
  18027. };
  18028. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18029. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18030. return this;
  18031. this._cacheMatrix(uniformName, matrix);
  18032. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18033. return this;
  18034. };
  18035. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18036. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18037. return this;
  18038. };
  18039. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18040. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18041. return this;
  18042. };
  18043. Effect.prototype.setFloat = function (uniformName, value) {
  18044. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18045. return this;
  18046. this._valueCache[uniformName] = value;
  18047. this._engine.setFloat(this.getUniform(uniformName), value);
  18048. return this;
  18049. };
  18050. Effect.prototype.setBool = function (uniformName, bool) {
  18051. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18052. return this;
  18053. this._valueCache[uniformName] = bool;
  18054. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18055. return this;
  18056. };
  18057. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18058. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18059. return this;
  18060. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18061. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18062. return this;
  18063. };
  18064. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18065. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18066. return this;
  18067. this._cacheFloat2(uniformName, x, y);
  18068. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18069. return this;
  18070. };
  18071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18072. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18073. return this;
  18074. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18075. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18076. return this;
  18077. };
  18078. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18079. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18080. return this;
  18081. this._cacheFloat3(uniformName, x, y, z);
  18082. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18083. return this;
  18084. };
  18085. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18086. 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)
  18087. return this;
  18088. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18089. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18090. return this;
  18091. };
  18092. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18093. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18094. return this;
  18095. this._cacheFloat4(uniformName, x, y, z, w);
  18096. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18097. return this;
  18098. };
  18099. Effect.prototype.setColor3 = function (uniformName, color3) {
  18100. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18101. return this;
  18102. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18103. this._engine.setColor3(this.getUniform(uniformName), color3);
  18104. return this;
  18105. };
  18106. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18107. 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)
  18108. return this;
  18109. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18110. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18111. return this;
  18112. };
  18113. // Statics
  18114. Effect.ShadersStore = {};
  18115. return Effect;
  18116. })();
  18117. BABYLON.Effect = Effect;
  18118. })(BABYLON || (BABYLON = {}));
  18119. var BABYLON;
  18120. (function (BABYLON) {
  18121. var MaterialDefines = (function () {
  18122. function MaterialDefines() {
  18123. }
  18124. MaterialDefines.prototype.isEqual = function (other) {
  18125. for (var index = 0; index < this._keys.length; index++) {
  18126. var prop = this._keys[index];
  18127. if (this[prop] !== other[prop]) {
  18128. return false;
  18129. }
  18130. }
  18131. return true;
  18132. };
  18133. MaterialDefines.prototype.cloneTo = function (other) {
  18134. for (var index = 0; index < this._keys.length; index++) {
  18135. var prop = this._keys[index];
  18136. other[prop] = this[prop];
  18137. }
  18138. };
  18139. MaterialDefines.prototype.reset = function () {
  18140. for (var index = 0; index < this._keys.length; index++) {
  18141. var prop = this._keys[index];
  18142. if (typeof (this[prop]) === "number") {
  18143. this[prop] = 0;
  18144. }
  18145. else {
  18146. this[prop] = false;
  18147. }
  18148. }
  18149. };
  18150. MaterialDefines.prototype.toString = function () {
  18151. var result = "";
  18152. for (var index = 0; index < this._keys.length; index++) {
  18153. var prop = this._keys[index];
  18154. if (typeof (this[prop]) === "number") {
  18155. result += "#define " + prop + " " + this[prop] + "\n";
  18156. }
  18157. else if (this[prop]) {
  18158. result += "#define " + prop + "\n";
  18159. }
  18160. }
  18161. return result;
  18162. };
  18163. return MaterialDefines;
  18164. })();
  18165. BABYLON.MaterialDefines = MaterialDefines;
  18166. var Material = (function () {
  18167. function Material(name, scene, doNotAdd) {
  18168. this.name = name;
  18169. this.checkReadyOnEveryCall = false;
  18170. this.checkReadyOnlyOnce = false;
  18171. this.state = "";
  18172. this.alpha = 1.0;
  18173. this.backFaceCulling = true;
  18174. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  18175. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18176. this.disableDepthWrite = false;
  18177. this.fogEnabled = true;
  18178. this._wasPreviouslyReady = false;
  18179. this._fillMode = Material.TriangleFillMode;
  18180. this.pointSize = 1.0;
  18181. this.zOffset = 0;
  18182. this.id = name;
  18183. this._scene = scene;
  18184. if (!doNotAdd) {
  18185. scene.materials.push(this);
  18186. }
  18187. }
  18188. Object.defineProperty(Material, "TriangleFillMode", {
  18189. get: function () {
  18190. return Material._TriangleFillMode;
  18191. },
  18192. enumerable: true,
  18193. configurable: true
  18194. });
  18195. Object.defineProperty(Material, "WireFrameFillMode", {
  18196. get: function () {
  18197. return Material._WireFrameFillMode;
  18198. },
  18199. enumerable: true,
  18200. configurable: true
  18201. });
  18202. Object.defineProperty(Material, "PointFillMode", {
  18203. get: function () {
  18204. return Material._PointFillMode;
  18205. },
  18206. enumerable: true,
  18207. configurable: true
  18208. });
  18209. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  18210. get: function () {
  18211. return Material._ClockWiseSideOrientation;
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  18217. get: function () {
  18218. return Material._CounterClockWiseSideOrientation;
  18219. },
  18220. enumerable: true,
  18221. configurable: true
  18222. });
  18223. Object.defineProperty(Material.prototype, "wireframe", {
  18224. get: function () {
  18225. return this._fillMode === Material.WireFrameFillMode;
  18226. },
  18227. set: function (value) {
  18228. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Object.defineProperty(Material.prototype, "pointsCloud", {
  18234. get: function () {
  18235. return this._fillMode === Material.PointFillMode;
  18236. },
  18237. set: function (value) {
  18238. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18239. },
  18240. enumerable: true,
  18241. configurable: true
  18242. });
  18243. Object.defineProperty(Material.prototype, "fillMode", {
  18244. get: function () {
  18245. return this._fillMode;
  18246. },
  18247. set: function (value) {
  18248. this._fillMode = value;
  18249. },
  18250. enumerable: true,
  18251. configurable: true
  18252. });
  18253. Material.prototype.isReady = function (mesh, useInstances) {
  18254. return true;
  18255. };
  18256. Material.prototype.getEffect = function () {
  18257. return this._effect;
  18258. };
  18259. Material.prototype.getScene = function () {
  18260. return this._scene;
  18261. };
  18262. Material.prototype.needAlphaBlending = function () {
  18263. return (this.alpha < 1.0);
  18264. };
  18265. Material.prototype.needAlphaTesting = function () {
  18266. return false;
  18267. };
  18268. Material.prototype.getAlphaTestTexture = function () {
  18269. return null;
  18270. };
  18271. Material.prototype.trackCreation = function (onCompiled, onError) {
  18272. };
  18273. Material.prototype.markDirty = function () {
  18274. this._wasPreviouslyReady = false;
  18275. };
  18276. Material.prototype._preBind = function () {
  18277. var engine = this._scene.getEngine();
  18278. engine.enableEffect(this._effect);
  18279. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18280. };
  18281. Material.prototype.bind = function (world, mesh) {
  18282. this._scene._cachedMaterial = this;
  18283. if (this.onBind) {
  18284. this.onBind(this, mesh);
  18285. }
  18286. if (this.disableDepthWrite) {
  18287. var engine = this._scene.getEngine();
  18288. this._cachedDepthWriteState = engine.getDepthWrite();
  18289. engine.setDepthWrite(false);
  18290. }
  18291. };
  18292. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18293. };
  18294. Material.prototype.unbind = function () {
  18295. if (this.disableDepthWrite) {
  18296. var engine = this._scene.getEngine();
  18297. engine.setDepthWrite(this._cachedDepthWriteState);
  18298. }
  18299. };
  18300. Material.prototype.clone = function (name) {
  18301. return null;
  18302. };
  18303. Material.prototype.getBindedMeshes = function () {
  18304. var result = new Array();
  18305. for (var index = 0; index < this._scene.meshes.length; index++) {
  18306. var mesh = this._scene.meshes[index];
  18307. if (mesh.material === this) {
  18308. result.push(mesh);
  18309. }
  18310. }
  18311. return result;
  18312. };
  18313. Material.prototype.dispose = function (forceDisposeEffect) {
  18314. // Animations
  18315. this.getScene().stopAnimation(this);
  18316. // Remove from scene
  18317. var index = this._scene.materials.indexOf(this);
  18318. if (index >= 0) {
  18319. this._scene.materials.splice(index, 1);
  18320. }
  18321. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18322. if (forceDisposeEffect && this._effect) {
  18323. this._scene.getEngine()._releaseEffect(this._effect);
  18324. this._effect = null;
  18325. }
  18326. // Remove from meshes
  18327. for (index = 0; index < this._scene.meshes.length; index++) {
  18328. var mesh = this._scene.meshes[index];
  18329. if (mesh.material === this) {
  18330. mesh.material = null;
  18331. }
  18332. }
  18333. // Callback
  18334. if (this.onDispose) {
  18335. this.onDispose();
  18336. }
  18337. };
  18338. Material.prototype.copyTo = function (other) {
  18339. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18340. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18341. other.alpha = this.alpha;
  18342. other.fillMode = this.fillMode;
  18343. other.backFaceCulling = this.backFaceCulling;
  18344. other.wireframe = this.wireframe;
  18345. other.fogEnabled = this.fogEnabled;
  18346. other.wireframe = this.wireframe;
  18347. other.zOffset = this.zOffset;
  18348. other.alphaMode = this.alphaMode;
  18349. other.sideOrientation = this.sideOrientation;
  18350. other.disableDepthWrite = this.disableDepthWrite;
  18351. other.pointSize = this.pointSize;
  18352. other.pointsCloud = this.pointsCloud;
  18353. };
  18354. Material._TriangleFillMode = 0;
  18355. Material._WireFrameFillMode = 1;
  18356. Material._PointFillMode = 2;
  18357. Material._ClockWiseSideOrientation = 0;
  18358. Material._CounterClockWiseSideOrientation = 1;
  18359. return Material;
  18360. })();
  18361. BABYLON.Material = Material;
  18362. })(BABYLON || (BABYLON = {}));
  18363. var BABYLON;
  18364. (function (BABYLON) {
  18365. var maxSimultaneousLights = 4;
  18366. var FresnelParameters = (function () {
  18367. function FresnelParameters() {
  18368. this.isEnabled = true;
  18369. this.leftColor = BABYLON.Color3.White();
  18370. this.rightColor = BABYLON.Color3.Black();
  18371. this.bias = 0;
  18372. this.power = 1;
  18373. }
  18374. FresnelParameters.prototype.clone = function () {
  18375. var newFresnelParameters = new FresnelParameters();
  18376. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18377. return new FresnelParameters;
  18378. };
  18379. return FresnelParameters;
  18380. })();
  18381. BABYLON.FresnelParameters = FresnelParameters;
  18382. var StandardMaterialDefines = (function (_super) {
  18383. __extends(StandardMaterialDefines, _super);
  18384. function StandardMaterialDefines() {
  18385. _super.call(this);
  18386. this.DIFFUSE = false;
  18387. this.AMBIENT = false;
  18388. this.OPACITY = false;
  18389. this.OPACITYRGB = false;
  18390. this.REFLECTION = false;
  18391. this.EMISSIVE = false;
  18392. this.SPECULAR = false;
  18393. this.BUMP = false;
  18394. this.SPECULAROVERALPHA = false;
  18395. this.CLIPPLANE = false;
  18396. this.ALPHATEST = false;
  18397. this.ALPHAFROMDIFFUSE = false;
  18398. this.POINTSIZE = false;
  18399. this.FOG = false;
  18400. this.LIGHT0 = false;
  18401. this.LIGHT1 = false;
  18402. this.LIGHT2 = false;
  18403. this.LIGHT3 = false;
  18404. this.SPOTLIGHT0 = false;
  18405. this.SPOTLIGHT1 = false;
  18406. this.SPOTLIGHT2 = false;
  18407. this.SPOTLIGHT3 = false;
  18408. this.HEMILIGHT0 = false;
  18409. this.HEMILIGHT1 = false;
  18410. this.HEMILIGHT2 = false;
  18411. this.HEMILIGHT3 = false;
  18412. this.POINTLIGHT0 = false;
  18413. this.POINTLIGHT1 = false;
  18414. this.POINTLIGHT2 = false;
  18415. this.POINTLIGHT3 = false;
  18416. this.DIRLIGHT0 = false;
  18417. this.DIRLIGHT1 = false;
  18418. this.DIRLIGHT2 = false;
  18419. this.DIRLIGHT3 = false;
  18420. this.SPECULARTERM = false;
  18421. this.SHADOW0 = false;
  18422. this.SHADOW1 = false;
  18423. this.SHADOW2 = false;
  18424. this.SHADOW3 = false;
  18425. this.SHADOWS = false;
  18426. this.SHADOWVSM0 = false;
  18427. this.SHADOWVSM1 = false;
  18428. this.SHADOWVSM2 = false;
  18429. this.SHADOWVSM3 = false;
  18430. this.SHADOWPCF0 = false;
  18431. this.SHADOWPCF1 = false;
  18432. this.SHADOWPCF2 = false;
  18433. this.SHADOWPCF3 = false;
  18434. this.DIFFUSEFRESNEL = false;
  18435. this.OPACITYFRESNEL = false;
  18436. this.REFLECTIONFRESNEL = false;
  18437. this.EMISSIVEFRESNEL = false;
  18438. this.FRESNEL = false;
  18439. this.NORMAL = false;
  18440. this.UV1 = false;
  18441. this.UV2 = false;
  18442. this.VERTEXCOLOR = false;
  18443. this.VERTEXALPHA = false;
  18444. this.NUM_BONE_INFLUENCERS = 0;
  18445. this.BonesPerMesh = 0;
  18446. this.INSTANCES = false;
  18447. this.GLOSSINESS = false;
  18448. this.ROUGHNESS = false;
  18449. this.EMISSIVEASILLUMINATION = false;
  18450. this.LINKEMISSIVEWITHDIFFUSE = false;
  18451. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18452. this.LIGHTMAP = false;
  18453. this.USELIGHTMAPASSHADOWMAP = false;
  18454. this.REFLECTIONMAP_3D = false;
  18455. this.REFLECTIONMAP_SPHERICAL = false;
  18456. this.REFLECTIONMAP_PLANAR = false;
  18457. this.REFLECTIONMAP_CUBIC = false;
  18458. this.REFLECTIONMAP_PROJECTION = false;
  18459. this.REFLECTIONMAP_SKYBOX = false;
  18460. this.REFLECTIONMAP_EXPLICIT = false;
  18461. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18462. this.INVERTCUBICMAP = false;
  18463. this._keys = Object.keys(this);
  18464. }
  18465. return StandardMaterialDefines;
  18466. })(BABYLON.MaterialDefines);
  18467. var StandardMaterial = (function (_super) {
  18468. __extends(StandardMaterial, _super);
  18469. function StandardMaterial(name, scene) {
  18470. var _this = this;
  18471. _super.call(this, name, scene);
  18472. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18473. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18474. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18475. this.specularPower = 64;
  18476. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18477. this.useAlphaFromDiffuseTexture = false;
  18478. this.useEmissiveAsIllumination = false;
  18479. this.linkEmissiveWithDiffuse = false;
  18480. this.useReflectionFresnelFromSpecular = false;
  18481. this.useSpecularOverAlpha = true;
  18482. this.disableLighting = false;
  18483. this.roughness = 0;
  18484. this.useLightmapAsShadowmap = false;
  18485. this.useGlossinessFromSpecularMapAlpha = false;
  18486. this._renderTargets = new BABYLON.SmartArray(16);
  18487. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18488. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18489. this._defines = new StandardMaterialDefines();
  18490. this._cachedDefines = new StandardMaterialDefines();
  18491. this._cachedDefines.BonesPerMesh = -1;
  18492. this.getRenderTargetTextures = function () {
  18493. _this._renderTargets.reset();
  18494. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18495. _this._renderTargets.push(_this.reflectionTexture);
  18496. }
  18497. return _this._renderTargets;
  18498. };
  18499. }
  18500. StandardMaterial.prototype.needAlphaBlending = function () {
  18501. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18502. };
  18503. StandardMaterial.prototype.needAlphaTesting = function () {
  18504. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18505. };
  18506. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18507. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18508. };
  18509. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18510. return this.diffuseTexture;
  18511. };
  18512. // Methods
  18513. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18514. if (!mesh) {
  18515. return true;
  18516. }
  18517. if (this._defines.INSTANCES !== useInstances) {
  18518. return false;
  18519. }
  18520. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18521. return true;
  18522. }
  18523. return false;
  18524. };
  18525. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  18526. var lightIndex = 0;
  18527. var needNormals = false;
  18528. for (var index = 0; index < scene.lights.length; index++) {
  18529. var light = scene.lights[index];
  18530. if (!light.isEnabled()) {
  18531. continue;
  18532. }
  18533. // Excluded check
  18534. if (light._excludedMeshesIds.length > 0) {
  18535. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18536. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18537. if (excludedMesh) {
  18538. light.excludedMeshes.push(excludedMesh);
  18539. }
  18540. }
  18541. light._excludedMeshesIds = [];
  18542. }
  18543. // Included check
  18544. if (light._includedOnlyMeshesIds.length > 0) {
  18545. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18546. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18547. if (includedOnlyMesh) {
  18548. light.includedOnlyMeshes.push(includedOnlyMesh);
  18549. }
  18550. }
  18551. light._includedOnlyMeshesIds = [];
  18552. }
  18553. if (!light.canAffectMesh(mesh)) {
  18554. continue;
  18555. }
  18556. needNormals = true;
  18557. defines["LIGHT" + lightIndex] = true;
  18558. var type;
  18559. if (light instanceof BABYLON.SpotLight) {
  18560. type = "SPOTLIGHT" + lightIndex;
  18561. }
  18562. else if (light instanceof BABYLON.HemisphericLight) {
  18563. type = "HEMILIGHT" + lightIndex;
  18564. }
  18565. else if (light instanceof BABYLON.PointLight) {
  18566. type = "POINTLIGHT" + lightIndex;
  18567. }
  18568. else {
  18569. type = "DIRLIGHT" + lightIndex;
  18570. }
  18571. defines[type] = true;
  18572. // Specular
  18573. if (!light.specular.equalsFloats(0, 0, 0)) {
  18574. defines["SPECULARTERM"] = true;
  18575. }
  18576. // Shadows
  18577. if (scene.shadowsEnabled) {
  18578. var shadowGenerator = light.getShadowGenerator();
  18579. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18580. defines["SHADOW" + lightIndex] = true;
  18581. defines["SHADOWS"] = true;
  18582. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18583. defines["SHADOWVSM" + lightIndex] = true;
  18584. }
  18585. if (shadowGenerator.usePoissonSampling) {
  18586. defines["SHADOWPCF" + lightIndex] = true;
  18587. }
  18588. }
  18589. }
  18590. lightIndex++;
  18591. if (lightIndex === maxSimultaneousLights)
  18592. break;
  18593. }
  18594. return needNormals;
  18595. };
  18596. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  18597. var lightIndex = 0;
  18598. for (var index = 0; index < scene.lights.length; index++) {
  18599. var light = scene.lights[index];
  18600. if (!light.isEnabled()) {
  18601. continue;
  18602. }
  18603. if (!light.canAffectMesh(mesh)) {
  18604. continue;
  18605. }
  18606. if (light instanceof BABYLON.PointLight) {
  18607. // Point Light
  18608. light.transferToEffect(effect, "vLightData" + lightIndex);
  18609. }
  18610. else if (light instanceof BABYLON.DirectionalLight) {
  18611. // Directional Light
  18612. light.transferToEffect(effect, "vLightData" + lightIndex);
  18613. }
  18614. else if (light instanceof BABYLON.SpotLight) {
  18615. // Spot Light
  18616. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18617. }
  18618. else if (light instanceof BABYLON.HemisphericLight) {
  18619. // Hemispheric Light
  18620. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18621. }
  18622. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  18623. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  18624. if (defines["SPECULARTERM"]) {
  18625. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  18626. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  18627. }
  18628. // Shadows
  18629. if (scene.shadowsEnabled) {
  18630. var shadowGenerator = light.getShadowGenerator();
  18631. if (mesh.receiveShadows && shadowGenerator) {
  18632. if (!light.needCube()) {
  18633. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18634. }
  18635. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18636. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18637. }
  18638. }
  18639. lightIndex++;
  18640. if (lightIndex === maxSimultaneousLights)
  18641. break;
  18642. }
  18643. };
  18644. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18645. if (this.checkReadyOnlyOnce) {
  18646. if (this._wasPreviouslyReady) {
  18647. return true;
  18648. }
  18649. }
  18650. var scene = this.getScene();
  18651. if (!this.checkReadyOnEveryCall) {
  18652. if (this._renderId === scene.getRenderId()) {
  18653. if (this._checkCache(scene, mesh, useInstances)) {
  18654. return true;
  18655. }
  18656. }
  18657. }
  18658. var engine = scene.getEngine();
  18659. var needNormals = false;
  18660. var needUVs = false;
  18661. this._defines.reset();
  18662. // Textures
  18663. if (scene.texturesEnabled) {
  18664. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18665. if (!this.diffuseTexture.isReady()) {
  18666. return false;
  18667. }
  18668. else {
  18669. needUVs = true;
  18670. this._defines.DIFFUSE = true;
  18671. }
  18672. }
  18673. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18674. if (!this.ambientTexture.isReady()) {
  18675. return false;
  18676. }
  18677. else {
  18678. needUVs = true;
  18679. this._defines.AMBIENT = true;
  18680. }
  18681. }
  18682. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18683. if (!this.opacityTexture.isReady()) {
  18684. return false;
  18685. }
  18686. else {
  18687. needUVs = true;
  18688. this._defines.OPACITY = true;
  18689. if (this.opacityTexture.getAlphaFromRGB) {
  18690. this._defines.OPACITYRGB = true;
  18691. }
  18692. }
  18693. }
  18694. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18695. if (!this.reflectionTexture.isReady()) {
  18696. return false;
  18697. }
  18698. else {
  18699. needNormals = true;
  18700. this._defines.REFLECTION = true;
  18701. if (this.roughness > 0) {
  18702. this._defines.ROUGHNESS = true;
  18703. }
  18704. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18705. this._defines.INVERTCUBICMAP = true;
  18706. }
  18707. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18708. switch (this.reflectionTexture.coordinatesMode) {
  18709. case BABYLON.Texture.CUBIC_MODE:
  18710. case BABYLON.Texture.INVCUBIC_MODE:
  18711. this._defines.REFLECTIONMAP_CUBIC = true;
  18712. break;
  18713. case BABYLON.Texture.EXPLICIT_MODE:
  18714. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18715. break;
  18716. case BABYLON.Texture.PLANAR_MODE:
  18717. this._defines.REFLECTIONMAP_PLANAR = true;
  18718. break;
  18719. case BABYLON.Texture.PROJECTION_MODE:
  18720. this._defines.REFLECTIONMAP_PROJECTION = true;
  18721. break;
  18722. case BABYLON.Texture.SKYBOX_MODE:
  18723. this._defines.REFLECTIONMAP_SKYBOX = true;
  18724. break;
  18725. case BABYLON.Texture.SPHERICAL_MODE:
  18726. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18727. break;
  18728. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18729. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18730. break;
  18731. }
  18732. }
  18733. }
  18734. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18735. if (!this.emissiveTexture.isReady()) {
  18736. return false;
  18737. }
  18738. else {
  18739. needUVs = true;
  18740. this._defines.EMISSIVE = true;
  18741. }
  18742. }
  18743. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18744. if (!this.lightmapTexture.isReady()) {
  18745. return false;
  18746. }
  18747. else {
  18748. needUVs = true;
  18749. this._defines.LIGHTMAP = true;
  18750. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18751. }
  18752. }
  18753. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18754. if (!this.specularTexture.isReady()) {
  18755. return false;
  18756. }
  18757. else {
  18758. needUVs = true;
  18759. this._defines.SPECULAR = true;
  18760. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18761. }
  18762. }
  18763. }
  18764. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18765. if (!this.bumpTexture.isReady()) {
  18766. return false;
  18767. }
  18768. else {
  18769. needUVs = true;
  18770. this._defines.BUMP = true;
  18771. }
  18772. }
  18773. // Effect
  18774. if (scene.clipPlane) {
  18775. this._defines.CLIPPLANE = true;
  18776. }
  18777. if (engine.getAlphaTesting()) {
  18778. this._defines.ALPHATEST = true;
  18779. }
  18780. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18781. this._defines.ALPHAFROMDIFFUSE = true;
  18782. }
  18783. if (this.useEmissiveAsIllumination) {
  18784. this._defines.EMISSIVEASILLUMINATION = true;
  18785. }
  18786. if (this.linkEmissiveWithDiffuse) {
  18787. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  18788. }
  18789. if (this.useReflectionFresnelFromSpecular) {
  18790. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18791. }
  18792. // Point size
  18793. if (this.pointsCloud || scene.forcePointsCloud) {
  18794. this._defines.POINTSIZE = true;
  18795. }
  18796. // Fog
  18797. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18798. this._defines.FOG = true;
  18799. }
  18800. if (scene.lightsEnabled && !this.disableLighting) {
  18801. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  18802. }
  18803. if (StandardMaterial.FresnelEnabled) {
  18804. // Fresnel
  18805. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18806. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18807. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18808. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18809. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18810. this._defines.DIFFUSEFRESNEL = true;
  18811. }
  18812. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18813. this._defines.OPACITYFRESNEL = true;
  18814. }
  18815. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18816. this._defines.REFLECTIONFRESNEL = true;
  18817. }
  18818. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18819. this._defines.EMISSIVEFRESNEL = true;
  18820. }
  18821. needNormals = true;
  18822. this._defines.FRESNEL = true;
  18823. }
  18824. }
  18825. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18826. this._defines.SPECULAROVERALPHA = true;
  18827. }
  18828. // Attribs
  18829. if (mesh) {
  18830. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18831. this._defines.NORMAL = true;
  18832. }
  18833. if (needUVs) {
  18834. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18835. this._defines.UV1 = true;
  18836. }
  18837. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18838. this._defines.UV2 = true;
  18839. }
  18840. }
  18841. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18842. this._defines.VERTEXCOLOR = true;
  18843. if (mesh.hasVertexAlpha) {
  18844. this._defines.VERTEXALPHA = true;
  18845. }
  18846. }
  18847. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18848. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  18849. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18850. }
  18851. // Instances
  18852. if (useInstances) {
  18853. this._defines.INSTANCES = true;
  18854. }
  18855. }
  18856. // Get correct effect
  18857. if (!this._defines.isEqual(this._cachedDefines)) {
  18858. this._defines.cloneTo(this._cachedDefines);
  18859. scene.resetCachedMaterial();
  18860. // Fallbacks
  18861. var fallbacks = new BABYLON.EffectFallbacks();
  18862. if (this._defines.REFLECTION) {
  18863. fallbacks.addFallback(0, "REFLECTION");
  18864. }
  18865. if (this._defines.SPECULAR) {
  18866. fallbacks.addFallback(0, "SPECULAR");
  18867. }
  18868. if (this._defines.BUMP) {
  18869. fallbacks.addFallback(0, "BUMP");
  18870. }
  18871. if (this._defines.SPECULAROVERALPHA) {
  18872. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18873. }
  18874. if (this._defines.FOG) {
  18875. fallbacks.addFallback(1, "FOG");
  18876. }
  18877. if (this._defines.POINTSIZE) {
  18878. fallbacks.addFallback(0, "POINTSIZE");
  18879. }
  18880. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18881. if (!this._defines["LIGHT" + lightIndex]) {
  18882. continue;
  18883. }
  18884. if (lightIndex > 0) {
  18885. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18886. }
  18887. if (this._defines["SHADOW" + lightIndex]) {
  18888. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18889. }
  18890. if (this._defines["SHADOWPCF" + lightIndex]) {
  18891. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18892. }
  18893. if (this._defines["SHADOWVSM" + lightIndex]) {
  18894. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18895. }
  18896. }
  18897. if (this._defines.SPECULARTERM) {
  18898. fallbacks.addFallback(0, "SPECULARTERM");
  18899. }
  18900. if (this._defines.DIFFUSEFRESNEL) {
  18901. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18902. }
  18903. if (this._defines.OPACITYFRESNEL) {
  18904. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18905. }
  18906. if (this._defines.REFLECTIONFRESNEL) {
  18907. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18908. }
  18909. if (this._defines.EMISSIVEFRESNEL) {
  18910. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18911. }
  18912. if (this._defines.FRESNEL) {
  18913. fallbacks.addFallback(4, "FRESNEL");
  18914. }
  18915. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18916. fallbacks.addCPUSkinningFallback(0, mesh);
  18917. }
  18918. //Attributes
  18919. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18920. if (this._defines.NORMAL) {
  18921. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18922. }
  18923. if (this._defines.UV1) {
  18924. attribs.push(BABYLON.VertexBuffer.UVKind);
  18925. }
  18926. if (this._defines.UV2) {
  18927. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18928. }
  18929. if (this._defines.VERTEXCOLOR) {
  18930. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18931. }
  18932. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  18933. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18934. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18935. if (this._defines.NUM_BONE_INFLUENCERS > 4) {
  18936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  18937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  18938. }
  18939. }
  18940. if (this._defines.INSTANCES) {
  18941. attribs.push("world0");
  18942. attribs.push("world1");
  18943. attribs.push("world2");
  18944. attribs.push("world3");
  18945. }
  18946. // Legacy browser patch
  18947. var shaderName = "default";
  18948. if (!scene.getEngine().getCaps().standardDerivatives) {
  18949. shaderName = "legacydefault";
  18950. }
  18951. var join = this._defines.toString();
  18952. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18953. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18954. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18955. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18956. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18957. "vFogInfos", "vFogColor", "pointSize",
  18958. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18959. "mBones",
  18960. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18961. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18962. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18963. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18964. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18965. ], join, fallbacks, this.onCompiled, this.onError);
  18966. }
  18967. if (!this._effect.isReady()) {
  18968. return false;
  18969. }
  18970. this._renderId = scene.getRenderId();
  18971. this._wasPreviouslyReady = true;
  18972. if (mesh) {
  18973. if (!mesh._materialDefines) {
  18974. mesh._materialDefines = new StandardMaterialDefines();
  18975. }
  18976. this._defines.cloneTo(mesh._materialDefines);
  18977. }
  18978. return true;
  18979. };
  18980. StandardMaterial.prototype.unbind = function () {
  18981. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18982. this._effect.setTexture("reflection2DSampler", null);
  18983. }
  18984. _super.prototype.unbind.call(this);
  18985. };
  18986. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18987. this._effect.setMatrix("world", world);
  18988. };
  18989. StandardMaterial.prototype.bind = function (world, mesh) {
  18990. var scene = this.getScene();
  18991. // Matrices
  18992. this.bindOnlyWorldMatrix(world);
  18993. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18994. // Bones
  18995. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18996. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18997. }
  18998. if (scene.getCachedMaterial() !== this) {
  18999. if (StandardMaterial.FresnelEnabled) {
  19000. // Fresnel
  19001. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19002. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19003. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19004. }
  19005. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19006. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19007. }
  19008. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19009. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19010. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19011. }
  19012. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19013. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19014. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19015. }
  19016. }
  19017. // Textures
  19018. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19019. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19020. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19021. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19022. }
  19023. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19024. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19025. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19026. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19027. }
  19028. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19029. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19030. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19031. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19032. }
  19033. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19034. if (this.reflectionTexture.isCube) {
  19035. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19036. }
  19037. else {
  19038. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19039. }
  19040. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19041. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  19042. }
  19043. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19044. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19045. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19046. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19047. }
  19048. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  19049. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  19050. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  19051. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  19052. }
  19053. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19054. this._effect.setTexture("specularSampler", this.specularTexture);
  19055. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19056. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19057. }
  19058. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19059. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19060. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19061. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19062. }
  19063. // Clip plane
  19064. if (scene.clipPlane) {
  19065. var clipPlane = scene.clipPlane;
  19066. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19067. }
  19068. // Point size
  19069. if (this.pointsCloud) {
  19070. this._effect.setFloat("pointSize", this.pointSize);
  19071. }
  19072. // Colors
  19073. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19074. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  19075. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19076. if (this._defines.SPECULARTERM) {
  19077. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  19078. }
  19079. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19080. }
  19081. // Diffuse
  19082. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  19083. // Lights
  19084. if (scene.lightsEnabled && !this.disableLighting) {
  19085. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  19086. }
  19087. // View
  19088. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19089. this._effect.setMatrix("view", scene.getViewMatrix());
  19090. }
  19091. // Fog
  19092. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19093. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19094. this._effect.setColor3("vFogColor", scene.fogColor);
  19095. }
  19096. _super.prototype.bind.call(this, world, mesh);
  19097. };
  19098. StandardMaterial.prototype.getAnimatables = function () {
  19099. var results = [];
  19100. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19101. results.push(this.diffuseTexture);
  19102. }
  19103. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19104. results.push(this.ambientTexture);
  19105. }
  19106. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19107. results.push(this.opacityTexture);
  19108. }
  19109. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19110. results.push(this.reflectionTexture);
  19111. }
  19112. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19113. results.push(this.emissiveTexture);
  19114. }
  19115. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19116. results.push(this.specularTexture);
  19117. }
  19118. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19119. results.push(this.bumpTexture);
  19120. }
  19121. return results;
  19122. };
  19123. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19124. if (this.diffuseTexture) {
  19125. this.diffuseTexture.dispose();
  19126. }
  19127. if (this.ambientTexture) {
  19128. this.ambientTexture.dispose();
  19129. }
  19130. if (this.opacityTexture) {
  19131. this.opacityTexture.dispose();
  19132. }
  19133. if (this.reflectionTexture) {
  19134. this.reflectionTexture.dispose();
  19135. }
  19136. if (this.emissiveTexture) {
  19137. this.emissiveTexture.dispose();
  19138. }
  19139. if (this.specularTexture) {
  19140. this.specularTexture.dispose();
  19141. }
  19142. if (this.bumpTexture) {
  19143. this.bumpTexture.dispose();
  19144. }
  19145. _super.prototype.dispose.call(this, forceDisposeEffect);
  19146. };
  19147. StandardMaterial.prototype.clone = function (name) {
  19148. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19149. // Base material
  19150. this.copyTo(newStandardMaterial);
  19151. // Standard material
  19152. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19153. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19154. }
  19155. if (this.ambientTexture && this.ambientTexture.clone) {
  19156. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19157. }
  19158. if (this.opacityTexture && this.opacityTexture.clone) {
  19159. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19160. }
  19161. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19162. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19163. }
  19164. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19165. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19166. }
  19167. if (this.specularTexture && this.specularTexture.clone) {
  19168. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19169. }
  19170. if (this.bumpTexture && this.bumpTexture.clone) {
  19171. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19172. }
  19173. if (this.lightmapTexture && this.lightmapTexture.clone) {
  19174. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  19175. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  19176. }
  19177. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19178. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19179. newStandardMaterial.specularColor = this.specularColor.clone();
  19180. newStandardMaterial.specularPower = this.specularPower;
  19181. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19182. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  19183. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  19184. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  19185. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  19186. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  19187. newStandardMaterial.roughness = this.roughness;
  19188. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  19189. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  19190. }
  19191. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  19192. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  19193. }
  19194. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  19195. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  19196. }
  19197. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  19198. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  19199. }
  19200. return newStandardMaterial;
  19201. };
  19202. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  19203. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  19204. // Statics
  19205. // Flags used to enable or disable a type of texture for all Standard Materials
  19206. StandardMaterial.DiffuseTextureEnabled = true;
  19207. StandardMaterial.AmbientTextureEnabled = true;
  19208. StandardMaterial.OpacityTextureEnabled = true;
  19209. StandardMaterial.ReflectionTextureEnabled = true;
  19210. StandardMaterial.EmissiveTextureEnabled = true;
  19211. StandardMaterial.SpecularTextureEnabled = true;
  19212. StandardMaterial.BumpTextureEnabled = true;
  19213. StandardMaterial.FresnelEnabled = true;
  19214. StandardMaterial.LightmapEnabled = true;
  19215. return StandardMaterial;
  19216. })(BABYLON.Material);
  19217. BABYLON.StandardMaterial = StandardMaterial;
  19218. })(BABYLON || (BABYLON = {}));
  19219. var BABYLON;
  19220. (function (BABYLON) {
  19221. var MultiMaterial = (function (_super) {
  19222. __extends(MultiMaterial, _super);
  19223. function MultiMaterial(name, scene) {
  19224. _super.call(this, name, scene, true);
  19225. this.subMaterials = new Array();
  19226. scene.multiMaterials.push(this);
  19227. }
  19228. // Properties
  19229. MultiMaterial.prototype.getSubMaterial = function (index) {
  19230. if (index < 0 || index >= this.subMaterials.length) {
  19231. return this.getScene().defaultMaterial;
  19232. }
  19233. return this.subMaterials[index];
  19234. };
  19235. // Methods
  19236. MultiMaterial.prototype.isReady = function (mesh) {
  19237. for (var index = 0; index < this.subMaterials.length; index++) {
  19238. var subMaterial = this.subMaterials[index];
  19239. if (subMaterial) {
  19240. if (!this.subMaterials[index].isReady(mesh)) {
  19241. return false;
  19242. }
  19243. }
  19244. }
  19245. return true;
  19246. };
  19247. MultiMaterial.prototype.clone = function (name) {
  19248. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19249. for (var index = 0; index < this.subMaterials.length; index++) {
  19250. var subMaterial = this.subMaterials[index];
  19251. newMultiMaterial.subMaterials.push(subMaterial);
  19252. }
  19253. return newMultiMaterial;
  19254. };
  19255. return MultiMaterial;
  19256. })(BABYLON.Material);
  19257. BABYLON.MultiMaterial = MultiMaterial;
  19258. })(BABYLON || (BABYLON = {}));
  19259. var BABYLON;
  19260. (function (BABYLON) {
  19261. var SceneLoader = (function () {
  19262. function SceneLoader() {
  19263. }
  19264. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19265. get: function () {
  19266. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19267. },
  19268. set: function (value) {
  19269. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19270. },
  19271. enumerable: true,
  19272. configurable: true
  19273. });
  19274. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19275. get: function () {
  19276. return SceneLoader._ShowLoadingScreen;
  19277. },
  19278. set: function (value) {
  19279. SceneLoader._ShowLoadingScreen = value;
  19280. },
  19281. enumerable: true,
  19282. configurable: true
  19283. });
  19284. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19285. var dotPosition = sceneFilename.lastIndexOf(".");
  19286. var queryStringPosition = sceneFilename.indexOf("?");
  19287. if (queryStringPosition === -1) {
  19288. queryStringPosition = sceneFilename.length;
  19289. }
  19290. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19291. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19292. var plugin = this._registeredPlugins[index];
  19293. if (plugin.extensions.indexOf(extension) !== -1) {
  19294. return plugin;
  19295. }
  19296. }
  19297. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19298. };
  19299. // Public functions
  19300. SceneLoader.RegisterPlugin = function (plugin) {
  19301. plugin.extensions = plugin.extensions.toLowerCase();
  19302. SceneLoader._registeredPlugins.push(plugin);
  19303. };
  19304. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19305. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19306. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19307. return;
  19308. }
  19309. var loadingToken = {};
  19310. scene._addPendingData(loadingToken);
  19311. var manifestChecked = function (success) {
  19312. scene.database = database;
  19313. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19314. var importMeshFromData = function (data) {
  19315. var meshes = [];
  19316. var particleSystems = [];
  19317. var skeletons = [];
  19318. try {
  19319. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19320. if (onerror) {
  19321. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19322. }
  19323. scene._removePendingData(loadingToken);
  19324. return;
  19325. }
  19326. }
  19327. catch (e) {
  19328. if (onerror) {
  19329. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19330. }
  19331. scene._removePendingData(loadingToken);
  19332. return;
  19333. }
  19334. if (onsuccess) {
  19335. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19336. onsuccess(meshes, particleSystems, skeletons);
  19337. scene._removePendingData(loadingToken);
  19338. }
  19339. };
  19340. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19341. // Direct load
  19342. importMeshFromData(sceneFilename.substr(5));
  19343. return;
  19344. }
  19345. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19346. importMeshFromData(data);
  19347. }, progressCallBack, database);
  19348. };
  19349. if (scene.getEngine().enableOfflineSupport) {
  19350. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19351. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19352. }
  19353. else {
  19354. manifestChecked(true);
  19355. }
  19356. };
  19357. /**
  19358. * Load a scene
  19359. * @param rootUrl a string that defines the root url for scene and resources
  19360. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19361. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19362. */
  19363. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19364. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19365. };
  19366. /**
  19367. * Append a scene
  19368. * @param rootUrl a string that defines the root url for scene and resources
  19369. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19370. * @param scene is the instance of BABYLON.Scene to append to
  19371. */
  19372. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19373. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19374. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19375. return;
  19376. }
  19377. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19378. var database;
  19379. var loadingToken = {};
  19380. scene._addPendingData(loadingToken);
  19381. if (SceneLoader.ShowLoadingScreen) {
  19382. scene.getEngine().displayLoadingUI();
  19383. }
  19384. var loadSceneFromData = function (data) {
  19385. scene.database = database;
  19386. if (!plugin.load(scene, data, rootUrl)) {
  19387. if (onerror) {
  19388. onerror(scene);
  19389. }
  19390. scene._removePendingData(loadingToken);
  19391. scene.getEngine().hideLoadingUI();
  19392. return;
  19393. }
  19394. if (onsuccess) {
  19395. onsuccess(scene);
  19396. }
  19397. scene._removePendingData(loadingToken);
  19398. if (SceneLoader.ShowLoadingScreen) {
  19399. scene.executeWhenReady(function () {
  19400. scene.getEngine().hideLoadingUI();
  19401. });
  19402. }
  19403. };
  19404. var manifestChecked = function (success) {
  19405. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19406. };
  19407. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19408. // Direct load
  19409. loadSceneFromData(sceneFilename.substr(5));
  19410. return;
  19411. }
  19412. if (rootUrl.indexOf("file:") === -1) {
  19413. if (scene.getEngine().enableOfflineSupport) {
  19414. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19415. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19416. }
  19417. else {
  19418. manifestChecked(true);
  19419. }
  19420. }
  19421. else {
  19422. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19423. }
  19424. };
  19425. // Flags
  19426. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19427. SceneLoader._ShowLoadingScreen = true;
  19428. // Members
  19429. SceneLoader._registeredPlugins = new Array();
  19430. return SceneLoader;
  19431. })();
  19432. BABYLON.SceneLoader = SceneLoader;
  19433. ;
  19434. })(BABYLON || (BABYLON = {}));
  19435. var BABYLON;
  19436. (function (BABYLON) {
  19437. var Internals;
  19438. (function (Internals) {
  19439. var checkColors4 = function (colors, count) {
  19440. // Check if color3 was used
  19441. if (colors.length === count * 3) {
  19442. var colors4 = [];
  19443. for (var index = 0; index < colors.length; index += 3) {
  19444. var newIndex = (index / 3) * 4;
  19445. colors4[newIndex] = colors[index];
  19446. colors4[newIndex + 1] = colors[index + 1];
  19447. colors4[newIndex + 2] = colors[index + 2];
  19448. colors4[newIndex + 3] = 1.0;
  19449. }
  19450. return colors4;
  19451. }
  19452. return colors;
  19453. };
  19454. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19455. var texture = null;
  19456. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19457. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19458. texture.name = parsedTexture.name;
  19459. texture.hasAlpha = parsedTexture.hasAlpha;
  19460. texture.level = parsedTexture.level;
  19461. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19462. }
  19463. return texture;
  19464. };
  19465. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19466. if (parsedTexture.isCube) {
  19467. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19468. }
  19469. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19470. return null;
  19471. }
  19472. var texture;
  19473. if (parsedTexture.mirrorPlane) {
  19474. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19475. texture._waitingRenderList = parsedTexture.renderList;
  19476. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19477. }
  19478. else if (parsedTexture.isRenderTarget) {
  19479. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19480. texture._waitingRenderList = parsedTexture.renderList;
  19481. }
  19482. else {
  19483. if (parsedTexture.base64String) {
  19484. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19485. }
  19486. else {
  19487. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19488. }
  19489. }
  19490. texture.name = parsedTexture.name;
  19491. texture.hasAlpha = parsedTexture.hasAlpha;
  19492. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19493. texture.level = parsedTexture.level;
  19494. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19495. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19496. texture.uOffset = parsedTexture.uOffset;
  19497. texture.vOffset = parsedTexture.vOffset;
  19498. texture.uScale = parsedTexture.uScale;
  19499. texture.vScale = parsedTexture.vScale;
  19500. texture.uAng = parsedTexture.uAng;
  19501. texture.vAng = parsedTexture.vAng;
  19502. texture.wAng = parsedTexture.wAng;
  19503. texture.wrapU = parsedTexture.wrapU;
  19504. texture.wrapV = parsedTexture.wrapV;
  19505. // Animations
  19506. if (parsedTexture.animations) {
  19507. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19508. var parsedAnimation = parsedTexture.animations[animationIndex];
  19509. texture.animations.push(parseAnimation(parsedAnimation));
  19510. }
  19511. }
  19512. return texture;
  19513. };
  19514. var parseSkeleton = function (parsedSkeleton, scene) {
  19515. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19516. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19517. var parsedBone = parsedSkeleton.bones[index];
  19518. var parentBone = null;
  19519. if (parsedBone.parentBoneIndex > -1) {
  19520. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19521. }
  19522. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19523. if (parsedBone.animation) {
  19524. bone.animations.push(parseAnimation(parsedBone.animation));
  19525. }
  19526. }
  19527. return skeleton;
  19528. };
  19529. var parseFresnelParameters = function (parsedFresnelParameters) {
  19530. var fresnelParameters = new BABYLON.FresnelParameters();
  19531. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19532. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19533. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19534. fresnelParameters.bias = parsedFresnelParameters.bias;
  19535. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19536. return fresnelParameters;
  19537. };
  19538. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19539. var material;
  19540. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19541. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19542. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19543. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19544. material.specularPower = parsedMaterial.specularPower;
  19545. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19546. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19547. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19548. material.alpha = parsedMaterial.alpha;
  19549. material.id = parsedMaterial.id;
  19550. if (parsedMaterial.disableDepthWrite) {
  19551. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19552. }
  19553. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19554. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19555. material.wireframe = parsedMaterial.wireframe;
  19556. if (parsedMaterial.diffuseTexture) {
  19557. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19558. }
  19559. if (parsedMaterial.diffuseFresnelParameters) {
  19560. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19561. }
  19562. if (parsedMaterial.ambientTexture) {
  19563. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19564. }
  19565. if (parsedMaterial.opacityTexture) {
  19566. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19567. }
  19568. if (parsedMaterial.opacityFresnelParameters) {
  19569. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19570. }
  19571. if (parsedMaterial.reflectionTexture) {
  19572. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19573. }
  19574. if (parsedMaterial.reflectionFresnelParameters) {
  19575. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19576. }
  19577. if (parsedMaterial.emissiveTexture) {
  19578. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19579. }
  19580. if (parsedMaterial.lightmapTexture) {
  19581. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19582. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19583. }
  19584. if (parsedMaterial.emissiveFresnelParameters) {
  19585. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19586. }
  19587. if (parsedMaterial.specularTexture) {
  19588. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19589. }
  19590. if (parsedMaterial.bumpTexture) {
  19591. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19592. }
  19593. if (parsedMaterial.checkReadyOnlyOnce) {
  19594. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19595. }
  19596. return material;
  19597. };
  19598. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19599. for (var index = 0; index < parsedData.materials.length; index++) {
  19600. var parsedMaterial = parsedData.materials[index];
  19601. if (parsedMaterial.id === id) {
  19602. return parseMaterial(parsedMaterial, scene, rootUrl);
  19603. }
  19604. }
  19605. return null;
  19606. };
  19607. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19608. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19609. multiMaterial.id = parsedMultiMaterial.id;
  19610. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19611. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19612. var subMatId = parsedMultiMaterial.materials[matIndex];
  19613. if (subMatId) {
  19614. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19615. }
  19616. else {
  19617. multiMaterial.subMaterials.push(null);
  19618. }
  19619. }
  19620. return multiMaterial;
  19621. };
  19622. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19623. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19624. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19625. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19626. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19627. var parsedFlare = parsedLensFlareSystem.flares[index];
  19628. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19629. }
  19630. return lensFlareSystem;
  19631. };
  19632. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19633. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19634. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19635. if (parsedParticleSystem.textureName) {
  19636. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19637. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19638. }
  19639. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19640. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19641. particleSystem.minSize = parsedParticleSystem.minSize;
  19642. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19643. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19644. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19645. particleSystem.emitter = emitter;
  19646. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19647. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19648. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19649. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19650. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19651. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19652. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19653. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19654. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19655. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19656. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19657. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19658. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19659. particleSystem.start();
  19660. return particleSystem;
  19661. };
  19662. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19663. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19664. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19665. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19666. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19667. shadowGenerator.getShadowMap().renderList.push(mesh);
  19668. }
  19669. if (parsedShadowGenerator.usePoissonSampling) {
  19670. shadowGenerator.usePoissonSampling = true;
  19671. }
  19672. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19673. shadowGenerator.useVarianceShadowMap = true;
  19674. }
  19675. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19676. shadowGenerator.useBlurVarianceShadowMap = true;
  19677. if (parsedShadowGenerator.blurScale) {
  19678. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19679. }
  19680. if (parsedShadowGenerator.blurBoxOffset) {
  19681. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19682. }
  19683. }
  19684. if (parsedShadowGenerator.bias !== undefined) {
  19685. shadowGenerator.bias = parsedShadowGenerator.bias;
  19686. }
  19687. return shadowGenerator;
  19688. };
  19689. var parseAnimation = function (parsedAnimation) {
  19690. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19691. var dataType = parsedAnimation.dataType;
  19692. var keys = [];
  19693. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19694. var key = parsedAnimation.keys[index];
  19695. var data;
  19696. switch (dataType) {
  19697. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19698. data = key.values[0];
  19699. break;
  19700. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19701. data = BABYLON.Quaternion.FromArray(key.values);
  19702. break;
  19703. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19704. data = BABYLON.Matrix.FromArray(key.values);
  19705. break;
  19706. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19707. default:
  19708. data = BABYLON.Vector3.FromArray(key.values);
  19709. break;
  19710. }
  19711. keys.push({
  19712. frame: key.frame,
  19713. value: data
  19714. });
  19715. }
  19716. animation.setKeys(keys);
  19717. return animation;
  19718. };
  19719. var parseLight = function (parsedLight, scene) {
  19720. var light;
  19721. switch (parsedLight.type) {
  19722. case 0:
  19723. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19724. break;
  19725. case 1:
  19726. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19727. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19728. break;
  19729. case 2:
  19730. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19731. break;
  19732. case 3:
  19733. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19734. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19735. break;
  19736. }
  19737. light.id = parsedLight.id;
  19738. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19739. if (parsedLight.intensity !== undefined) {
  19740. light.intensity = parsedLight.intensity;
  19741. }
  19742. if (parsedLight.range) {
  19743. light.range = parsedLight.range;
  19744. }
  19745. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19746. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19747. if (parsedLight.excludedMeshesIds) {
  19748. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19749. }
  19750. // Parent
  19751. if (parsedLight.parentId) {
  19752. light._waitingParentId = parsedLight.parentId;
  19753. }
  19754. if (parsedLight.includedOnlyMeshesIds) {
  19755. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19756. }
  19757. // Animations
  19758. if (parsedLight.animations) {
  19759. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19760. var parsedAnimation = parsedLight.animations[animationIndex];
  19761. light.animations.push(parseAnimation(parsedAnimation));
  19762. }
  19763. }
  19764. if (parsedLight.autoAnimate) {
  19765. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19766. }
  19767. };
  19768. var parseCamera = function (parsedCamera, scene) {
  19769. var camera;
  19770. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19771. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19772. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19773. var alpha = parsedCamera.alpha;
  19774. var beta = parsedCamera.beta;
  19775. var radius = parsedCamera.radius;
  19776. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19777. var interaxial_distance = parsedCamera.interaxial_distance;
  19778. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19779. }
  19780. else {
  19781. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19782. }
  19783. }
  19784. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19785. interaxial_distance = parsedCamera.interaxial_distance;
  19786. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19787. }
  19788. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19789. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19790. }
  19791. else if (parsedCamera.type === "FollowCamera") {
  19792. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19793. camera.heightOffset = parsedCamera.heightOffset;
  19794. camera.radius = parsedCamera.radius;
  19795. camera.rotationOffset = parsedCamera.rotationOffset;
  19796. if (lockedTargetMesh)
  19797. camera.target = lockedTargetMesh;
  19798. }
  19799. else if (parsedCamera.type === "GamepadCamera") {
  19800. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19801. }
  19802. else if (parsedCamera.type === "TouchCamera") {
  19803. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19804. }
  19805. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19806. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19807. }
  19808. else if (parsedCamera.type === "WebVRFreeCamera") {
  19809. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19810. }
  19811. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19812. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19813. }
  19814. else {
  19815. // Free Camera is the default value
  19816. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19817. }
  19818. // apply 3d rig, when found
  19819. if (parsedCamera.cameraRigMode) {
  19820. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19821. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19822. }
  19823. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19824. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19825. camera.lockedTarget = lockedTargetMesh;
  19826. }
  19827. camera.id = parsedCamera.id;
  19828. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19829. // Parent
  19830. if (parsedCamera.parentId) {
  19831. camera._waitingParentId = parsedCamera.parentId;
  19832. }
  19833. // Target
  19834. if (parsedCamera.target) {
  19835. if (camera.setTarget) {
  19836. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19837. }
  19838. else {
  19839. //For ArcRotate
  19840. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19841. }
  19842. }
  19843. else {
  19844. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19845. }
  19846. camera.fov = parsedCamera.fov;
  19847. camera.minZ = parsedCamera.minZ;
  19848. camera.maxZ = parsedCamera.maxZ;
  19849. camera.speed = parsedCamera.speed;
  19850. camera.inertia = parsedCamera.inertia;
  19851. camera.checkCollisions = parsedCamera.checkCollisions;
  19852. camera.applyGravity = parsedCamera.applyGravity;
  19853. if (parsedCamera.ellipsoid) {
  19854. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19855. }
  19856. // Animations
  19857. if (parsedCamera.animations) {
  19858. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19859. var parsedAnimation = parsedCamera.animations[animationIndex];
  19860. camera.animations.push(parseAnimation(parsedAnimation));
  19861. }
  19862. }
  19863. if (parsedCamera.autoAnimate) {
  19864. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19865. }
  19866. // Layer Mask
  19867. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19868. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19869. }
  19870. else {
  19871. camera.layerMask = 0x0FFFFFFF;
  19872. }
  19873. return camera;
  19874. };
  19875. var parseGeometry = function (parsedGeometry, scene) {
  19876. var id = parsedGeometry.id;
  19877. return scene.getGeometryByID(id);
  19878. };
  19879. var parseBox = function (parsedBox, scene) {
  19880. if (parseGeometry(parsedBox, scene)) {
  19881. return null; // null since geometry could be something else than a box...
  19882. }
  19883. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19884. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19885. scene.pushGeometry(box, true);
  19886. return box;
  19887. };
  19888. var parseSphere = function (parsedSphere, scene) {
  19889. if (parseGeometry(parsedSphere, scene)) {
  19890. return null; // null since geometry could be something else than a sphere...
  19891. }
  19892. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19893. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19894. scene.pushGeometry(sphere, true);
  19895. return sphere;
  19896. };
  19897. var parseCylinder = function (parsedCylinder, scene) {
  19898. if (parseGeometry(parsedCylinder, scene)) {
  19899. return null; // null since geometry could be something else than a cylinder...
  19900. }
  19901. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19902. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19903. scene.pushGeometry(cylinder, true);
  19904. return cylinder;
  19905. };
  19906. var parseTorus = function (parsedTorus, scene) {
  19907. if (parseGeometry(parsedTorus, scene)) {
  19908. return null; // null since geometry could be something else than a torus...
  19909. }
  19910. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19911. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19912. scene.pushGeometry(torus, true);
  19913. return torus;
  19914. };
  19915. var parseGround = function (parsedGround, scene) {
  19916. if (parseGeometry(parsedGround, scene)) {
  19917. return null; // null since geometry could be something else than a ground...
  19918. }
  19919. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19920. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19921. scene.pushGeometry(ground, true);
  19922. return ground;
  19923. };
  19924. var parsePlane = function (parsedPlane, scene) {
  19925. if (parseGeometry(parsedPlane, scene)) {
  19926. return null; // null since geometry could be something else than a plane...
  19927. }
  19928. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19929. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19930. scene.pushGeometry(plane, true);
  19931. return plane;
  19932. };
  19933. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19934. if (parseGeometry(parsedTorusKnot, scene)) {
  19935. return null; // null since geometry could be something else than a torusKnot...
  19936. }
  19937. 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);
  19938. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19939. scene.pushGeometry(torusKnot, true);
  19940. return torusKnot;
  19941. };
  19942. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19943. if (parseGeometry(parsedVertexData, scene)) {
  19944. return null; // null since geometry could be a primitive
  19945. }
  19946. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19947. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19948. if (parsedVertexData.delayLoadingFile) {
  19949. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19950. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19951. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19952. geometry._delayInfo = [];
  19953. if (parsedVertexData.hasUVs) {
  19954. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19955. }
  19956. if (parsedVertexData.hasUVs2) {
  19957. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19958. }
  19959. if (parsedVertexData.hasUVs3) {
  19960. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19961. }
  19962. if (parsedVertexData.hasUVs4) {
  19963. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19964. }
  19965. if (parsedVertexData.hasUVs5) {
  19966. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19967. }
  19968. if (parsedVertexData.hasUVs6) {
  19969. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19970. }
  19971. if (parsedVertexData.hasColors) {
  19972. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19973. }
  19974. if (parsedVertexData.hasMatricesIndices) {
  19975. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19976. }
  19977. if (parsedVertexData.hasMatricesWeights) {
  19978. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19979. }
  19980. geometry._delayLoadingFunction = importVertexData;
  19981. }
  19982. else {
  19983. importVertexData(parsedVertexData, geometry);
  19984. }
  19985. scene.pushGeometry(geometry, true);
  19986. return geometry;
  19987. };
  19988. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19989. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19990. mesh.id = parsedMesh.id;
  19991. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19992. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19993. if (parsedMesh.rotationQuaternion) {
  19994. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19995. }
  19996. else if (parsedMesh.rotation) {
  19997. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19998. }
  19999. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20000. if (parsedMesh.localMatrix) {
  20001. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20002. }
  20003. else if (parsedMesh.pivotMatrix) {
  20004. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20005. }
  20006. mesh.setEnabled(parsedMesh.isEnabled);
  20007. mesh.isVisible = parsedMesh.isVisible;
  20008. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20009. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20010. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20011. if (parsedMesh.applyFog !== undefined) {
  20012. mesh.applyFog = parsedMesh.applyFog;
  20013. }
  20014. if (parsedMesh.pickable !== undefined) {
  20015. mesh.isPickable = parsedMesh.pickable;
  20016. }
  20017. if (parsedMesh.alphaIndex !== undefined) {
  20018. mesh.alphaIndex = parsedMesh.alphaIndex;
  20019. }
  20020. mesh.receiveShadows = parsedMesh.receiveShadows;
  20021. mesh.billboardMode = parsedMesh.billboardMode;
  20022. if (parsedMesh.visibility !== undefined) {
  20023. mesh.visibility = parsedMesh.visibility;
  20024. }
  20025. mesh.checkCollisions = parsedMesh.checkCollisions;
  20026. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20027. // freezeWorldMatrix
  20028. if (parsedMesh.freezeWorldMatrix) {
  20029. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20030. }
  20031. // Parent
  20032. if (parsedMesh.parentId) {
  20033. mesh._waitingParentId = parsedMesh.parentId;
  20034. }
  20035. // Actions
  20036. if (parsedMesh.actions !== undefined) {
  20037. mesh._waitingActions = parsedMesh.actions;
  20038. }
  20039. // Geometry
  20040. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20041. if (parsedMesh.delayLoadingFile) {
  20042. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20043. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20044. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20045. if (parsedMesh._binaryInfo) {
  20046. mesh._binaryInfo = parsedMesh._binaryInfo;
  20047. }
  20048. mesh._delayInfo = [];
  20049. if (parsedMesh.hasUVs) {
  20050. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20051. }
  20052. if (parsedMesh.hasUVs2) {
  20053. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20054. }
  20055. if (parsedMesh.hasUVs3) {
  20056. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20057. }
  20058. if (parsedMesh.hasUVs4) {
  20059. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20060. }
  20061. if (parsedMesh.hasUVs5) {
  20062. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20063. }
  20064. if (parsedMesh.hasUVs6) {
  20065. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20066. }
  20067. if (parsedMesh.hasColors) {
  20068. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20069. }
  20070. if (parsedMesh.hasMatricesIndices) {
  20071. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20072. }
  20073. if (parsedMesh.hasMatricesWeights) {
  20074. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20075. }
  20076. mesh._delayLoadingFunction = importGeometry;
  20077. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20078. mesh._checkDelayState();
  20079. }
  20080. }
  20081. else {
  20082. importGeometry(parsedMesh, mesh);
  20083. }
  20084. // Material
  20085. if (parsedMesh.materialId) {
  20086. mesh.setMaterialByID(parsedMesh.materialId);
  20087. }
  20088. else {
  20089. mesh.material = null;
  20090. }
  20091. // Skeleton
  20092. if (parsedMesh.skeletonId > -1) {
  20093. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20094. if (parsedMesh.numBoneInfluencers) {
  20095. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20096. }
  20097. }
  20098. // Physics
  20099. if (parsedMesh.physicsImpostor) {
  20100. if (!scene.isPhysicsEnabled()) {
  20101. scene.enablePhysics();
  20102. }
  20103. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20104. }
  20105. // Animations
  20106. if (parsedMesh.animations) {
  20107. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20108. var parsedAnimation = parsedMesh.animations[animationIndex];
  20109. mesh.animations.push(parseAnimation(parsedAnimation));
  20110. }
  20111. }
  20112. if (parsedMesh.autoAnimate) {
  20113. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20114. }
  20115. // Layer Mask
  20116. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20117. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20118. }
  20119. else {
  20120. mesh.layerMask = 0x0FFFFFFF;
  20121. }
  20122. // Instances
  20123. if (parsedMesh.instances) {
  20124. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20125. var parsedInstance = parsedMesh.instances[index];
  20126. var instance = mesh.createInstance(parsedInstance.name);
  20127. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20128. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20129. if (parsedInstance.rotationQuaternion) {
  20130. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20131. }
  20132. else if (parsedInstance.rotation) {
  20133. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20134. }
  20135. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20136. instance.checkCollisions = mesh.checkCollisions;
  20137. if (parsedMesh.animations) {
  20138. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20139. parsedAnimation = parsedMesh.animations[animationIndex];
  20140. instance.animations.push(parseAnimation(parsedAnimation));
  20141. }
  20142. }
  20143. }
  20144. }
  20145. return mesh;
  20146. };
  20147. var parseActions = function (parsedActions, object, scene) {
  20148. var actionManager = new BABYLON.ActionManager(scene);
  20149. if (object === null)
  20150. scene.actionManager = actionManager;
  20151. else
  20152. object.actionManager = actionManager;
  20153. // instanciate a new object
  20154. var instanciate = function (name, params) {
  20155. var newInstance = Object.create(BABYLON[name].prototype);
  20156. newInstance.constructor.apply(newInstance, params);
  20157. return newInstance;
  20158. };
  20159. var parseParameter = function (name, value, target, propertyPath) {
  20160. if (propertyPath === null) {
  20161. // String, boolean or float
  20162. var floatValue = parseFloat(value);
  20163. if (value === "true" || value === "false")
  20164. return value === "true";
  20165. else
  20166. return isNaN(floatValue) ? value : floatValue;
  20167. }
  20168. var effectiveTarget = propertyPath.split(".");
  20169. var values = value.split(",");
  20170. // Get effective Target
  20171. for (var i = 0; i < effectiveTarget.length; i++) {
  20172. target = target[effectiveTarget[i]];
  20173. }
  20174. // Return appropriate value with its type
  20175. if (typeof (target) === "boolean")
  20176. return values[0] === "true";
  20177. if (typeof (target) === "string")
  20178. return values[0];
  20179. // Parameters with multiple values such as Vector3 etc.
  20180. var split = new Array();
  20181. for (var i = 0; i < values.length; i++)
  20182. split.push(parseFloat(values[i]));
  20183. if (target instanceof BABYLON.Vector3)
  20184. return BABYLON.Vector3.FromArray(split);
  20185. if (target instanceof BABYLON.Vector4)
  20186. return BABYLON.Vector4.FromArray(split);
  20187. if (target instanceof BABYLON.Color3)
  20188. return BABYLON.Color3.FromArray(split);
  20189. if (target instanceof BABYLON.Color4)
  20190. return BABYLON.Color4.FromArray(split);
  20191. return parseFloat(values[0]);
  20192. };
  20193. // traverse graph per trigger
  20194. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20195. if (combineArray === void 0) { combineArray = null; }
  20196. if (parsedAction.detached)
  20197. return;
  20198. var parameters = new Array();
  20199. var target = null;
  20200. var propertyPath = null;
  20201. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20202. // Parameters
  20203. if (parsedAction.type === 2)
  20204. parameters.push(actionManager);
  20205. else
  20206. parameters.push(trigger);
  20207. if (combine) {
  20208. var actions = new Array();
  20209. for (var j = 0; j < parsedAction.combine.length; j++) {
  20210. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20211. }
  20212. parameters.push(actions);
  20213. }
  20214. else {
  20215. for (var i = 0; i < parsedAction.properties.length; i++) {
  20216. var value = parsedAction.properties[i].value;
  20217. var name = parsedAction.properties[i].name;
  20218. var targetType = parsedAction.properties[i].targetType;
  20219. if (name === "target")
  20220. if (targetType !== null && targetType === "SceneProperties")
  20221. value = target = scene;
  20222. else
  20223. value = target = scene.getNodeByName(value);
  20224. else if (name === "parent")
  20225. value = scene.getNodeByName(value);
  20226. else if (name === "sound")
  20227. value = scene.getSoundByName(value);
  20228. else if (name !== "propertyPath") {
  20229. if (parsedAction.type === 2 && name === "operator")
  20230. value = BABYLON.ValueCondition[value];
  20231. else
  20232. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20233. }
  20234. else {
  20235. propertyPath = value;
  20236. }
  20237. parameters.push(value);
  20238. }
  20239. }
  20240. if (combineArray === null) {
  20241. parameters.push(condition);
  20242. }
  20243. else {
  20244. parameters.push(null);
  20245. }
  20246. // If interpolate value action
  20247. if (parsedAction.name === "InterpolateValueAction") {
  20248. var param = parameters[parameters.length - 2];
  20249. parameters[parameters.length - 1] = param;
  20250. parameters[parameters.length - 2] = condition;
  20251. }
  20252. // Action or condition(s) and not CombineAction
  20253. var newAction = instanciate(parsedAction.name, parameters);
  20254. if (newAction instanceof BABYLON.Condition && condition !== null) {
  20255. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  20256. if (action)
  20257. action.then(nothing);
  20258. else
  20259. actionManager.registerAction(nothing);
  20260. action = nothing;
  20261. }
  20262. if (combineArray === null) {
  20263. if (newAction instanceof BABYLON.Condition) {
  20264. condition = newAction;
  20265. newAction = action;
  20266. }
  20267. else {
  20268. condition = null;
  20269. if (action)
  20270. action.then(newAction);
  20271. else
  20272. actionManager.registerAction(newAction);
  20273. }
  20274. }
  20275. else {
  20276. combineArray.push(newAction);
  20277. }
  20278. for (var i = 0; i < parsedAction.children.length; i++)
  20279. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20280. };
  20281. // triggers
  20282. for (var i = 0; i < parsedActions.children.length; i++) {
  20283. var triggerParams;
  20284. var trigger = parsedActions.children[i];
  20285. if (trigger.properties.length > 0) {
  20286. var param = trigger.properties[0].value;
  20287. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20288. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20289. }
  20290. else
  20291. triggerParams = BABYLON.ActionManager[trigger.name];
  20292. for (var j = 0; j < trigger.children.length; j++) {
  20293. if (!trigger.detached)
  20294. traverse(trigger.children[j], triggerParams, null, null);
  20295. }
  20296. }
  20297. };
  20298. var parseSound = function (parsedSound, scene, rootUrl) {
  20299. var soundName = parsedSound.name;
  20300. var soundUrl = rootUrl + soundName;
  20301. var options = {
  20302. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20303. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20304. rolloffFactor: parsedSound.rolloffFactor,
  20305. refDistance: parsedSound.refDistance,
  20306. distanceModel: parsedSound.distanceModel,
  20307. playbackRate: parsedSound.playbackRate
  20308. };
  20309. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20310. scene._addPendingData(newSound);
  20311. if (parsedSound.position) {
  20312. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20313. newSound.setPosition(soundPosition);
  20314. }
  20315. if (parsedSound.isDirectional) {
  20316. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20317. if (parsedSound.localDirectionToMesh) {
  20318. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20319. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20320. }
  20321. }
  20322. if (parsedSound.connectedMeshId) {
  20323. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20324. if (connectedMesh) {
  20325. newSound.attachToMesh(connectedMesh);
  20326. }
  20327. }
  20328. };
  20329. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20330. names = (names instanceof Array) ? names : [names];
  20331. for (var i in names) {
  20332. if (mesh.name === names[i]) {
  20333. hierarchyIds.push(mesh.id);
  20334. return true;
  20335. }
  20336. }
  20337. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20338. hierarchyIds.push(mesh.id);
  20339. return true;
  20340. }
  20341. return false;
  20342. };
  20343. var importVertexData = function (parsedVertexData, geometry) {
  20344. var vertexData = new BABYLON.VertexData();
  20345. // positions
  20346. var positions = parsedVertexData.positions;
  20347. if (positions) {
  20348. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20349. }
  20350. // normals
  20351. var normals = parsedVertexData.normals;
  20352. if (normals) {
  20353. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20354. }
  20355. // uvs
  20356. var uvs = parsedVertexData.uvs;
  20357. if (uvs) {
  20358. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20359. }
  20360. // uv2s
  20361. var uv2s = parsedVertexData.uv2s;
  20362. if (uv2s) {
  20363. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20364. }
  20365. // uv3s
  20366. var uv3s = parsedVertexData.uv3s;
  20367. if (uv3s) {
  20368. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20369. }
  20370. // uv4s
  20371. var uv4s = parsedVertexData.uv4s;
  20372. if (uv4s) {
  20373. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20374. }
  20375. // uv5s
  20376. var uv5s = parsedVertexData.uv5s;
  20377. if (uv5s) {
  20378. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20379. }
  20380. // uv6s
  20381. var uv6s = parsedVertexData.uv6s;
  20382. if (uv6s) {
  20383. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20384. }
  20385. // colors
  20386. var colors = parsedVertexData.colors;
  20387. if (colors) {
  20388. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20389. }
  20390. // matricesIndices
  20391. var matricesIndices = parsedVertexData.matricesIndices;
  20392. if (matricesIndices) {
  20393. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20394. }
  20395. // matricesWeights
  20396. var matricesWeights = parsedVertexData.matricesWeights;
  20397. if (matricesWeights) {
  20398. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20399. }
  20400. // indices
  20401. var indices = parsedVertexData.indices;
  20402. if (indices) {
  20403. vertexData.indices = indices;
  20404. }
  20405. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20406. };
  20407. var importGeometry = function (parsedGeometry, mesh) {
  20408. var scene = mesh.getScene();
  20409. // Geometry
  20410. var geometryId = parsedGeometry.geometryId;
  20411. if (geometryId) {
  20412. var geometry = scene.getGeometryByID(geometryId);
  20413. if (geometry) {
  20414. geometry.applyToMesh(mesh);
  20415. }
  20416. }
  20417. else if (parsedGeometry instanceof ArrayBuffer) {
  20418. var binaryInfo = mesh._binaryInfo;
  20419. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20420. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20421. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20422. }
  20423. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20424. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20425. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20426. }
  20427. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20428. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20429. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20430. }
  20431. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20432. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20433. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20434. }
  20435. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20436. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20437. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20438. }
  20439. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20440. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20441. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20442. }
  20443. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20444. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20445. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20446. }
  20447. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20448. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20449. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20450. }
  20451. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20452. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20453. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20454. }
  20455. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20456. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20457. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20458. }
  20459. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20460. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20461. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20462. }
  20463. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20464. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20465. mesh.setIndices(indicesData);
  20466. }
  20467. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20468. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20469. mesh.subMeshes = [];
  20470. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20471. var materialIndex = subMeshesData[(i * 5) + 0];
  20472. var verticesStart = subMeshesData[(i * 5) + 1];
  20473. var verticesCount = subMeshesData[(i * 5) + 2];
  20474. var indexStart = subMeshesData[(i * 5) + 3];
  20475. var indexCount = subMeshesData[(i * 5) + 4];
  20476. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20477. }
  20478. }
  20479. }
  20480. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20481. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20482. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20483. if (parsedGeometry.uvs) {
  20484. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20485. }
  20486. if (parsedGeometry.uvs2) {
  20487. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20488. }
  20489. if (parsedGeometry.uvs3) {
  20490. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20491. }
  20492. if (parsedGeometry.uvs4) {
  20493. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20494. }
  20495. if (parsedGeometry.uvs5) {
  20496. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20497. }
  20498. if (parsedGeometry.uvs6) {
  20499. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20500. }
  20501. if (parsedGeometry.colors) {
  20502. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20503. }
  20504. if (parsedGeometry.matricesIndices) {
  20505. if (!parsedGeometry.matricesIndices._isExpanded) {
  20506. var floatIndices = [];
  20507. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20508. var matricesIndex = parsedGeometry.matricesIndices[i];
  20509. floatIndices.push(matricesIndex & 0x000000FF);
  20510. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20511. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20512. floatIndices.push(matricesIndex >> 24);
  20513. }
  20514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20515. }
  20516. else {
  20517. delete parsedGeometry.matricesIndices._isExpanded;
  20518. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20519. }
  20520. }
  20521. if (parsedGeometry.matricesIndicesExtra) {
  20522. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  20523. var floatIndices = [];
  20524. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  20525. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  20526. floatIndices.push(matricesIndex & 0x000000FF);
  20527. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20528. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20529. floatIndices.push(matricesIndex >> 24);
  20530. }
  20531. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  20532. }
  20533. else {
  20534. delete parsedGeometry.matricesIndices._isExpanded;
  20535. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  20536. }
  20537. }
  20538. if (parsedGeometry.matricesWeights) {
  20539. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20540. }
  20541. if (parsedGeometry.matricesWeightsExtra) {
  20542. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  20543. }
  20544. mesh.setIndices(parsedGeometry.indices);
  20545. }
  20546. // SubMeshes
  20547. if (parsedGeometry.subMeshes) {
  20548. mesh.subMeshes = [];
  20549. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20550. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20551. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20552. }
  20553. }
  20554. // Flat shading
  20555. if (mesh._shouldGenerateFlatShading) {
  20556. mesh.convertToFlatShadedMesh();
  20557. delete mesh._shouldGenerateFlatShading;
  20558. }
  20559. // Update
  20560. mesh.computeWorldMatrix(true);
  20561. // Octree
  20562. if (scene._selectionOctree) {
  20563. scene._selectionOctree.addMesh(mesh);
  20564. }
  20565. };
  20566. BABYLON.SceneLoader.RegisterPlugin({
  20567. extensions: ".babylon",
  20568. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20569. var parsedData = JSON.parse(data);
  20570. var loadedSkeletonsIds = [];
  20571. var loadedMaterialsIds = [];
  20572. var hierarchyIds = [];
  20573. for (var index = 0; index < parsedData.meshes.length; index++) {
  20574. var parsedMesh = parsedData.meshes[index];
  20575. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20576. if (meshesNames instanceof Array) {
  20577. // Remove found mesh name from list.
  20578. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20579. }
  20580. //Geometry?
  20581. if (parsedMesh.geometryId) {
  20582. //does the file contain geometries?
  20583. if (parsedData.geometries) {
  20584. //find the correct geometry and add it to the scene
  20585. var found = false;
  20586. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20587. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20588. return;
  20589. }
  20590. else {
  20591. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20592. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20593. switch (geometryType) {
  20594. case "boxes":
  20595. parseBox(parsedGeometryData, scene);
  20596. break;
  20597. case "spheres":
  20598. parseSphere(parsedGeometryData, scene);
  20599. break;
  20600. case "cylinders":
  20601. parseCylinder(parsedGeometryData, scene);
  20602. break;
  20603. case "toruses":
  20604. parseTorus(parsedGeometryData, scene);
  20605. break;
  20606. case "grounds":
  20607. parseGround(parsedGeometryData, scene);
  20608. break;
  20609. case "planes":
  20610. parsePlane(parsedGeometryData, scene);
  20611. break;
  20612. case "torusKnots":
  20613. parseTorusKnot(parsedGeometryData, scene);
  20614. break;
  20615. case "vertexData":
  20616. parseVertexData(parsedGeometryData, scene, rootUrl);
  20617. break;
  20618. }
  20619. found = true;
  20620. }
  20621. });
  20622. }
  20623. });
  20624. if (!found) {
  20625. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20626. }
  20627. }
  20628. }
  20629. // Material ?
  20630. if (parsedMesh.materialId) {
  20631. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20632. if (!materialFound && parsedData.multiMaterials) {
  20633. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20634. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20635. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20636. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20637. var subMatId = parsedMultiMaterial.materials[matIndex];
  20638. loadedMaterialsIds.push(subMatId);
  20639. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20640. }
  20641. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20642. parseMultiMaterial(parsedMultiMaterial, scene);
  20643. materialFound = true;
  20644. break;
  20645. }
  20646. }
  20647. }
  20648. if (!materialFound) {
  20649. loadedMaterialsIds.push(parsedMesh.materialId);
  20650. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20651. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20652. }
  20653. }
  20654. }
  20655. // Skeleton ?
  20656. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20657. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20658. if (!skeletonAlreadyLoaded) {
  20659. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20660. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20661. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20662. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20663. loadedSkeletonsIds.push(parsedSkeleton.id);
  20664. }
  20665. }
  20666. }
  20667. }
  20668. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20669. meshes.push(mesh);
  20670. }
  20671. }
  20672. // Connecting parents
  20673. for (index = 0; index < scene.meshes.length; index++) {
  20674. var currentMesh = scene.meshes[index];
  20675. if (currentMesh._waitingParentId) {
  20676. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20677. currentMesh._waitingParentId = undefined;
  20678. }
  20679. }
  20680. // freeze world matrix application
  20681. for (index = 0; index < scene.meshes.length; index++) {
  20682. var currentMesh = scene.meshes[index];
  20683. if (currentMesh._waitingFreezeWorldMatrix) {
  20684. currentMesh.freezeWorldMatrix();
  20685. currentMesh._waitingFreezeWorldMatrix = undefined;
  20686. }
  20687. }
  20688. // Particles
  20689. if (parsedData.particleSystems) {
  20690. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20691. var parsedParticleSystem = parsedData.particleSystems[index];
  20692. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20693. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20694. }
  20695. }
  20696. }
  20697. return true;
  20698. },
  20699. load: function (scene, data, rootUrl) {
  20700. var parsedData = JSON.parse(data);
  20701. // Scene
  20702. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20703. scene.autoClear = parsedData.autoClear;
  20704. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20705. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20706. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20707. // Fog
  20708. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20709. scene.fogMode = parsedData.fogMode;
  20710. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20711. scene.fogStart = parsedData.fogStart;
  20712. scene.fogEnd = parsedData.fogEnd;
  20713. scene.fogDensity = parsedData.fogDensity;
  20714. }
  20715. // Lights
  20716. for (var index = 0; index < parsedData.lights.length; index++) {
  20717. var parsedLight = parsedData.lights[index];
  20718. parseLight(parsedLight, scene);
  20719. }
  20720. // Materials
  20721. if (parsedData.materials) {
  20722. for (index = 0; index < parsedData.materials.length; index++) {
  20723. var parsedMaterial = parsedData.materials[index];
  20724. parseMaterial(parsedMaterial, scene, rootUrl);
  20725. }
  20726. }
  20727. if (parsedData.multiMaterials) {
  20728. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20729. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20730. parseMultiMaterial(parsedMultiMaterial, scene);
  20731. }
  20732. }
  20733. // Skeletons
  20734. if (parsedData.skeletons) {
  20735. for (index = 0; index < parsedData.skeletons.length; index++) {
  20736. var parsedSkeleton = parsedData.skeletons[index];
  20737. parseSkeleton(parsedSkeleton, scene);
  20738. }
  20739. }
  20740. // Geometries
  20741. var geometries = parsedData.geometries;
  20742. if (geometries) {
  20743. // Boxes
  20744. var boxes = geometries.boxes;
  20745. if (boxes) {
  20746. for (index = 0; index < boxes.length; index++) {
  20747. var parsedBox = boxes[index];
  20748. parseBox(parsedBox, scene);
  20749. }
  20750. }
  20751. // Spheres
  20752. var spheres = geometries.spheres;
  20753. if (spheres) {
  20754. for (index = 0; index < spheres.length; index++) {
  20755. var parsedSphere = spheres[index];
  20756. parseSphere(parsedSphere, scene);
  20757. }
  20758. }
  20759. // Cylinders
  20760. var cylinders = geometries.cylinders;
  20761. if (cylinders) {
  20762. for (index = 0; index < cylinders.length; index++) {
  20763. var parsedCylinder = cylinders[index];
  20764. parseCylinder(parsedCylinder, scene);
  20765. }
  20766. }
  20767. // Toruses
  20768. var toruses = geometries.toruses;
  20769. if (toruses) {
  20770. for (index = 0; index < toruses.length; index++) {
  20771. var parsedTorus = toruses[index];
  20772. parseTorus(parsedTorus, scene);
  20773. }
  20774. }
  20775. // Grounds
  20776. var grounds = geometries.grounds;
  20777. if (grounds) {
  20778. for (index = 0; index < grounds.length; index++) {
  20779. var parsedGround = grounds[index];
  20780. parseGround(parsedGround, scene);
  20781. }
  20782. }
  20783. // Planes
  20784. var planes = geometries.planes;
  20785. if (planes) {
  20786. for (index = 0; index < planes.length; index++) {
  20787. var parsedPlane = planes[index];
  20788. parsePlane(parsedPlane, scene);
  20789. }
  20790. }
  20791. // TorusKnots
  20792. var torusKnots = geometries.torusKnots;
  20793. if (torusKnots) {
  20794. for (index = 0; index < torusKnots.length; index++) {
  20795. var parsedTorusKnot = torusKnots[index];
  20796. parseTorusKnot(parsedTorusKnot, scene);
  20797. }
  20798. }
  20799. // VertexData
  20800. var vertexData = geometries.vertexData;
  20801. if (vertexData) {
  20802. for (index = 0; index < vertexData.length; index++) {
  20803. var parsedVertexData = vertexData[index];
  20804. parseVertexData(parsedVertexData, scene, rootUrl);
  20805. }
  20806. }
  20807. }
  20808. // Meshes
  20809. for (index = 0; index < parsedData.meshes.length; index++) {
  20810. var parsedMesh = parsedData.meshes[index];
  20811. parseMesh(parsedMesh, scene, rootUrl);
  20812. }
  20813. // Cameras
  20814. for (index = 0; index < parsedData.cameras.length; index++) {
  20815. var parsedCamera = parsedData.cameras[index];
  20816. parseCamera(parsedCamera, scene);
  20817. }
  20818. if (parsedData.activeCameraID) {
  20819. scene.setActiveCameraByID(parsedData.activeCameraID);
  20820. }
  20821. // Browsing all the graph to connect the dots
  20822. for (index = 0; index < scene.cameras.length; index++) {
  20823. var camera = scene.cameras[index];
  20824. if (camera._waitingParentId) {
  20825. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20826. camera._waitingParentId = undefined;
  20827. }
  20828. }
  20829. for (index = 0; index < scene.lights.length; index++) {
  20830. var light = scene.lights[index];
  20831. if (light._waitingParentId) {
  20832. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20833. light._waitingParentId = undefined;
  20834. }
  20835. }
  20836. // Sounds
  20837. if (BABYLON.AudioEngine && parsedData.sounds) {
  20838. for (index = 0; index < parsedData.sounds.length; index++) {
  20839. var parsedSound = parsedData.sounds[index];
  20840. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20841. parseSound(parsedSound, scene, rootUrl);
  20842. }
  20843. else {
  20844. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20845. }
  20846. }
  20847. }
  20848. // Connect parents & children and parse actions
  20849. for (index = 0; index < scene.meshes.length; index++) {
  20850. var mesh = scene.meshes[index];
  20851. if (mesh._waitingParentId) {
  20852. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20853. mesh._waitingParentId = undefined;
  20854. }
  20855. if (mesh._waitingActions) {
  20856. parseActions(mesh._waitingActions, mesh, scene);
  20857. mesh._waitingActions = undefined;
  20858. }
  20859. }
  20860. // freeze world matrix application
  20861. for (index = 0; index < scene.meshes.length; index++) {
  20862. var currentMesh = scene.meshes[index];
  20863. if (currentMesh._waitingFreezeWorldMatrix) {
  20864. currentMesh.freezeWorldMatrix();
  20865. currentMesh._waitingFreezeWorldMatrix = undefined;
  20866. }
  20867. }
  20868. // Particles Systems
  20869. if (parsedData.particleSystems) {
  20870. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20871. var parsedParticleSystem = parsedData.particleSystems[index];
  20872. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20873. }
  20874. }
  20875. // Lens flares
  20876. if (parsedData.lensFlareSystems) {
  20877. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20878. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20879. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20880. }
  20881. }
  20882. // Shadows
  20883. if (parsedData.shadowGenerators) {
  20884. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20885. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20886. parseShadowGenerator(parsedShadowGenerator, scene);
  20887. }
  20888. }
  20889. // Actions (scene)
  20890. if (parsedData.actions) {
  20891. parseActions(parsedData.actions, null, scene);
  20892. }
  20893. // Finish
  20894. return true;
  20895. }
  20896. });
  20897. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20898. })(BABYLON || (BABYLON = {}));
  20899. var BABYLON;
  20900. (function (BABYLON) {
  20901. var SpriteManager = (function () {
  20902. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20903. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20904. this.name = name;
  20905. this.cellSize = cellSize;
  20906. this.sprites = new Array();
  20907. this.renderingGroupId = 0;
  20908. this.layerMask = 0x0FFFFFFF;
  20909. this.fogEnabled = true;
  20910. this.isPickable = false;
  20911. this._vertexDeclaration = [4, 4, 4, 4];
  20912. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20913. this._capacity = capacity;
  20914. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20915. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20916. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20917. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20918. this._scene = scene;
  20919. this._scene.spriteManagers.push(this);
  20920. // VBO
  20921. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20922. var indices = [];
  20923. var index = 0;
  20924. for (var count = 0; count < capacity; count++) {
  20925. indices.push(index);
  20926. indices.push(index + 1);
  20927. indices.push(index + 2);
  20928. indices.push(index);
  20929. indices.push(index + 2);
  20930. indices.push(index + 3);
  20931. index += 4;
  20932. }
  20933. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20934. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20935. // Effects
  20936. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20937. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20938. }
  20939. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20940. var arrayOffset = index * 16;
  20941. if (offsetX === 0)
  20942. offsetX = this._epsilon;
  20943. else if (offsetX === 1)
  20944. offsetX = 1 - this._epsilon;
  20945. if (offsetY === 0)
  20946. offsetY = this._epsilon;
  20947. else if (offsetY === 1)
  20948. offsetY = 1 - this._epsilon;
  20949. this._vertices[arrayOffset] = sprite.position.x;
  20950. this._vertices[arrayOffset + 1] = sprite.position.y;
  20951. this._vertices[arrayOffset + 2] = sprite.position.z;
  20952. this._vertices[arrayOffset + 3] = sprite.angle;
  20953. this._vertices[arrayOffset + 4] = sprite.width;
  20954. this._vertices[arrayOffset + 5] = sprite.height;
  20955. this._vertices[arrayOffset + 6] = offsetX;
  20956. this._vertices[arrayOffset + 7] = offsetY;
  20957. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20958. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20959. var offset = (sprite.cellIndex / rowSize) >> 0;
  20960. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20961. this._vertices[arrayOffset + 11] = offset;
  20962. // Color
  20963. this._vertices[arrayOffset + 12] = sprite.color.r;
  20964. this._vertices[arrayOffset + 13] = sprite.color.g;
  20965. this._vertices[arrayOffset + 14] = sprite.color.b;
  20966. this._vertices[arrayOffset + 15] = sprite.color.a;
  20967. };
  20968. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20969. var count = Math.min(this._capacity, this.sprites.length);
  20970. var min = BABYLON.Vector3.Zero();
  20971. var max = BABYLON.Vector3.Zero();
  20972. var distance = Number.MAX_VALUE;
  20973. var currentSprite;
  20974. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20975. var cameraView = camera.getViewMatrix();
  20976. for (var index = 0; index < count; index++) {
  20977. var sprite = this.sprites[index];
  20978. if (!sprite) {
  20979. continue;
  20980. }
  20981. if (predicate) {
  20982. if (!predicate(sprite)) {
  20983. continue;
  20984. }
  20985. }
  20986. else if (!sprite.isPickable) {
  20987. continue;
  20988. }
  20989. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20990. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20991. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20992. if (ray.intersectsBoxMinMax(min, max)) {
  20993. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20994. if (distance > currentDistance) {
  20995. distance = currentDistance;
  20996. currentSprite = sprite;
  20997. if (fastCheck) {
  20998. break;
  20999. }
  21000. }
  21001. }
  21002. }
  21003. if (currentSprite) {
  21004. var result = new BABYLON.PickingInfo();
  21005. result.hit = true;
  21006. result.pickedSprite = currentSprite;
  21007. result.distance = distance;
  21008. return result;
  21009. }
  21010. return null;
  21011. };
  21012. SpriteManager.prototype.render = function () {
  21013. // Check
  21014. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21015. return;
  21016. var engine = this._scene.getEngine();
  21017. var baseSize = this._spriteTexture.getBaseSize();
  21018. // Sprites
  21019. var deltaTime = engine.getDeltaTime();
  21020. var max = Math.min(this._capacity, this.sprites.length);
  21021. var rowSize = baseSize.width / this.cellSize;
  21022. var offset = 0;
  21023. for (var index = 0; index < max; index++) {
  21024. var sprite = this.sprites[index];
  21025. if (!sprite) {
  21026. continue;
  21027. }
  21028. sprite._animate(deltaTime);
  21029. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21030. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21031. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21032. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21033. }
  21034. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21035. // Render
  21036. var effect = this._effectBase;
  21037. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21038. effect = this._effectFog;
  21039. }
  21040. engine.enableEffect(effect);
  21041. var viewMatrix = this._scene.getViewMatrix();
  21042. effect.setTexture("diffuseSampler", this._spriteTexture);
  21043. effect.setMatrix("view", viewMatrix);
  21044. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21045. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21046. // Fog
  21047. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21048. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21049. effect.setColor3("vFogColor", this._scene.fogColor);
  21050. }
  21051. // VBOs
  21052. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21053. // Draw order
  21054. engine.setDepthFunctionToLessOrEqual();
  21055. effect.setBool("alphaTest", true);
  21056. engine.setColorWrite(false);
  21057. engine.draw(true, 0, max * 6);
  21058. engine.setColorWrite(true);
  21059. effect.setBool("alphaTest", false);
  21060. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21061. engine.draw(true, 0, max * 6);
  21062. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21063. };
  21064. SpriteManager.prototype.dispose = function () {
  21065. if (this._vertexBuffer) {
  21066. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21067. this._vertexBuffer = null;
  21068. }
  21069. if (this._indexBuffer) {
  21070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21071. this._indexBuffer = null;
  21072. }
  21073. if (this._spriteTexture) {
  21074. this._spriteTexture.dispose();
  21075. this._spriteTexture = null;
  21076. }
  21077. // Remove from scene
  21078. var index = this._scene.spriteManagers.indexOf(this);
  21079. this._scene.spriteManagers.splice(index, 1);
  21080. // Callback
  21081. if (this.onDispose) {
  21082. this.onDispose();
  21083. }
  21084. };
  21085. return SpriteManager;
  21086. })();
  21087. BABYLON.SpriteManager = SpriteManager;
  21088. })(BABYLON || (BABYLON = {}));
  21089. var BABYLON;
  21090. (function (BABYLON) {
  21091. var Sprite = (function () {
  21092. function Sprite(name, manager) {
  21093. this.name = name;
  21094. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21095. this.width = 1.0;
  21096. this.height = 1.0;
  21097. this.angle = 0;
  21098. this.cellIndex = 0;
  21099. this.invertU = 0;
  21100. this.invertV = 0;
  21101. this.animations = new Array();
  21102. this.isPickable = false;
  21103. this._animationStarted = false;
  21104. this._loopAnimation = false;
  21105. this._fromIndex = 0;
  21106. this._toIndex = 0;
  21107. this._delay = 0;
  21108. this._direction = 1;
  21109. this._frameCount = 0;
  21110. this._time = 0;
  21111. this._manager = manager;
  21112. this._manager.sprites.push(this);
  21113. this.position = BABYLON.Vector3.Zero();
  21114. }
  21115. Object.defineProperty(Sprite.prototype, "size", {
  21116. get: function () {
  21117. return this.width;
  21118. },
  21119. set: function (value) {
  21120. this.width = value;
  21121. this.height = value;
  21122. },
  21123. enumerable: true,
  21124. configurable: true
  21125. });
  21126. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21127. this._fromIndex = from;
  21128. this._toIndex = to;
  21129. this._loopAnimation = loop;
  21130. this._delay = delay;
  21131. this._animationStarted = true;
  21132. this._direction = from < to ? 1 : -1;
  21133. this.cellIndex = from;
  21134. this._time = 0;
  21135. };
  21136. Sprite.prototype.stopAnimation = function () {
  21137. this._animationStarted = false;
  21138. };
  21139. Sprite.prototype._animate = function (deltaTime) {
  21140. if (!this._animationStarted)
  21141. return;
  21142. this._time += deltaTime;
  21143. if (this._time > this._delay) {
  21144. this._time = this._time % this._delay;
  21145. this.cellIndex += this._direction;
  21146. if (this.cellIndex == this._toIndex) {
  21147. if (this._loopAnimation) {
  21148. this.cellIndex = this._fromIndex;
  21149. }
  21150. else {
  21151. this._animationStarted = false;
  21152. if (this.disposeWhenFinishedAnimating) {
  21153. this.dispose();
  21154. }
  21155. }
  21156. }
  21157. }
  21158. };
  21159. Sprite.prototype.dispose = function () {
  21160. for (var i = 0; i < this._manager.sprites.length; i++) {
  21161. if (this._manager.sprites[i] == this) {
  21162. this._manager.sprites.splice(i, 1);
  21163. }
  21164. }
  21165. };
  21166. return Sprite;
  21167. })();
  21168. BABYLON.Sprite = Sprite;
  21169. })(BABYLON || (BABYLON = {}));
  21170. var BABYLON;
  21171. (function (BABYLON) {
  21172. var Layer = (function () {
  21173. function Layer(name, imgUrl, scene, isBackground, color) {
  21174. this.name = name;
  21175. this._vertexDeclaration = [2];
  21176. this._vertexStrideSize = 2 * 4;
  21177. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21178. this.isBackground = isBackground === undefined ? true : isBackground;
  21179. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21180. this._scene = scene;
  21181. this._scene.layers.push(this);
  21182. // VBO
  21183. var vertices = [];
  21184. vertices.push(1, 1);
  21185. vertices.push(-1, 1);
  21186. vertices.push(-1, -1);
  21187. vertices.push(1, -1);
  21188. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21189. // Indices
  21190. var indices = [];
  21191. indices.push(0);
  21192. indices.push(1);
  21193. indices.push(2);
  21194. indices.push(0);
  21195. indices.push(2);
  21196. indices.push(3);
  21197. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21198. // Effects
  21199. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21200. }
  21201. Layer.prototype.render = function () {
  21202. // Check
  21203. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21204. return;
  21205. var engine = this._scene.getEngine();
  21206. // Render
  21207. engine.enableEffect(this._effect);
  21208. engine.setState(false);
  21209. // Texture
  21210. this._effect.setTexture("textureSampler", this.texture);
  21211. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21212. // Color
  21213. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21214. // VBOs
  21215. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21216. // Draw order
  21217. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21218. engine.draw(true, 0, 6);
  21219. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21220. };
  21221. Layer.prototype.dispose = function () {
  21222. if (this._vertexBuffer) {
  21223. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21224. this._vertexBuffer = null;
  21225. }
  21226. if (this._indexBuffer) {
  21227. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21228. this._indexBuffer = null;
  21229. }
  21230. if (this.texture) {
  21231. this.texture.dispose();
  21232. this.texture = null;
  21233. }
  21234. // Remove from scene
  21235. var index = this._scene.layers.indexOf(this);
  21236. this._scene.layers.splice(index, 1);
  21237. // Callback
  21238. if (this.onDispose) {
  21239. this.onDispose();
  21240. }
  21241. };
  21242. return Layer;
  21243. })();
  21244. BABYLON.Layer = Layer;
  21245. })(BABYLON || (BABYLON = {}));
  21246. var BABYLON;
  21247. (function (BABYLON) {
  21248. var Particle = (function () {
  21249. function Particle() {
  21250. this.position = BABYLON.Vector3.Zero();
  21251. this.direction = BABYLON.Vector3.Zero();
  21252. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21253. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21254. this.lifeTime = 1.0;
  21255. this.age = 0;
  21256. this.size = 0;
  21257. this.angle = 0;
  21258. this.angularSpeed = 0;
  21259. }
  21260. Particle.prototype.copyTo = function (other) {
  21261. other.position.copyFrom(this.position);
  21262. other.direction.copyFrom(this.direction);
  21263. other.color.copyFrom(this.color);
  21264. other.colorStep.copyFrom(this.colorStep);
  21265. other.lifeTime = this.lifeTime;
  21266. other.age = this.age;
  21267. other.size = this.size;
  21268. other.angle = this.angle;
  21269. other.angularSpeed = this.angularSpeed;
  21270. };
  21271. return Particle;
  21272. })();
  21273. BABYLON.Particle = Particle;
  21274. })(BABYLON || (BABYLON = {}));
  21275. var BABYLON;
  21276. (function (BABYLON) {
  21277. var randomNumber = function (min, max) {
  21278. if (min === max) {
  21279. return (min);
  21280. }
  21281. var random = Math.random();
  21282. return ((random * (max - min)) + min);
  21283. };
  21284. var ParticleSystem = (function () {
  21285. function ParticleSystem(name, capacity, scene, customEffect) {
  21286. var _this = this;
  21287. this.name = name;
  21288. this.renderingGroupId = 0;
  21289. this.emitter = null;
  21290. this.emitRate = 10;
  21291. this.manualEmitCount = -1;
  21292. this.updateSpeed = 0.01;
  21293. this.targetStopDuration = 0;
  21294. this.disposeOnStop = false;
  21295. this.minEmitPower = 1;
  21296. this.maxEmitPower = 1;
  21297. this.minLifeTime = 1;
  21298. this.maxLifeTime = 1;
  21299. this.minSize = 1;
  21300. this.maxSize = 1;
  21301. this.minAngularSpeed = 0;
  21302. this.maxAngularSpeed = 0;
  21303. this.layerMask = 0x0FFFFFFF;
  21304. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21305. this.forceDepthWrite = false;
  21306. this.gravity = BABYLON.Vector3.Zero();
  21307. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21308. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21309. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21310. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21311. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21312. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21313. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21314. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21315. this.particles = new Array();
  21316. this._vertexDeclaration = [3, 4, 4];
  21317. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21318. this._stockParticles = new Array();
  21319. this._newPartsExcess = 0;
  21320. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21321. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21322. this._scaledDirection = BABYLON.Vector3.Zero();
  21323. this._scaledGravity = BABYLON.Vector3.Zero();
  21324. this._currentRenderId = -1;
  21325. this._started = false;
  21326. this._stopped = false;
  21327. this._actualFrame = 0;
  21328. this.id = name;
  21329. this._capacity = capacity;
  21330. this._scene = scene;
  21331. this._customEffect = customEffect;
  21332. scene.particleSystems.push(this);
  21333. // VBO
  21334. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21335. var indices = [];
  21336. var index = 0;
  21337. for (var count = 0; count < capacity; count++) {
  21338. indices.push(index);
  21339. indices.push(index + 1);
  21340. indices.push(index + 2);
  21341. indices.push(index);
  21342. indices.push(index + 2);
  21343. indices.push(index + 3);
  21344. index += 4;
  21345. }
  21346. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21347. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21348. // Default behaviors
  21349. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21350. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21351. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21352. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21353. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21354. };
  21355. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21356. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21357. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21358. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21359. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21360. };
  21361. this.updateFunction = function (particles) {
  21362. for (var index = 0; index < particles.length; index++) {
  21363. var particle = particles[index];
  21364. particle.age += _this._scaledUpdateSpeed;
  21365. if (particle.age >= particle.lifeTime) {
  21366. _this.recycleParticle(particle);
  21367. index--;
  21368. continue;
  21369. }
  21370. else {
  21371. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21372. particle.color.addInPlace(_this._scaledColorStep);
  21373. if (particle.color.a < 0)
  21374. particle.color.a = 0;
  21375. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21376. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21377. particle.position.addInPlace(_this._scaledDirection);
  21378. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21379. particle.direction.addInPlace(_this._scaledGravity);
  21380. }
  21381. }
  21382. };
  21383. }
  21384. ParticleSystem.prototype.recycleParticle = function (particle) {
  21385. var lastParticle = this.particles.pop();
  21386. if (lastParticle !== particle) {
  21387. lastParticle.copyTo(particle);
  21388. this._stockParticles.push(lastParticle);
  21389. }
  21390. };
  21391. ParticleSystem.prototype.getCapacity = function () {
  21392. return this._capacity;
  21393. };
  21394. ParticleSystem.prototype.isAlive = function () {
  21395. return this._alive;
  21396. };
  21397. ParticleSystem.prototype.isStarted = function () {
  21398. return this._started;
  21399. };
  21400. ParticleSystem.prototype.start = function () {
  21401. this._started = true;
  21402. this._stopped = false;
  21403. this._actualFrame = 0;
  21404. };
  21405. ParticleSystem.prototype.stop = function () {
  21406. this._stopped = true;
  21407. };
  21408. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21409. var offset = index * 11;
  21410. this._vertices[offset] = particle.position.x;
  21411. this._vertices[offset + 1] = particle.position.y;
  21412. this._vertices[offset + 2] = particle.position.z;
  21413. this._vertices[offset + 3] = particle.color.r;
  21414. this._vertices[offset + 4] = particle.color.g;
  21415. this._vertices[offset + 5] = particle.color.b;
  21416. this._vertices[offset + 6] = particle.color.a;
  21417. this._vertices[offset + 7] = particle.angle;
  21418. this._vertices[offset + 8] = particle.size;
  21419. this._vertices[offset + 9] = offsetX;
  21420. this._vertices[offset + 10] = offsetY;
  21421. };
  21422. ParticleSystem.prototype._update = function (newParticles) {
  21423. // Update current
  21424. this._alive = this.particles.length > 0;
  21425. this.updateFunction(this.particles);
  21426. // Add new ones
  21427. var worldMatrix;
  21428. if (this.emitter.position) {
  21429. worldMatrix = this.emitter.getWorldMatrix();
  21430. }
  21431. else {
  21432. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21433. }
  21434. for (var index = 0; index < newParticles; index++) {
  21435. if (this.particles.length === this._capacity) {
  21436. break;
  21437. }
  21438. if (this._stockParticles.length !== 0) {
  21439. var particle = this._stockParticles.pop();
  21440. particle.age = 0;
  21441. }
  21442. else {
  21443. particle = new BABYLON.Particle();
  21444. }
  21445. this.particles.push(particle);
  21446. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21447. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21448. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21449. particle.size = randomNumber(this.minSize, this.maxSize);
  21450. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21451. this.startPositionFunction(worldMatrix, particle.position);
  21452. var step = randomNumber(0, 1.0);
  21453. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21454. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21455. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21456. }
  21457. };
  21458. ParticleSystem.prototype._getEffect = function () {
  21459. if (this._customEffect) {
  21460. return this._customEffect;
  21461. }
  21462. ;
  21463. var defines = [];
  21464. if (this._scene.clipPlane) {
  21465. defines.push("#define CLIPPLANE");
  21466. }
  21467. // Effect
  21468. var join = defines.join("\n");
  21469. if (this._cachedDefines !== join) {
  21470. this._cachedDefines = join;
  21471. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21472. }
  21473. return this._effect;
  21474. };
  21475. ParticleSystem.prototype.animate = function () {
  21476. if (!this._started)
  21477. return;
  21478. var effect = this._getEffect();
  21479. // Check
  21480. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21481. return;
  21482. if (this._currentRenderId === this._scene.getRenderId()) {
  21483. return;
  21484. }
  21485. this._currentRenderId = this._scene.getRenderId();
  21486. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21487. // determine the number of particles we need to create
  21488. var emitCout;
  21489. if (this.manualEmitCount > -1) {
  21490. emitCout = this.manualEmitCount;
  21491. this.manualEmitCount = 0;
  21492. }
  21493. else {
  21494. emitCout = this.emitRate;
  21495. }
  21496. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21497. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21498. if (this._newPartsExcess > 1.0) {
  21499. newParticles += this._newPartsExcess >> 0;
  21500. this._newPartsExcess -= this._newPartsExcess >> 0;
  21501. }
  21502. this._alive = false;
  21503. if (!this._stopped) {
  21504. this._actualFrame += this._scaledUpdateSpeed;
  21505. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21506. this.stop();
  21507. }
  21508. else {
  21509. newParticles = 0;
  21510. }
  21511. this._update(newParticles);
  21512. // Stopped?
  21513. if (this._stopped) {
  21514. if (!this._alive) {
  21515. this._started = false;
  21516. if (this.disposeOnStop) {
  21517. this._scene._toBeDisposed.push(this);
  21518. }
  21519. }
  21520. }
  21521. // Update VBO
  21522. var offset = 0;
  21523. for (var index = 0; index < this.particles.length; index++) {
  21524. var particle = this.particles[index];
  21525. this._appendParticleVertex(offset++, particle, 0, 0);
  21526. this._appendParticleVertex(offset++, particle, 1, 0);
  21527. this._appendParticleVertex(offset++, particle, 1, 1);
  21528. this._appendParticleVertex(offset++, particle, 0, 1);
  21529. }
  21530. var engine = this._scene.getEngine();
  21531. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21532. };
  21533. ParticleSystem.prototype.render = function () {
  21534. var effect = this._getEffect();
  21535. // Check
  21536. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21537. return 0;
  21538. var engine = this._scene.getEngine();
  21539. // Render
  21540. engine.enableEffect(effect);
  21541. engine.setState(false);
  21542. var viewMatrix = this._scene.getViewMatrix();
  21543. effect.setTexture("diffuseSampler", this.particleTexture);
  21544. effect.setMatrix("view", viewMatrix);
  21545. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21546. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21547. if (this._scene.clipPlane) {
  21548. var clipPlane = this._scene.clipPlane;
  21549. var invView = viewMatrix.clone();
  21550. invView.invert();
  21551. effect.setMatrix("invView", invView);
  21552. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21553. }
  21554. // VBOs
  21555. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21556. // Draw order
  21557. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21558. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21559. }
  21560. else {
  21561. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21562. }
  21563. if (this.forceDepthWrite) {
  21564. engine.setDepthWrite(true);
  21565. }
  21566. engine.draw(true, 0, this.particles.length * 6);
  21567. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21568. return this.particles.length;
  21569. };
  21570. ParticleSystem.prototype.dispose = function () {
  21571. if (this._vertexBuffer) {
  21572. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21573. this._vertexBuffer = null;
  21574. }
  21575. if (this._indexBuffer) {
  21576. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21577. this._indexBuffer = null;
  21578. }
  21579. if (this.particleTexture) {
  21580. this.particleTexture.dispose();
  21581. this.particleTexture = null;
  21582. }
  21583. // Remove from scene
  21584. var index = this._scene.particleSystems.indexOf(this);
  21585. this._scene.particleSystems.splice(index, 1);
  21586. // Callback
  21587. if (this.onDispose) {
  21588. this.onDispose();
  21589. }
  21590. };
  21591. // Clone
  21592. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21593. var result = new ParticleSystem(name, this._capacity, this._scene);
  21594. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21595. if (newEmitter === undefined) {
  21596. newEmitter = this.emitter;
  21597. }
  21598. result.emitter = newEmitter;
  21599. if (this.particleTexture) {
  21600. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21601. }
  21602. result.start();
  21603. return result;
  21604. };
  21605. // Statics
  21606. ParticleSystem.BLENDMODE_ONEONE = 0;
  21607. ParticleSystem.BLENDMODE_STANDARD = 1;
  21608. return ParticleSystem;
  21609. })();
  21610. BABYLON.ParticleSystem = ParticleSystem;
  21611. })(BABYLON || (BABYLON = {}));
  21612. var BABYLON;
  21613. (function (BABYLON) {
  21614. var AnimationRange = (function () {
  21615. function AnimationRange(name, from, to) {
  21616. this.name = name;
  21617. this.from = from;
  21618. this.to = to;
  21619. }
  21620. return AnimationRange;
  21621. })();
  21622. BABYLON.AnimationRange = AnimationRange;
  21623. var Animation = (function () {
  21624. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21625. this.name = name;
  21626. this.targetProperty = targetProperty;
  21627. this.framePerSecond = framePerSecond;
  21628. this.dataType = dataType;
  21629. this.loopMode = loopMode;
  21630. this._offsetsCache = {};
  21631. this._highLimitsCache = {};
  21632. this._stopped = false;
  21633. this.allowMatricesInterpolation = false;
  21634. this._ranges = new Array();
  21635. this.targetPropertyPath = targetProperty.split(".");
  21636. this.dataType = dataType;
  21637. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21638. }
  21639. Animation._PrepareAnimation = function (targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21640. var dataType = undefined;
  21641. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21642. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21643. }
  21644. else if (from instanceof BABYLON.Quaternion) {
  21645. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21646. }
  21647. else if (from instanceof BABYLON.Vector3) {
  21648. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21649. }
  21650. else if (from instanceof BABYLON.Vector2) {
  21651. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21652. }
  21653. else if (from instanceof BABYLON.Color3) {
  21654. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21655. }
  21656. if (dataType == undefined) {
  21657. return null;
  21658. }
  21659. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21660. var keys = [];
  21661. keys.push({ frame: 0, value: from });
  21662. keys.push({ frame: totalFrame, value: to });
  21663. animation.setKeys(keys);
  21664. if (easingFunction !== undefined) {
  21665. animation.setEasingFunction(easingFunction);
  21666. }
  21667. return animation;
  21668. };
  21669. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21670. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21671. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21672. };
  21673. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21674. var animation = Animation._PrepareAnimation(targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  21675. node.animations.push(animation);
  21676. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21677. };
  21678. // Methods
  21679. Animation.prototype.createRange = function (name, from, to) {
  21680. this._ranges.push(new AnimationRange(name, from, to));
  21681. };
  21682. Animation.prototype.deleteRange = function (name) {
  21683. for (var index = 0; index < this._ranges.length; index++) {
  21684. if (this._ranges[index].name === name) {
  21685. this._ranges.splice(index, 1);
  21686. return;
  21687. }
  21688. }
  21689. };
  21690. Animation.prototype.getRange = function (name) {
  21691. for (var index = 0; index < this._ranges.length; index++) {
  21692. if (this._ranges[index].name === name) {
  21693. return this._ranges[index];
  21694. }
  21695. }
  21696. return null;
  21697. };
  21698. Animation.prototype.reset = function () {
  21699. this._offsetsCache = {};
  21700. this._highLimitsCache = {};
  21701. this.currentFrame = 0;
  21702. };
  21703. Animation.prototype.isStopped = function () {
  21704. return this._stopped;
  21705. };
  21706. Animation.prototype.getKeys = function () {
  21707. return this._keys;
  21708. };
  21709. Animation.prototype.getEasingFunction = function () {
  21710. return this._easingFunction;
  21711. };
  21712. Animation.prototype.setEasingFunction = function (easingFunction) {
  21713. this._easingFunction = easingFunction;
  21714. };
  21715. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21716. return startValue + (endValue - startValue) * gradient;
  21717. };
  21718. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21719. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21720. };
  21721. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21722. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21723. };
  21724. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21725. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21726. };
  21727. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21728. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21729. };
  21730. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21731. var startScale = new BABYLON.Vector3(0, 0, 0);
  21732. var startRotation = new BABYLON.Quaternion();
  21733. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21734. startValue.decompose(startScale, startRotation, startTranslation);
  21735. var endScale = new BABYLON.Vector3(0, 0, 0);
  21736. var endRotation = new BABYLON.Quaternion();
  21737. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21738. endValue.decompose(endScale, endRotation, endTranslation);
  21739. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21740. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21741. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21742. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21743. return result;
  21744. };
  21745. Animation.prototype.clone = function () {
  21746. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21747. if (this._keys) {
  21748. clone.setKeys(this._keys);
  21749. }
  21750. return clone;
  21751. };
  21752. Animation.prototype.setKeys = function (values) {
  21753. this._keys = values.slice(0);
  21754. this._offsetsCache = {};
  21755. this._highLimitsCache = {};
  21756. };
  21757. Animation.prototype._getKeyValue = function (value) {
  21758. if (typeof value === "function") {
  21759. return value();
  21760. }
  21761. return value;
  21762. };
  21763. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21764. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21765. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21766. }
  21767. this.currentFrame = currentFrame;
  21768. // Try to get a hash to find the right key
  21769. 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));
  21770. if (this._keys[startKey].frame >= currentFrame) {
  21771. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21772. startKey--;
  21773. }
  21774. }
  21775. for (var key = startKey; key < this._keys.length; key++) {
  21776. if (this._keys[key + 1].frame >= currentFrame) {
  21777. var startValue = this._getKeyValue(this._keys[key].value);
  21778. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21779. // gradient : percent of currentFrame between the frame inf and the frame sup
  21780. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21781. // check for easingFunction and correction of gradient
  21782. if (this._easingFunction != null) {
  21783. gradient = this._easingFunction.ease(gradient);
  21784. }
  21785. switch (this.dataType) {
  21786. // Float
  21787. case Animation.ANIMATIONTYPE_FLOAT:
  21788. switch (loopMode) {
  21789. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21790. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21791. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21792. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21793. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21794. }
  21795. break;
  21796. // Quaternion
  21797. case Animation.ANIMATIONTYPE_QUATERNION:
  21798. var quaternion = null;
  21799. switch (loopMode) {
  21800. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21801. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21802. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21803. break;
  21804. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21805. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21806. break;
  21807. }
  21808. return quaternion;
  21809. // Vector3
  21810. case Animation.ANIMATIONTYPE_VECTOR3:
  21811. switch (loopMode) {
  21812. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21813. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21814. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21815. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21816. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21817. }
  21818. // Vector2
  21819. case Animation.ANIMATIONTYPE_VECTOR2:
  21820. switch (loopMode) {
  21821. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21822. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21823. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21824. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21825. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21826. }
  21827. // Color3
  21828. case Animation.ANIMATIONTYPE_COLOR3:
  21829. switch (loopMode) {
  21830. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21831. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21832. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21833. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21834. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21835. }
  21836. // Matrix
  21837. case Animation.ANIMATIONTYPE_MATRIX:
  21838. switch (loopMode) {
  21839. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21840. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21841. if (this.allowMatricesInterpolation) {
  21842. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21843. }
  21844. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21845. return startValue;
  21846. }
  21847. default:
  21848. break;
  21849. }
  21850. break;
  21851. }
  21852. }
  21853. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21854. };
  21855. Animation.prototype.setValue = function (currentValue) {
  21856. // Set value
  21857. if (this.targetPropertyPath.length > 1) {
  21858. var property = this._target[this.targetPropertyPath[0]];
  21859. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21860. property = property[this.targetPropertyPath[index]];
  21861. }
  21862. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21863. }
  21864. else {
  21865. this._target[this.targetPropertyPath[0]] = currentValue;
  21866. }
  21867. if (this._target.markAsDirty) {
  21868. this._target.markAsDirty(this.targetProperty);
  21869. }
  21870. };
  21871. Animation.prototype.goToFrame = function (frame) {
  21872. if (frame < this._keys[0].frame) {
  21873. frame = this._keys[0].frame;
  21874. }
  21875. else if (frame > this._keys[this._keys.length - 1].frame) {
  21876. frame = this._keys[this._keys.length - 1].frame;
  21877. }
  21878. var currentValue = this._interpolate(frame, 0, this.loopMode);
  21879. this.setValue(currentValue);
  21880. };
  21881. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21882. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21883. this._stopped = true;
  21884. return false;
  21885. }
  21886. var returnValue = true;
  21887. // Adding a start key at frame 0 if missing
  21888. if (this._keys[0].frame !== 0) {
  21889. var newKey = { frame: 0, value: this._keys[0].value };
  21890. this._keys.splice(0, 0, newKey);
  21891. }
  21892. // Check limits
  21893. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21894. from = this._keys[0].frame;
  21895. }
  21896. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21897. to = this._keys[this._keys.length - 1].frame;
  21898. }
  21899. // Compute ratio
  21900. var range = to - from;
  21901. var offsetValue;
  21902. // ratio represents the frame delta between from and to
  21903. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21904. var highLimitValue = 0;
  21905. if (ratio > range && !loop) {
  21906. returnValue = false;
  21907. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21908. }
  21909. else {
  21910. // Get max value if required
  21911. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21912. var keyOffset = to.toString() + from.toString();
  21913. if (!this._offsetsCache[keyOffset]) {
  21914. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21915. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21916. switch (this.dataType) {
  21917. // Float
  21918. case Animation.ANIMATIONTYPE_FLOAT:
  21919. this._offsetsCache[keyOffset] = toValue - fromValue;
  21920. break;
  21921. // Quaternion
  21922. case Animation.ANIMATIONTYPE_QUATERNION:
  21923. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21924. break;
  21925. // Vector3
  21926. case Animation.ANIMATIONTYPE_VECTOR3:
  21927. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21928. // Vector2
  21929. case Animation.ANIMATIONTYPE_VECTOR2:
  21930. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21931. // Color3
  21932. case Animation.ANIMATIONTYPE_COLOR3:
  21933. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21934. default:
  21935. break;
  21936. }
  21937. this._highLimitsCache[keyOffset] = toValue;
  21938. }
  21939. highLimitValue = this._highLimitsCache[keyOffset];
  21940. offsetValue = this._offsetsCache[keyOffset];
  21941. }
  21942. }
  21943. if (offsetValue === undefined) {
  21944. switch (this.dataType) {
  21945. // Float
  21946. case Animation.ANIMATIONTYPE_FLOAT:
  21947. offsetValue = 0;
  21948. break;
  21949. // Quaternion
  21950. case Animation.ANIMATIONTYPE_QUATERNION:
  21951. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21952. break;
  21953. // Vector3
  21954. case Animation.ANIMATIONTYPE_VECTOR3:
  21955. offsetValue = BABYLON.Vector3.Zero();
  21956. break;
  21957. // Vector2
  21958. case Animation.ANIMATIONTYPE_VECTOR2:
  21959. offsetValue = BABYLON.Vector2.Zero();
  21960. break;
  21961. // Color3
  21962. case Animation.ANIMATIONTYPE_COLOR3:
  21963. offsetValue = BABYLON.Color3.Black();
  21964. }
  21965. }
  21966. // Compute value
  21967. var repeatCount = (ratio / range) >> 0;
  21968. var currentFrame = returnValue ? from + ratio % range : to;
  21969. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21970. // Set value
  21971. this.setValue(currentValue);
  21972. if (!returnValue) {
  21973. this._stopped = true;
  21974. }
  21975. return returnValue;
  21976. };
  21977. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21978. get: function () {
  21979. return Animation._ANIMATIONTYPE_FLOAT;
  21980. },
  21981. enumerable: true,
  21982. configurable: true
  21983. });
  21984. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21985. get: function () {
  21986. return Animation._ANIMATIONTYPE_VECTOR3;
  21987. },
  21988. enumerable: true,
  21989. configurable: true
  21990. });
  21991. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21992. get: function () {
  21993. return Animation._ANIMATIONTYPE_VECTOR2;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21999. get: function () {
  22000. return Animation._ANIMATIONTYPE_QUATERNION;
  22001. },
  22002. enumerable: true,
  22003. configurable: true
  22004. });
  22005. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22006. get: function () {
  22007. return Animation._ANIMATIONTYPE_MATRIX;
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22013. get: function () {
  22014. return Animation._ANIMATIONTYPE_COLOR3;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22020. get: function () {
  22021. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22022. },
  22023. enumerable: true,
  22024. configurable: true
  22025. });
  22026. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22027. get: function () {
  22028. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22034. get: function () {
  22035. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22036. },
  22037. enumerable: true,
  22038. configurable: true
  22039. });
  22040. // Statics
  22041. Animation._ANIMATIONTYPE_FLOAT = 0;
  22042. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22043. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22044. Animation._ANIMATIONTYPE_MATRIX = 3;
  22045. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22046. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22047. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22048. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22049. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22050. return Animation;
  22051. })();
  22052. BABYLON.Animation = Animation;
  22053. })(BABYLON || (BABYLON = {}));
  22054. var BABYLON;
  22055. (function (BABYLON) {
  22056. var Animatable = (function () {
  22057. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22058. if (fromFrame === void 0) { fromFrame = 0; }
  22059. if (toFrame === void 0) { toFrame = 100; }
  22060. if (loopAnimation === void 0) { loopAnimation = false; }
  22061. if (speedRatio === void 0) { speedRatio = 1.0; }
  22062. this.target = target;
  22063. this.fromFrame = fromFrame;
  22064. this.toFrame = toFrame;
  22065. this.loopAnimation = loopAnimation;
  22066. this.speedRatio = speedRatio;
  22067. this.onAnimationEnd = onAnimationEnd;
  22068. this._animations = new Array();
  22069. this._paused = false;
  22070. this.animationStarted = false;
  22071. if (animations) {
  22072. this.appendAnimations(target, animations);
  22073. }
  22074. this._scene = scene;
  22075. scene._activeAnimatables.push(this);
  22076. }
  22077. // Methods
  22078. Animatable.prototype.getAnimations = function () {
  22079. return this._animations;
  22080. };
  22081. Animatable.prototype.appendAnimations = function (target, animations) {
  22082. for (var index = 0; index < animations.length; index++) {
  22083. var animation = animations[index];
  22084. animation._target = target;
  22085. this._animations.push(animation);
  22086. }
  22087. };
  22088. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22089. var animations = this._animations;
  22090. for (var index = 0; index < animations.length; index++) {
  22091. if (animations[index].targetProperty === property) {
  22092. return animations[index];
  22093. }
  22094. }
  22095. return null;
  22096. };
  22097. Animatable.prototype.reset = function () {
  22098. var animations = this._animations;
  22099. for (var index = 0; index < animations.length; index++) {
  22100. animations[index].reset();
  22101. }
  22102. this._localDelayOffset = null;
  22103. this._pausedDelay = null;
  22104. };
  22105. Animatable.prototype.goToFrame = function (frame) {
  22106. var animations = this._animations;
  22107. for (var index = 0; index < animations.length; index++) {
  22108. animations[index].goToFrame(frame);
  22109. }
  22110. };
  22111. Animatable.prototype.pause = function () {
  22112. if (this._paused) {
  22113. return;
  22114. }
  22115. this._paused = true;
  22116. };
  22117. Animatable.prototype.restart = function () {
  22118. this._paused = false;
  22119. };
  22120. Animatable.prototype.stop = function () {
  22121. var index = this._scene._activeAnimatables.indexOf(this);
  22122. if (index > -1) {
  22123. this._scene._activeAnimatables.splice(index, 1);
  22124. }
  22125. if (this.onAnimationEnd) {
  22126. this.onAnimationEnd();
  22127. }
  22128. };
  22129. Animatable.prototype._animate = function (delay) {
  22130. if (this._paused) {
  22131. this.animationStarted = false;
  22132. if (!this._pausedDelay) {
  22133. this._pausedDelay = delay;
  22134. }
  22135. return true;
  22136. }
  22137. if (!this._localDelayOffset) {
  22138. this._localDelayOffset = delay;
  22139. }
  22140. else if (this._pausedDelay) {
  22141. this._localDelayOffset += delay - this._pausedDelay;
  22142. this._pausedDelay = null;
  22143. }
  22144. // Animating
  22145. var running = false;
  22146. var animations = this._animations;
  22147. var index;
  22148. for (index = 0; index < animations.length; index++) {
  22149. var animation = animations[index];
  22150. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22151. running = running || isRunning;
  22152. }
  22153. this.animationStarted = running;
  22154. if (!running) {
  22155. // Remove from active animatables
  22156. index = this._scene._activeAnimatables.indexOf(this);
  22157. this._scene._activeAnimatables.splice(index, 1);
  22158. }
  22159. if (!running && this.onAnimationEnd) {
  22160. this.onAnimationEnd();
  22161. }
  22162. return running;
  22163. };
  22164. return Animatable;
  22165. })();
  22166. BABYLON.Animatable = Animatable;
  22167. })(BABYLON || (BABYLON = {}));
  22168. var BABYLON;
  22169. (function (BABYLON) {
  22170. var EasingFunction = (function () {
  22171. function EasingFunction() {
  22172. // Properties
  22173. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22174. }
  22175. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22176. get: function () {
  22177. return EasingFunction._EASINGMODE_EASEIN;
  22178. },
  22179. enumerable: true,
  22180. configurable: true
  22181. });
  22182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22183. get: function () {
  22184. return EasingFunction._EASINGMODE_EASEOUT;
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22190. get: function () {
  22191. return EasingFunction._EASINGMODE_EASEINOUT;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22197. var n = Math.min(Math.max(easingMode, 0), 2);
  22198. this._easingMode = n;
  22199. };
  22200. EasingFunction.prototype.getEasingMode = function () {
  22201. return this._easingMode;
  22202. };
  22203. EasingFunction.prototype.easeInCore = function (gradient) {
  22204. throw new Error('You must implement this method');
  22205. };
  22206. EasingFunction.prototype.ease = function (gradient) {
  22207. switch (this._easingMode) {
  22208. case EasingFunction.EASINGMODE_EASEIN:
  22209. return this.easeInCore(gradient);
  22210. case EasingFunction.EASINGMODE_EASEOUT:
  22211. return (1 - this.easeInCore(1 - gradient));
  22212. }
  22213. if (gradient >= 0.5) {
  22214. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22215. }
  22216. return (this.easeInCore(gradient * 2) * 0.5);
  22217. };
  22218. //Statics
  22219. EasingFunction._EASINGMODE_EASEIN = 0;
  22220. EasingFunction._EASINGMODE_EASEOUT = 1;
  22221. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22222. return EasingFunction;
  22223. })();
  22224. BABYLON.EasingFunction = EasingFunction;
  22225. var CircleEase = (function (_super) {
  22226. __extends(CircleEase, _super);
  22227. function CircleEase() {
  22228. _super.apply(this, arguments);
  22229. }
  22230. CircleEase.prototype.easeInCore = function (gradient) {
  22231. gradient = Math.max(0, Math.min(1, gradient));
  22232. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22233. };
  22234. return CircleEase;
  22235. })(EasingFunction);
  22236. BABYLON.CircleEase = CircleEase;
  22237. var BackEase = (function (_super) {
  22238. __extends(BackEase, _super);
  22239. function BackEase(amplitude) {
  22240. if (amplitude === void 0) { amplitude = 1; }
  22241. _super.call(this);
  22242. this.amplitude = amplitude;
  22243. }
  22244. BackEase.prototype.easeInCore = function (gradient) {
  22245. var num = Math.max(0, this.amplitude);
  22246. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22247. };
  22248. return BackEase;
  22249. })(EasingFunction);
  22250. BABYLON.BackEase = BackEase;
  22251. var BounceEase = (function (_super) {
  22252. __extends(BounceEase, _super);
  22253. function BounceEase(bounces, bounciness) {
  22254. if (bounces === void 0) { bounces = 3; }
  22255. if (bounciness === void 0) { bounciness = 2; }
  22256. _super.call(this);
  22257. this.bounces = bounces;
  22258. this.bounciness = bounciness;
  22259. }
  22260. BounceEase.prototype.easeInCore = function (gradient) {
  22261. var y = Math.max(0.0, this.bounces);
  22262. var bounciness = this.bounciness;
  22263. if (bounciness <= 1.0) {
  22264. bounciness = 1.001;
  22265. }
  22266. var num9 = Math.pow(bounciness, y);
  22267. var num5 = 1.0 - bounciness;
  22268. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22269. var num15 = gradient * num4;
  22270. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22271. var num3 = Math.floor(num65);
  22272. var num13 = num3 + 1.0;
  22273. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22274. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22275. var num7 = (num8 + num12) * 0.5;
  22276. var num6 = gradient - num7;
  22277. var num2 = num7 - num8;
  22278. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22279. };
  22280. return BounceEase;
  22281. })(EasingFunction);
  22282. BABYLON.BounceEase = BounceEase;
  22283. var CubicEase = (function (_super) {
  22284. __extends(CubicEase, _super);
  22285. function CubicEase() {
  22286. _super.apply(this, arguments);
  22287. }
  22288. CubicEase.prototype.easeInCore = function (gradient) {
  22289. return (gradient * gradient * gradient);
  22290. };
  22291. return CubicEase;
  22292. })(EasingFunction);
  22293. BABYLON.CubicEase = CubicEase;
  22294. var ElasticEase = (function (_super) {
  22295. __extends(ElasticEase, _super);
  22296. function ElasticEase(oscillations, springiness) {
  22297. if (oscillations === void 0) { oscillations = 3; }
  22298. if (springiness === void 0) { springiness = 3; }
  22299. _super.call(this);
  22300. this.oscillations = oscillations;
  22301. this.springiness = springiness;
  22302. }
  22303. ElasticEase.prototype.easeInCore = function (gradient) {
  22304. var num2;
  22305. var num3 = Math.max(0.0, this.oscillations);
  22306. var num = Math.max(0.0, this.springiness);
  22307. if (num == 0) {
  22308. num2 = gradient;
  22309. }
  22310. else {
  22311. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22312. }
  22313. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22314. };
  22315. return ElasticEase;
  22316. })(EasingFunction);
  22317. BABYLON.ElasticEase = ElasticEase;
  22318. var ExponentialEase = (function (_super) {
  22319. __extends(ExponentialEase, _super);
  22320. function ExponentialEase(exponent) {
  22321. if (exponent === void 0) { exponent = 2; }
  22322. _super.call(this);
  22323. this.exponent = exponent;
  22324. }
  22325. ExponentialEase.prototype.easeInCore = function (gradient) {
  22326. if (this.exponent <= 0) {
  22327. return gradient;
  22328. }
  22329. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22330. };
  22331. return ExponentialEase;
  22332. })(EasingFunction);
  22333. BABYLON.ExponentialEase = ExponentialEase;
  22334. var PowerEase = (function (_super) {
  22335. __extends(PowerEase, _super);
  22336. function PowerEase(power) {
  22337. if (power === void 0) { power = 2; }
  22338. _super.call(this);
  22339. this.power = power;
  22340. }
  22341. PowerEase.prototype.easeInCore = function (gradient) {
  22342. var y = Math.max(0.0, this.power);
  22343. return Math.pow(gradient, y);
  22344. };
  22345. return PowerEase;
  22346. })(EasingFunction);
  22347. BABYLON.PowerEase = PowerEase;
  22348. var QuadraticEase = (function (_super) {
  22349. __extends(QuadraticEase, _super);
  22350. function QuadraticEase() {
  22351. _super.apply(this, arguments);
  22352. }
  22353. QuadraticEase.prototype.easeInCore = function (gradient) {
  22354. return (gradient * gradient);
  22355. };
  22356. return QuadraticEase;
  22357. })(EasingFunction);
  22358. BABYLON.QuadraticEase = QuadraticEase;
  22359. var QuarticEase = (function (_super) {
  22360. __extends(QuarticEase, _super);
  22361. function QuarticEase() {
  22362. _super.apply(this, arguments);
  22363. }
  22364. QuarticEase.prototype.easeInCore = function (gradient) {
  22365. return (gradient * gradient * gradient * gradient);
  22366. };
  22367. return QuarticEase;
  22368. })(EasingFunction);
  22369. BABYLON.QuarticEase = QuarticEase;
  22370. var QuinticEase = (function (_super) {
  22371. __extends(QuinticEase, _super);
  22372. function QuinticEase() {
  22373. _super.apply(this, arguments);
  22374. }
  22375. QuinticEase.prototype.easeInCore = function (gradient) {
  22376. return (gradient * gradient * gradient * gradient * gradient);
  22377. };
  22378. return QuinticEase;
  22379. })(EasingFunction);
  22380. BABYLON.QuinticEase = QuinticEase;
  22381. var SineEase = (function (_super) {
  22382. __extends(SineEase, _super);
  22383. function SineEase() {
  22384. _super.apply(this, arguments);
  22385. }
  22386. SineEase.prototype.easeInCore = function (gradient) {
  22387. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22388. };
  22389. return SineEase;
  22390. })(EasingFunction);
  22391. BABYLON.SineEase = SineEase;
  22392. var BezierCurveEase = (function (_super) {
  22393. __extends(BezierCurveEase, _super);
  22394. function BezierCurveEase(x1, y1, x2, y2) {
  22395. if (x1 === void 0) { x1 = 0; }
  22396. if (y1 === void 0) { y1 = 0; }
  22397. if (x2 === void 0) { x2 = 1; }
  22398. if (y2 === void 0) { y2 = 1; }
  22399. _super.call(this);
  22400. this.x1 = x1;
  22401. this.y1 = y1;
  22402. this.x2 = x2;
  22403. this.y2 = y2;
  22404. }
  22405. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22406. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22407. };
  22408. return BezierCurveEase;
  22409. })(EasingFunction);
  22410. BABYLON.BezierCurveEase = BezierCurveEase;
  22411. })(BABYLON || (BABYLON = {}));
  22412. var BABYLON;
  22413. (function (BABYLON) {
  22414. var Bone = (function (_super) {
  22415. __extends(Bone, _super);
  22416. function Bone(name, skeleton, parentBone, matrix) {
  22417. _super.call(this, name, skeleton.getScene());
  22418. this.name = name;
  22419. this.children = new Array();
  22420. this.animations = new Array();
  22421. this._worldTransform = new BABYLON.Matrix();
  22422. this._absoluteTransform = new BABYLON.Matrix();
  22423. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22424. this._skeleton = skeleton;
  22425. this._matrix = matrix;
  22426. this._baseMatrix = matrix;
  22427. skeleton.bones.push(this);
  22428. if (parentBone) {
  22429. this._parent = parentBone;
  22430. parentBone.children.push(this);
  22431. }
  22432. else {
  22433. this._parent = null;
  22434. }
  22435. this._updateDifferenceMatrix();
  22436. }
  22437. // Members
  22438. Bone.prototype.getParent = function () {
  22439. return this._parent;
  22440. };
  22441. Bone.prototype.getLocalMatrix = function () {
  22442. return this._matrix;
  22443. };
  22444. Bone.prototype.getBaseMatrix = function () {
  22445. return this._baseMatrix;
  22446. };
  22447. Bone.prototype.getWorldMatrix = function () {
  22448. return this._worldTransform;
  22449. };
  22450. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22451. return this._invertedAbsoluteTransform;
  22452. };
  22453. Bone.prototype.getAbsoluteMatrix = function () {
  22454. var matrix = this._matrix.clone();
  22455. var parent = this._parent;
  22456. while (parent) {
  22457. matrix = matrix.multiply(parent.getLocalMatrix());
  22458. parent = parent.getParent();
  22459. }
  22460. return matrix;
  22461. };
  22462. // Methods
  22463. Bone.prototype.updateMatrix = function (matrix) {
  22464. this._matrix = matrix;
  22465. this._skeleton._markAsDirty();
  22466. this._updateDifferenceMatrix();
  22467. };
  22468. Bone.prototype._updateDifferenceMatrix = function () {
  22469. if (this._parent) {
  22470. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22471. }
  22472. else {
  22473. this._absoluteTransform.copyFrom(this._matrix);
  22474. }
  22475. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22476. for (var index = 0; index < this.children.length; index++) {
  22477. this.children[index]._updateDifferenceMatrix();
  22478. }
  22479. };
  22480. Bone.prototype.markAsDirty = function () {
  22481. this._currentRenderId++;
  22482. this._skeleton._markAsDirty();
  22483. };
  22484. return Bone;
  22485. })(BABYLON.Node);
  22486. BABYLON.Bone = Bone;
  22487. })(BABYLON || (BABYLON = {}));
  22488. var BABYLON;
  22489. (function (BABYLON) {
  22490. var Skeleton = (function () {
  22491. function Skeleton(name, id, scene) {
  22492. this.name = name;
  22493. this.id = id;
  22494. this.bones = new Array();
  22495. this._isDirty = true;
  22496. this._identity = BABYLON.Matrix.Identity();
  22497. this._ranges = new Array();
  22498. this.bones = [];
  22499. this._scene = scene;
  22500. scene.skeletons.push(this);
  22501. this.prepare();
  22502. //make sure it will recalculate the matrix next time prepare is called.
  22503. this._isDirty = true;
  22504. }
  22505. // Members
  22506. Skeleton.prototype.getTransformMatrices = function () {
  22507. return this._transformMatrices;
  22508. };
  22509. Skeleton.prototype.getScene = function () {
  22510. return this._scene;
  22511. };
  22512. // Methods
  22513. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22514. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22515. };
  22516. Skeleton.prototype.deleteAnimationRange = function (name) {
  22517. for (var index = 0; index < this._ranges.length; index++) {
  22518. if (this._ranges[index].name === name) {
  22519. this._ranges.splice(index, 1);
  22520. return;
  22521. }
  22522. }
  22523. };
  22524. Skeleton.prototype.getAnimationRange = function (name) {
  22525. for (var index = 0; index < this._ranges.length; index++) {
  22526. if (this._ranges[index].name === name) {
  22527. return this._ranges[index];
  22528. }
  22529. }
  22530. return null;
  22531. };
  22532. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22533. var range = this.getAnimationRange(name);
  22534. if (!range) {
  22535. return null;
  22536. }
  22537. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22538. };
  22539. Skeleton.prototype._markAsDirty = function () {
  22540. this._isDirty = true;
  22541. };
  22542. Skeleton.prototype.prepare = function () {
  22543. if (!this._isDirty) {
  22544. return;
  22545. }
  22546. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22547. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22548. }
  22549. for (var index = 0; index < this.bones.length; index++) {
  22550. var bone = this.bones[index];
  22551. var parentBone = bone.getParent();
  22552. if (parentBone) {
  22553. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22554. }
  22555. else {
  22556. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22557. }
  22558. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22559. }
  22560. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22561. this._isDirty = false;
  22562. this._scene._activeBones += this.bones.length;
  22563. };
  22564. Skeleton.prototype.getAnimatables = function () {
  22565. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22566. this._animatables = [];
  22567. for (var index = 0; index < this.bones.length; index++) {
  22568. this._animatables.push(this.bones[index]);
  22569. }
  22570. }
  22571. return this._animatables;
  22572. };
  22573. Skeleton.prototype.clone = function (name, id) {
  22574. var result = new Skeleton(name, id || name, this._scene);
  22575. for (var index = 0; index < this.bones.length; index++) {
  22576. var source = this.bones[index];
  22577. var parentBone = null;
  22578. if (source.getParent()) {
  22579. var parentIndex = this.bones.indexOf(source.getParent());
  22580. parentBone = result.bones[parentIndex];
  22581. }
  22582. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22583. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22584. }
  22585. return result;
  22586. };
  22587. Skeleton.prototype.dispose = function () {
  22588. // Animations
  22589. this.getScene().stopAnimation(this);
  22590. // Remove from scene
  22591. this.getScene().removeSkeleton(this);
  22592. };
  22593. return Skeleton;
  22594. })();
  22595. BABYLON.Skeleton = Skeleton;
  22596. })(BABYLON || (BABYLON = {}));
  22597. var BABYLON;
  22598. (function (BABYLON) {
  22599. var PostProcess = (function () {
  22600. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22603. this.name = name;
  22604. this.width = -1;
  22605. this.height = -1;
  22606. this._reusable = false;
  22607. this._textures = new BABYLON.SmartArray(2);
  22608. this._currentRenderTextureInd = 0;
  22609. if (camera != null) {
  22610. this._camera = camera;
  22611. this._scene = camera.getScene();
  22612. camera.attachPostProcess(this);
  22613. this._engine = this._scene.getEngine();
  22614. }
  22615. else {
  22616. this._engine = engine;
  22617. }
  22618. this._renderRatio = ratio;
  22619. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22620. this._reusable = reusable || false;
  22621. this._textureType = textureType;
  22622. this._samplers = samplers || [];
  22623. this._samplers.push("textureSampler");
  22624. this._fragmentUrl = fragmentUrl;
  22625. this._parameters = parameters || [];
  22626. this.updateEffect(defines);
  22627. }
  22628. PostProcess.prototype.updateEffect = function (defines) {
  22629. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  22630. };
  22631. PostProcess.prototype.isReusable = function () {
  22632. return this._reusable;
  22633. };
  22634. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22635. camera = camera || this._camera;
  22636. var scene = camera.getScene();
  22637. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22638. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22639. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22640. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22641. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22642. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22643. if (this._textures.length > 0) {
  22644. for (var i = 0; i < this._textures.length; i++) {
  22645. this._engine._releaseTexture(this._textures.data[i]);
  22646. }
  22647. this._textures.reset();
  22648. }
  22649. this.width = desiredWidth;
  22650. this.height = desiredHeight;
  22651. 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 }));
  22652. if (this._reusable) {
  22653. 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 }));
  22654. }
  22655. if (this.onSizeChanged) {
  22656. this.onSizeChanged();
  22657. }
  22658. }
  22659. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22660. if (this.onActivate) {
  22661. this.onActivate(camera);
  22662. }
  22663. // Clear
  22664. if (this.clearColor) {
  22665. this._engine.clear(this.clearColor, true, true);
  22666. }
  22667. else {
  22668. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22669. }
  22670. if (this._reusable) {
  22671. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22672. }
  22673. };
  22674. Object.defineProperty(PostProcess.prototype, "isSupported", {
  22675. get: function () {
  22676. return this._effect.isSupported;
  22677. },
  22678. enumerable: true,
  22679. configurable: true
  22680. });
  22681. PostProcess.prototype.apply = function () {
  22682. // Check
  22683. if (!this._effect.isReady())
  22684. return null;
  22685. // States
  22686. this._engine.enableEffect(this._effect);
  22687. this._engine.setState(false);
  22688. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22689. this._engine.setDepthBuffer(false);
  22690. this._engine.setDepthWrite(false);
  22691. // Texture
  22692. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22693. // Parameters
  22694. if (this.onApply) {
  22695. this.onApply(this._effect);
  22696. }
  22697. return this._effect;
  22698. };
  22699. PostProcess.prototype.dispose = function (camera) {
  22700. camera = camera || this._camera;
  22701. if (this._textures.length > 0) {
  22702. for (var i = 0; i < this._textures.length; i++) {
  22703. this._engine._releaseTexture(this._textures.data[i]);
  22704. }
  22705. this._textures.reset();
  22706. }
  22707. if (!camera) {
  22708. return;
  22709. }
  22710. camera.detachPostProcess(this);
  22711. var index = camera._postProcesses.indexOf(this);
  22712. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22713. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22714. }
  22715. };
  22716. return PostProcess;
  22717. })();
  22718. BABYLON.PostProcess = PostProcess;
  22719. })(BABYLON || (BABYLON = {}));
  22720. var BABYLON;
  22721. (function (BABYLON) {
  22722. var PostProcessManager = (function () {
  22723. function PostProcessManager(scene) {
  22724. this._vertexDeclaration = [2];
  22725. this._vertexStrideSize = 2 * 4;
  22726. this._scene = scene;
  22727. }
  22728. PostProcessManager.prototype._prepareBuffers = function () {
  22729. if (this._vertexBuffer) {
  22730. return;
  22731. }
  22732. // VBO
  22733. var vertices = [];
  22734. vertices.push(1, 1);
  22735. vertices.push(-1, 1);
  22736. vertices.push(-1, -1);
  22737. vertices.push(1, -1);
  22738. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22739. // Indices
  22740. var indices = [];
  22741. indices.push(0);
  22742. indices.push(1);
  22743. indices.push(2);
  22744. indices.push(0);
  22745. indices.push(2);
  22746. indices.push(3);
  22747. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22748. };
  22749. // Methods
  22750. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22751. var postProcesses = this._scene.activeCamera._postProcesses;
  22752. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22753. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22754. return false;
  22755. }
  22756. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22757. return true;
  22758. };
  22759. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22760. var engine = this._scene.getEngine();
  22761. for (var index = 0; index < postProcesses.length; index++) {
  22762. if (index < postProcesses.length - 1) {
  22763. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22764. }
  22765. else {
  22766. if (targetTexture) {
  22767. engine.bindFramebuffer(targetTexture);
  22768. }
  22769. else {
  22770. engine.restoreDefaultFramebuffer();
  22771. }
  22772. }
  22773. var pp = postProcesses[index];
  22774. var effect = pp.apply();
  22775. if (effect) {
  22776. if (pp.onBeforeRender) {
  22777. pp.onBeforeRender(effect);
  22778. }
  22779. // VBOs
  22780. this._prepareBuffers();
  22781. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22782. // Draw order
  22783. engine.draw(true, 0, 6);
  22784. if (pp.onAfterRender) {
  22785. pp.onAfterRender(effect);
  22786. }
  22787. }
  22788. }
  22789. // Restore depth buffer
  22790. engine.setDepthBuffer(true);
  22791. engine.setDepthWrite(true);
  22792. };
  22793. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22794. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22795. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22796. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22797. return;
  22798. }
  22799. var engine = this._scene.getEngine();
  22800. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22801. if (index < postProcessesTakenIndices.length - 1) {
  22802. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22803. }
  22804. else {
  22805. if (targetTexture) {
  22806. engine.bindFramebuffer(targetTexture, faceIndex);
  22807. }
  22808. else {
  22809. engine.restoreDefaultFramebuffer();
  22810. }
  22811. }
  22812. if (doNotPresent) {
  22813. break;
  22814. }
  22815. var pp = postProcesses[postProcessesTakenIndices[index]];
  22816. var effect = pp.apply();
  22817. if (effect) {
  22818. if (pp.onBeforeRender) {
  22819. pp.onBeforeRender(effect);
  22820. }
  22821. // VBOs
  22822. this._prepareBuffers();
  22823. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22824. // Draw order
  22825. engine.draw(true, 0, 6);
  22826. if (pp.onAfterRender) {
  22827. pp.onAfterRender(effect);
  22828. }
  22829. }
  22830. }
  22831. // Restore depth buffer
  22832. engine.setDepthBuffer(true);
  22833. engine.setDepthWrite(true);
  22834. };
  22835. PostProcessManager.prototype.dispose = function () {
  22836. if (this._vertexBuffer) {
  22837. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22838. this._vertexBuffer = null;
  22839. }
  22840. if (this._indexBuffer) {
  22841. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22842. this._indexBuffer = null;
  22843. }
  22844. };
  22845. return PostProcessManager;
  22846. })();
  22847. BABYLON.PostProcessManager = PostProcessManager;
  22848. })(BABYLON || (BABYLON = {}));
  22849. var BABYLON;
  22850. (function (BABYLON) {
  22851. var PassPostProcess = (function (_super) {
  22852. __extends(PassPostProcess, _super);
  22853. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22854. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22855. }
  22856. return PassPostProcess;
  22857. })(BABYLON.PostProcess);
  22858. BABYLON.PassPostProcess = PassPostProcess;
  22859. })(BABYLON || (BABYLON = {}));
  22860. var BABYLON;
  22861. (function (BABYLON) {
  22862. var PhysicsEngine = (function () {
  22863. function PhysicsEngine(plugin) {
  22864. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22865. }
  22866. PhysicsEngine.prototype._initialize = function (gravity) {
  22867. this._currentPlugin.initialize();
  22868. this._setGravity(gravity);
  22869. };
  22870. PhysicsEngine.prototype._runOneStep = function (delta) {
  22871. if (delta > 0.1) {
  22872. delta = 0.1;
  22873. }
  22874. else if (delta <= 0) {
  22875. delta = 1.0 / 60.0;
  22876. }
  22877. this._currentPlugin.runOneStep(delta);
  22878. };
  22879. PhysicsEngine.prototype._setGravity = function (gravity) {
  22880. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22881. this._currentPlugin.setGravity(this.gravity);
  22882. };
  22883. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22884. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22885. };
  22886. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22887. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22888. };
  22889. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22890. this._currentPlugin.unregisterMesh(mesh);
  22891. };
  22892. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22893. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22894. };
  22895. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22896. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22897. };
  22898. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22899. this._currentPlugin.updateBodyPosition(mesh);
  22900. };
  22901. PhysicsEngine.prototype.dispose = function () {
  22902. this._currentPlugin.dispose();
  22903. };
  22904. PhysicsEngine.prototype.isSupported = function () {
  22905. return this._currentPlugin.isSupported();
  22906. };
  22907. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22908. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22909. };
  22910. // Statics
  22911. PhysicsEngine.NoImpostor = 0;
  22912. PhysicsEngine.SphereImpostor = 1;
  22913. PhysicsEngine.BoxImpostor = 2;
  22914. PhysicsEngine.PlaneImpostor = 3;
  22915. PhysicsEngine.MeshImpostor = 4;
  22916. PhysicsEngine.CapsuleImpostor = 5;
  22917. PhysicsEngine.ConeImpostor = 6;
  22918. PhysicsEngine.CylinderImpostor = 7;
  22919. PhysicsEngine.ConvexHullImpostor = 8;
  22920. PhysicsEngine.HeightmapImpostor = 9;
  22921. PhysicsEngine.Epsilon = 0.001;
  22922. return PhysicsEngine;
  22923. })();
  22924. BABYLON.PhysicsEngine = PhysicsEngine;
  22925. })(BABYLON || (BABYLON = {}));
  22926. var BABYLON;
  22927. (function (BABYLON) {
  22928. var VertexData = (function () {
  22929. function VertexData() {
  22930. }
  22931. VertexData.prototype.set = function (data, kind) {
  22932. switch (kind) {
  22933. case BABYLON.VertexBuffer.PositionKind:
  22934. this.positions = data;
  22935. break;
  22936. case BABYLON.VertexBuffer.NormalKind:
  22937. this.normals = data;
  22938. break;
  22939. case BABYLON.VertexBuffer.UVKind:
  22940. this.uvs = data;
  22941. break;
  22942. case BABYLON.VertexBuffer.UV2Kind:
  22943. this.uvs2 = data;
  22944. break;
  22945. case BABYLON.VertexBuffer.UV3Kind:
  22946. this.uvs3 = data;
  22947. break;
  22948. case BABYLON.VertexBuffer.UV4Kind:
  22949. this.uvs4 = data;
  22950. break;
  22951. case BABYLON.VertexBuffer.UV5Kind:
  22952. this.uvs5 = data;
  22953. break;
  22954. case BABYLON.VertexBuffer.UV6Kind:
  22955. this.uvs6 = data;
  22956. break;
  22957. case BABYLON.VertexBuffer.ColorKind:
  22958. this.colors = data;
  22959. break;
  22960. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22961. this.matricesIndices = data;
  22962. break;
  22963. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22964. this.matricesWeights = data;
  22965. break;
  22966. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  22967. this.matricesIndicesExtra = data;
  22968. break;
  22969. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  22970. this.matricesWeightsExtra = data;
  22971. break;
  22972. }
  22973. };
  22974. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22975. this._applyTo(mesh, updatable);
  22976. };
  22977. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22978. this._applyTo(geometry, updatable);
  22979. };
  22980. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22981. this._update(mesh);
  22982. };
  22983. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22984. this._update(geometry);
  22985. };
  22986. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22987. if (this.positions) {
  22988. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22989. }
  22990. if (this.normals) {
  22991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22992. }
  22993. if (this.uvs) {
  22994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22995. }
  22996. if (this.uvs2) {
  22997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22998. }
  22999. if (this.uvs3) {
  23000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23001. }
  23002. if (this.uvs4) {
  23003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23004. }
  23005. if (this.uvs5) {
  23006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23007. }
  23008. if (this.uvs6) {
  23009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23010. }
  23011. if (this.colors) {
  23012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23013. }
  23014. if (this.matricesIndices) {
  23015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23016. }
  23017. if (this.matricesWeights) {
  23018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23019. }
  23020. if (this.matricesIndicesExtra) {
  23021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23022. }
  23023. if (this.matricesWeightsExtra) {
  23024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23025. }
  23026. if (this.indices) {
  23027. meshOrGeometry.setIndices(this.indices);
  23028. }
  23029. };
  23030. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23031. if (this.positions) {
  23032. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23033. }
  23034. if (this.normals) {
  23035. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23036. }
  23037. if (this.uvs) {
  23038. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23039. }
  23040. if (this.uvs2) {
  23041. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23042. }
  23043. if (this.uvs3) {
  23044. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23045. }
  23046. if (this.uvs4) {
  23047. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23048. }
  23049. if (this.uvs5) {
  23050. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23051. }
  23052. if (this.uvs6) {
  23053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23054. }
  23055. if (this.colors) {
  23056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23057. }
  23058. if (this.matricesIndices) {
  23059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23060. }
  23061. if (this.matricesWeights) {
  23062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23063. }
  23064. if (this.matricesIndicesExtra) {
  23065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23066. }
  23067. if (this.matricesWeightsExtra) {
  23068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23069. }
  23070. if (this.indices) {
  23071. meshOrGeometry.setIndices(this.indices);
  23072. }
  23073. };
  23074. VertexData.prototype.transform = function (matrix) {
  23075. var transformed = BABYLON.Vector3.Zero();
  23076. var index;
  23077. if (this.positions) {
  23078. var position = BABYLON.Vector3.Zero();
  23079. for (index = 0; index < this.positions.length; index += 3) {
  23080. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23081. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23082. this.positions[index] = transformed.x;
  23083. this.positions[index + 1] = transformed.y;
  23084. this.positions[index + 2] = transformed.z;
  23085. }
  23086. }
  23087. if (this.normals) {
  23088. var normal = BABYLON.Vector3.Zero();
  23089. for (index = 0; index < this.normals.length; index += 3) {
  23090. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23091. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23092. this.normals[index] = transformed.x;
  23093. this.normals[index + 1] = transformed.y;
  23094. this.normals[index + 2] = transformed.z;
  23095. }
  23096. }
  23097. };
  23098. VertexData.prototype.merge = function (other) {
  23099. var index;
  23100. if (other.indices) {
  23101. if (!this.indices) {
  23102. this.indices = [];
  23103. }
  23104. var offset = this.positions ? this.positions.length / 3 : 0;
  23105. for (index = 0; index < other.indices.length; index++) {
  23106. this.indices.push(other.indices[index] + offset);
  23107. }
  23108. }
  23109. if (other.positions) {
  23110. if (!this.positions) {
  23111. this.positions = [];
  23112. }
  23113. for (index = 0; index < other.positions.length; index++) {
  23114. this.positions.push(other.positions[index]);
  23115. }
  23116. }
  23117. if (other.normals) {
  23118. if (!this.normals) {
  23119. this.normals = [];
  23120. }
  23121. for (index = 0; index < other.normals.length; index++) {
  23122. this.normals.push(other.normals[index]);
  23123. }
  23124. }
  23125. if (other.uvs) {
  23126. if (!this.uvs) {
  23127. this.uvs = [];
  23128. }
  23129. for (index = 0; index < other.uvs.length; index++) {
  23130. this.uvs.push(other.uvs[index]);
  23131. }
  23132. }
  23133. if (other.uvs2) {
  23134. if (!this.uvs2) {
  23135. this.uvs2 = [];
  23136. }
  23137. for (index = 0; index < other.uvs2.length; index++) {
  23138. this.uvs2.push(other.uvs2[index]);
  23139. }
  23140. }
  23141. if (other.uvs3) {
  23142. if (!this.uvs3) {
  23143. this.uvs3 = [];
  23144. }
  23145. for (index = 0; index < other.uvs3.length; index++) {
  23146. this.uvs3.push(other.uvs3[index]);
  23147. }
  23148. }
  23149. if (other.uvs4) {
  23150. if (!this.uvs4) {
  23151. this.uvs4 = [];
  23152. }
  23153. for (index = 0; index < other.uvs4.length; index++) {
  23154. this.uvs4.push(other.uvs4[index]);
  23155. }
  23156. }
  23157. if (other.uvs5) {
  23158. if (!this.uvs5) {
  23159. this.uvs5 = [];
  23160. }
  23161. for (index = 0; index < other.uvs5.length; index++) {
  23162. this.uvs5.push(other.uvs5[index]);
  23163. }
  23164. }
  23165. if (other.uvs6) {
  23166. if (!this.uvs6) {
  23167. this.uvs6 = [];
  23168. }
  23169. for (index = 0; index < other.uvs6.length; index++) {
  23170. this.uvs6.push(other.uvs6[index]);
  23171. }
  23172. }
  23173. if (other.matricesIndices) {
  23174. if (!this.matricesIndices) {
  23175. this.matricesIndices = [];
  23176. }
  23177. for (index = 0; index < other.matricesIndices.length; index++) {
  23178. this.matricesIndices.push(other.matricesIndices[index]);
  23179. }
  23180. }
  23181. if (other.matricesWeights) {
  23182. if (!this.matricesWeights) {
  23183. this.matricesWeights = [];
  23184. }
  23185. for (index = 0; index < other.matricesWeights.length; index++) {
  23186. this.matricesWeights.push(other.matricesWeights[index]);
  23187. }
  23188. }
  23189. if (other.matricesIndicesExtra) {
  23190. if (!this.matricesIndicesExtra) {
  23191. this.matricesIndicesExtra = [];
  23192. }
  23193. for (index = 0; index < other.matricesIndicesExtra.length; index++) {
  23194. this.matricesIndicesExtra.push(other.matricesIndicesExtra[index]);
  23195. }
  23196. }
  23197. if (other.matricesWeightsExtra) {
  23198. if (!this.matricesWeightsExtra) {
  23199. this.matricesWeightsExtra = [];
  23200. }
  23201. for (index = 0; index < other.matricesWeightsExtra.length; index++) {
  23202. this.matricesWeightsExtra.push(other.matricesWeightsExtra[index]);
  23203. }
  23204. }
  23205. if (other.colors) {
  23206. if (!this.colors) {
  23207. this.colors = [];
  23208. }
  23209. for (index = 0; index < other.colors.length; index++) {
  23210. this.colors.push(other.colors[index]);
  23211. }
  23212. }
  23213. };
  23214. // Statics
  23215. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23216. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23217. };
  23218. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23219. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23220. };
  23221. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23222. var result = new VertexData();
  23223. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23224. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23225. }
  23226. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23227. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23228. }
  23229. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23230. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23231. }
  23232. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23233. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23234. }
  23235. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23236. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23237. }
  23238. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23239. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23240. }
  23241. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23242. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23243. }
  23244. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23245. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23246. }
  23247. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23248. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23249. }
  23250. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23251. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23252. }
  23253. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23254. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23255. }
  23256. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23257. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23258. }
  23259. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23260. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23261. }
  23262. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23263. return result;
  23264. };
  23265. VertexData.CreateRibbon = function (options) {
  23266. var pathArray = options.pathArray;
  23267. var closeArray = options.closeArray || false;
  23268. var closePath = options.closePath || false;
  23269. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23270. var offset = options.offset || defaultOffset;
  23271. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23272. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23273. var positions = [];
  23274. var indices = [];
  23275. var normals = [];
  23276. var uvs = [];
  23277. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23278. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23279. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23280. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23281. var minlg; // minimal length among all paths from pathArray
  23282. var lg = []; // array of path lengths : nb of vertex per path
  23283. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23284. var p; // path iterator
  23285. var i; // point iterator
  23286. var j; // point iterator
  23287. // if single path in pathArray
  23288. if (pathArray.length < 2) {
  23289. var ar1 = [];
  23290. var ar2 = [];
  23291. for (i = 0; i < pathArray[0].length - offset; i++) {
  23292. ar1.push(pathArray[0][i]);
  23293. ar2.push(pathArray[0][i + offset]);
  23294. }
  23295. pathArray = [ar1, ar2];
  23296. }
  23297. // positions and horizontal distances (u)
  23298. var idc = 0;
  23299. var closePathCorr = (closePath) ? 1 : 0;
  23300. var path;
  23301. var l;
  23302. minlg = pathArray[0].length;
  23303. var vectlg;
  23304. var dist;
  23305. for (p = 0; p < pathArray.length; p++) {
  23306. uTotalDistance[p] = 0;
  23307. us[p] = [0];
  23308. path = pathArray[p];
  23309. l = path.length;
  23310. minlg = (minlg < l) ? minlg : l;
  23311. j = 0;
  23312. while (j < l) {
  23313. positions.push(path[j].x, path[j].y, path[j].z);
  23314. if (j > 0) {
  23315. vectlg = path[j].subtract(path[j - 1]).length();
  23316. dist = vectlg + uTotalDistance[p];
  23317. us[p].push(dist);
  23318. uTotalDistance[p] = dist;
  23319. }
  23320. j++;
  23321. }
  23322. if (closePath) {
  23323. j--;
  23324. positions.push(path[0].x, path[0].y, path[0].z);
  23325. vectlg = path[j].subtract(path[0]).length();
  23326. dist = vectlg + uTotalDistance[p];
  23327. us[p].push(dist);
  23328. uTotalDistance[p] = dist;
  23329. }
  23330. lg[p] = l + closePathCorr;
  23331. idx[p] = idc;
  23332. idc += (l + closePathCorr);
  23333. }
  23334. // vertical distances (v)
  23335. var path1;
  23336. var path2;
  23337. var vertex1;
  23338. var vertex2;
  23339. for (i = 0; i < minlg + closePathCorr; i++) {
  23340. vTotalDistance[i] = 0;
  23341. vs[i] = [0];
  23342. for (p = 0; p < pathArray.length - 1; p++) {
  23343. path1 = pathArray[p];
  23344. path2 = pathArray[p + 1];
  23345. if (i === minlg) {
  23346. vertex1 = path1[0];
  23347. vertex2 = path2[0];
  23348. }
  23349. else {
  23350. vertex1 = path1[i];
  23351. vertex2 = path2[i];
  23352. }
  23353. vectlg = vertex2.subtract(vertex1).length();
  23354. dist = vectlg + vTotalDistance[i];
  23355. vs[i].push(dist);
  23356. vTotalDistance[i] = dist;
  23357. }
  23358. if (closeArray) {
  23359. path1 = pathArray[p];
  23360. path2 = pathArray[0];
  23361. if (i === minlg) {
  23362. vertex2 = path2[0];
  23363. }
  23364. vectlg = vertex2.subtract(vertex1).length();
  23365. dist = vectlg + vTotalDistance[i];
  23366. vTotalDistance[i] = dist;
  23367. }
  23368. }
  23369. // uvs
  23370. var u;
  23371. var v;
  23372. for (p = 0; p < pathArray.length; p++) {
  23373. for (i = 0; i < minlg + closePathCorr; i++) {
  23374. u = us[p][i] / uTotalDistance[p];
  23375. v = vs[i][p] / vTotalDistance[i];
  23376. uvs.push(u, v);
  23377. }
  23378. }
  23379. // indices
  23380. p = 0; // path index
  23381. var pi = 0; // positions array index
  23382. var l1 = lg[p] - 1; // path1 length
  23383. var l2 = lg[p + 1] - 1; // path2 length
  23384. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23385. var shft = idx[1] - idx[0]; // shift
  23386. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23387. while (pi <= min && p < path1nb) {
  23388. // 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
  23389. indices.push(pi, pi + shft, pi + 1);
  23390. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23391. pi += 1;
  23392. if (pi === min) {
  23393. p++;
  23394. if (p === lg.length - 1) {
  23395. shft = idx[0] - idx[p];
  23396. l1 = lg[p] - 1;
  23397. l2 = lg[0] - 1;
  23398. }
  23399. else {
  23400. shft = idx[p + 1] - idx[p];
  23401. l1 = lg[p] - 1;
  23402. l2 = lg[p + 1] - 1;
  23403. }
  23404. pi = idx[p];
  23405. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23406. }
  23407. }
  23408. // normals
  23409. VertexData.ComputeNormals(positions, indices, normals);
  23410. if (closePath) {
  23411. var indexFirst = 0;
  23412. var indexLast = 0;
  23413. for (p = 0; p < pathArray.length; p++) {
  23414. indexFirst = idx[p] * 3;
  23415. if (p + 1 < pathArray.length) {
  23416. indexLast = (idx[p + 1] - 1) * 3;
  23417. }
  23418. else {
  23419. indexLast = normals.length - 3;
  23420. }
  23421. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23422. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23423. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23424. normals[indexLast] = normals[indexFirst];
  23425. normals[indexLast + 1] = normals[indexFirst + 1];
  23426. normals[indexLast + 2] = normals[indexFirst + 2];
  23427. }
  23428. }
  23429. // sides
  23430. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23431. // Result
  23432. var vertexData = new VertexData();
  23433. vertexData.indices = indices;
  23434. vertexData.positions = positions;
  23435. vertexData.normals = normals;
  23436. vertexData.uvs = uvs;
  23437. if (closePath) {
  23438. vertexData._idx = idx;
  23439. }
  23440. return vertexData;
  23441. };
  23442. VertexData.CreateBox = function (options) {
  23443. var normalsSource = [
  23444. new BABYLON.Vector3(0, 0, 1),
  23445. new BABYLON.Vector3(0, 0, -1),
  23446. new BABYLON.Vector3(1, 0, 0),
  23447. new BABYLON.Vector3(-1, 0, 0),
  23448. new BABYLON.Vector3(0, 1, 0),
  23449. new BABYLON.Vector3(0, -1, 0)
  23450. ];
  23451. var indices = [];
  23452. var positions = [];
  23453. var normals = [];
  23454. var uvs = [];
  23455. var width = options.width || options.size || 1;
  23456. var height = options.height || options.size || 1;
  23457. var depth = options.depth || options.size || 1;
  23458. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23459. var faceUV = options.faceUV || new Array(6);
  23460. var faceColors = options.faceColors;
  23461. var colors = [];
  23462. // default face colors and UV if undefined
  23463. for (var f = 0; f < 6; f++) {
  23464. if (faceUV[f] === undefined) {
  23465. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23466. }
  23467. if (faceColors && faceColors[f] === undefined) {
  23468. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23469. }
  23470. }
  23471. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23472. // Create each face in turn.
  23473. for (var index = 0; index < normalsSource.length; index++) {
  23474. var normal = normalsSource[index];
  23475. // Get two vectors perpendicular to the face normal and to each other.
  23476. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23477. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23478. // Six indices (two triangles) per face.
  23479. var verticesLength = positions.length / 3;
  23480. indices.push(verticesLength);
  23481. indices.push(verticesLength + 1);
  23482. indices.push(verticesLength + 2);
  23483. indices.push(verticesLength);
  23484. indices.push(verticesLength + 2);
  23485. indices.push(verticesLength + 3);
  23486. // Four vertices per face.
  23487. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23488. positions.push(vertex.x, vertex.y, vertex.z);
  23489. normals.push(normal.x, normal.y, normal.z);
  23490. uvs.push(faceUV[index].z, faceUV[index].w);
  23491. if (faceColors) {
  23492. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23493. }
  23494. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23495. positions.push(vertex.x, vertex.y, vertex.z);
  23496. normals.push(normal.x, normal.y, normal.z);
  23497. uvs.push(faceUV[index].x, faceUV[index].w);
  23498. if (faceColors) {
  23499. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23500. }
  23501. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23502. positions.push(vertex.x, vertex.y, vertex.z);
  23503. normals.push(normal.x, normal.y, normal.z);
  23504. uvs.push(faceUV[index].x, faceUV[index].y);
  23505. if (faceColors) {
  23506. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23507. }
  23508. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23509. positions.push(vertex.x, vertex.y, vertex.z);
  23510. normals.push(normal.x, normal.y, normal.z);
  23511. uvs.push(faceUV[index].z, faceUV[index].y);
  23512. if (faceColors) {
  23513. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23514. }
  23515. }
  23516. // sides
  23517. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23518. // Result
  23519. var vertexData = new VertexData();
  23520. vertexData.indices = indices;
  23521. vertexData.positions = positions;
  23522. vertexData.normals = normals;
  23523. vertexData.uvs = uvs;
  23524. if (faceColors) {
  23525. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23526. vertexData.colors = totalColors;
  23527. }
  23528. return vertexData;
  23529. };
  23530. VertexData.CreateSphere = function (options) {
  23531. var segments = options.segments || 32;
  23532. var diameterX = options.diameterX || options.diameter || 1;
  23533. var diameterY = options.diameterY || options.diameter || 1;
  23534. var diameterZ = options.diameterZ || options.diameter || 1;
  23535. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23536. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23537. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23538. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23539. var totalZRotationSteps = 2 + segments;
  23540. var totalYRotationSteps = 2 * totalZRotationSteps;
  23541. var indices = [];
  23542. var positions = [];
  23543. var normals = [];
  23544. var uvs = [];
  23545. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23546. var normalizedZ = zRotationStep / totalZRotationSteps;
  23547. var angleZ = normalizedZ * Math.PI * slice;
  23548. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23549. var normalizedY = yRotationStep / totalYRotationSteps;
  23550. var angleY = normalizedY * Math.PI * 2 * arc;
  23551. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23552. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23553. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23554. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23555. var vertex = complete.multiply(radius);
  23556. var normal = BABYLON.Vector3.Normalize(vertex);
  23557. positions.push(vertex.x, vertex.y, vertex.z);
  23558. normals.push(normal.x, normal.y, normal.z);
  23559. uvs.push(normalizedY, normalizedZ);
  23560. }
  23561. if (zRotationStep > 0) {
  23562. var verticesCount = positions.length / 3;
  23563. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23564. indices.push((firstIndex));
  23565. indices.push((firstIndex + 1));
  23566. indices.push(firstIndex + totalYRotationSteps + 1);
  23567. indices.push((firstIndex + totalYRotationSteps + 1));
  23568. indices.push((firstIndex + 1));
  23569. indices.push((firstIndex + totalYRotationSteps + 2));
  23570. }
  23571. }
  23572. }
  23573. // Sides
  23574. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23575. // Result
  23576. var vertexData = new VertexData();
  23577. vertexData.indices = indices;
  23578. vertexData.positions = positions;
  23579. vertexData.normals = normals;
  23580. vertexData.uvs = uvs;
  23581. return vertexData;
  23582. };
  23583. // Cylinder and cone
  23584. VertexData.CreateCylinder = function (options) {
  23585. var height = options.height || 2;
  23586. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23587. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23588. var tessellation = options.tessellation || 24;
  23589. var subdivisions = options.subdivisions || 1;
  23590. var hasRings = options.hasRings;
  23591. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23592. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23593. var faceUV = options.faceUV || new Array(3);
  23594. var faceColors = options.faceColors;
  23595. // default face colors and UV if undefined
  23596. for (var f = 0; f < 3; f++) {
  23597. if (faceColors && faceColors[f] === undefined) {
  23598. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23599. }
  23600. if (faceUV && faceUV[f] === undefined) {
  23601. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23602. }
  23603. }
  23604. var indices = [];
  23605. var positions = [];
  23606. var normals = [];
  23607. var uvs = [];
  23608. var colors = [];
  23609. var angle_step = Math.PI * 2 * arc / tessellation;
  23610. var angle;
  23611. var h;
  23612. var radius;
  23613. var tan = (diameterBottom - diameterTop) / 2 / height;
  23614. var ringVertex = BABYLON.Vector3.Zero();
  23615. var ringNormal = BABYLON.Vector3.Zero();
  23616. // positions, normals, uvs
  23617. var i;
  23618. var j;
  23619. var r;
  23620. var ringIdx = 1;
  23621. for (i = 0; i <= subdivisions; i++) {
  23622. h = i / subdivisions;
  23623. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23624. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  23625. for (r = 0; r < ringIdx; r++) {
  23626. for (j = 0; j <= tessellation; j++) {
  23627. angle = j * angle_step;
  23628. ringVertex.x = Math.cos(-angle) * radius;
  23629. ringVertex.y = -height / 2 + h * height;
  23630. ringVertex.z = Math.sin(-angle) * radius;
  23631. if (diameterTop === 0 && i === subdivisions) {
  23632. // if no top cap, reuse former normals
  23633. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23634. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23635. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23636. }
  23637. else {
  23638. ringNormal.x = ringVertex.x;
  23639. ringNormal.z = ringVertex.z;
  23640. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23641. ringNormal.normalize();
  23642. }
  23643. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23644. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23645. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23646. if (faceColors) {
  23647. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23648. }
  23649. }
  23650. }
  23651. }
  23652. // indices
  23653. var s;
  23654. i = 0;
  23655. for (s = 0; s < subdivisions; s++) {
  23656. for (j = 0; j < tessellation; j++) {
  23657. var i0 = i * (tessellation + 1) + j;
  23658. var i1 = (i + 1) * (tessellation + 1) + j;
  23659. var i2 = i * (tessellation + 1) + (j + 1);
  23660. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23661. indices.push(i0, i1, i2);
  23662. indices.push(i3, i2, i1);
  23663. }
  23664. i = (hasRings) ? (i + 2) : (i + 1);
  23665. }
  23666. // Caps
  23667. var createCylinderCap = function (isTop) {
  23668. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23669. if (radius === 0) {
  23670. return;
  23671. }
  23672. // Cap positions, normals & uvs
  23673. var angle;
  23674. var circleVector;
  23675. var i;
  23676. var u = (isTop) ? faceUV[2] : faceUV[0];
  23677. var c;
  23678. if (faceColors) {
  23679. c = (isTop) ? faceColors[2] : faceColors[0];
  23680. }
  23681. // cap center
  23682. var vbase = positions.length / 3;
  23683. var offset = isTop ? height / 2 : -height / 2;
  23684. var center = new BABYLON.Vector3(0, offset, 0);
  23685. positions.push(center.x, center.y, center.z);
  23686. normals.push(0, isTop ? 1 : -1, 0);
  23687. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23688. if (faceColors) {
  23689. colors.push(c.r, c.g, c.b, c.a);
  23690. }
  23691. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23692. for (i = 0; i <= tessellation; i++) {
  23693. angle = Math.PI * 2 * i * arc / tessellation;
  23694. var cos = Math.cos(-angle);
  23695. var sin = Math.sin(-angle);
  23696. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23697. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23698. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23699. normals.push(0, isTop ? 1 : -1, 0);
  23700. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23701. if (faceColors) {
  23702. colors.push(c.r, c.g, c.b, c.a);
  23703. }
  23704. }
  23705. // Cap indices
  23706. for (i = 0; i < tessellation; i++) {
  23707. if (!isTop) {
  23708. indices.push(vbase);
  23709. indices.push(vbase + (i + 1));
  23710. indices.push(vbase + (i + 2));
  23711. }
  23712. else {
  23713. indices.push(vbase);
  23714. indices.push(vbase + (i + 2));
  23715. indices.push(vbase + (i + 1));
  23716. }
  23717. }
  23718. };
  23719. // add caps to geometry
  23720. createCylinderCap(false);
  23721. createCylinderCap(true);
  23722. // Sides
  23723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23724. var vertexData = new VertexData();
  23725. vertexData.indices = indices;
  23726. vertexData.positions = positions;
  23727. vertexData.normals = normals;
  23728. vertexData.uvs = uvs;
  23729. if (faceColors) {
  23730. vertexData.colors = colors;
  23731. }
  23732. return vertexData;
  23733. };
  23734. VertexData.CreateTorus = function (options) {
  23735. var indices = [];
  23736. var positions = [];
  23737. var normals = [];
  23738. var uvs = [];
  23739. var diameter = options.diameter || 1;
  23740. var thickness = options.thickness || 0.5;
  23741. var tessellation = options.tessellation || 16;
  23742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23743. var stride = tessellation + 1;
  23744. for (var i = 0; i <= tessellation; i++) {
  23745. var u = i / tessellation;
  23746. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23747. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23748. for (var j = 0; j <= tessellation; j++) {
  23749. var v = 1 - j / tessellation;
  23750. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23751. var dx = Math.cos(innerAngle);
  23752. var dy = Math.sin(innerAngle);
  23753. // Create a vertex.
  23754. var normal = new BABYLON.Vector3(dx, dy, 0);
  23755. var position = normal.scale(thickness / 2);
  23756. var textureCoordinate = new BABYLON.Vector2(u, v);
  23757. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23758. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23759. positions.push(position.x, position.y, position.z);
  23760. normals.push(normal.x, normal.y, normal.z);
  23761. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23762. // And create indices for two triangles.
  23763. var nextI = (i + 1) % stride;
  23764. var nextJ = (j + 1) % stride;
  23765. indices.push(i * stride + j);
  23766. indices.push(i * stride + nextJ);
  23767. indices.push(nextI * stride + j);
  23768. indices.push(i * stride + nextJ);
  23769. indices.push(nextI * stride + nextJ);
  23770. indices.push(nextI * stride + j);
  23771. }
  23772. }
  23773. // Sides
  23774. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23775. // Result
  23776. var vertexData = new VertexData();
  23777. vertexData.indices = indices;
  23778. vertexData.positions = positions;
  23779. vertexData.normals = normals;
  23780. vertexData.uvs = uvs;
  23781. return vertexData;
  23782. };
  23783. VertexData.CreateLines = function (options) {
  23784. var indices = [];
  23785. var positions = [];
  23786. var points = options.points;
  23787. for (var index = 0; index < points.length; index++) {
  23788. positions.push(points[index].x, points[index].y, points[index].z);
  23789. if (index > 0) {
  23790. indices.push(index - 1);
  23791. indices.push(index);
  23792. }
  23793. }
  23794. // Result
  23795. var vertexData = new VertexData();
  23796. vertexData.indices = indices;
  23797. vertexData.positions = positions;
  23798. return vertexData;
  23799. };
  23800. VertexData.CreateDashedLines = function (options) {
  23801. var dashSize = options.dashSize || 3;
  23802. var gapSize = options.gapSize || 1;
  23803. var dashNb = options.dashNb || 200;
  23804. var points = options.points;
  23805. var positions = new Array();
  23806. var indices = new Array();
  23807. var curvect = BABYLON.Vector3.Zero();
  23808. var lg = 0;
  23809. var nb = 0;
  23810. var shft = 0;
  23811. var dashshft = 0;
  23812. var curshft = 0;
  23813. var idx = 0;
  23814. var i = 0;
  23815. for (i = 0; i < points.length - 1; i++) {
  23816. points[i + 1].subtractToRef(points[i], curvect);
  23817. lg += curvect.length();
  23818. }
  23819. shft = lg / dashNb;
  23820. dashshft = dashSize * shft / (dashSize + gapSize);
  23821. for (i = 0; i < points.length - 1; i++) {
  23822. points[i + 1].subtractToRef(points[i], curvect);
  23823. nb = Math.floor(curvect.length() / shft);
  23824. curvect.normalize();
  23825. for (var j = 0; j < nb; j++) {
  23826. curshft = shft * j;
  23827. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23828. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23829. indices.push(idx, idx + 1);
  23830. idx += 2;
  23831. }
  23832. }
  23833. // Result
  23834. var vertexData = new VertexData();
  23835. vertexData.positions = positions;
  23836. vertexData.indices = indices;
  23837. return vertexData;
  23838. };
  23839. VertexData.CreateGround = function (options) {
  23840. var indices = [];
  23841. var positions = [];
  23842. var normals = [];
  23843. var uvs = [];
  23844. var row, col;
  23845. var width = options.width || 1;
  23846. var height = options.height || 1;
  23847. var subdivisions = options.subdivisions || 1;
  23848. for (row = 0; row <= subdivisions; row++) {
  23849. for (col = 0; col <= subdivisions; col++) {
  23850. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23851. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23852. positions.push(position.x, position.y, position.z);
  23853. normals.push(normal.x, normal.y, normal.z);
  23854. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23855. }
  23856. }
  23857. for (row = 0; row < subdivisions; row++) {
  23858. for (col = 0; col < subdivisions; col++) {
  23859. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23860. indices.push(col + 1 + row * (subdivisions + 1));
  23861. indices.push(col + row * (subdivisions + 1));
  23862. indices.push(col + (row + 1) * (subdivisions + 1));
  23863. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23864. indices.push(col + row * (subdivisions + 1));
  23865. }
  23866. }
  23867. // Result
  23868. var vertexData = new VertexData();
  23869. vertexData.indices = indices;
  23870. vertexData.positions = positions;
  23871. vertexData.normals = normals;
  23872. vertexData.uvs = uvs;
  23873. return vertexData;
  23874. };
  23875. VertexData.CreateTiledGround = function (options) {
  23876. var xmin = options.xmin;
  23877. var zmin = options.zmin;
  23878. var xmax = options.xmax;
  23879. var zmax = options.zmax;
  23880. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23881. var precision = options.precision || { w: 1, h: 1 };
  23882. var indices = [];
  23883. var positions = [];
  23884. var normals = [];
  23885. var uvs = [];
  23886. var row, col, tileRow, tileCol;
  23887. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23888. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23889. precision.w = (precision.w < 1) ? 1 : precision.w;
  23890. precision.h = (precision.h < 1) ? 1 : precision.h;
  23891. var tileSize = {
  23892. 'w': (xmax - xmin) / subdivisions.w,
  23893. 'h': (zmax - zmin) / subdivisions.h
  23894. };
  23895. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23896. // Indices
  23897. var base = positions.length / 3;
  23898. var rowLength = precision.w + 1;
  23899. for (row = 0; row < precision.h; row++) {
  23900. for (col = 0; col < precision.w; col++) {
  23901. var square = [
  23902. base + col + row * rowLength,
  23903. base + (col + 1) + row * rowLength,
  23904. base + (col + 1) + (row + 1) * rowLength,
  23905. base + col + (row + 1) * rowLength
  23906. ];
  23907. indices.push(square[1]);
  23908. indices.push(square[2]);
  23909. indices.push(square[3]);
  23910. indices.push(square[0]);
  23911. indices.push(square[1]);
  23912. indices.push(square[3]);
  23913. }
  23914. }
  23915. // Position, normals and uvs
  23916. var position = BABYLON.Vector3.Zero();
  23917. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23918. for (row = 0; row <= precision.h; row++) {
  23919. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23920. for (col = 0; col <= precision.w; col++) {
  23921. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23922. position.y = 0;
  23923. positions.push(position.x, position.y, position.z);
  23924. normals.push(normal.x, normal.y, normal.z);
  23925. uvs.push(col / precision.w, row / precision.h);
  23926. }
  23927. }
  23928. }
  23929. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23930. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23931. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23932. }
  23933. }
  23934. // Result
  23935. var vertexData = new VertexData();
  23936. vertexData.indices = indices;
  23937. vertexData.positions = positions;
  23938. vertexData.normals = normals;
  23939. vertexData.uvs = uvs;
  23940. return vertexData;
  23941. };
  23942. VertexData.CreateGroundFromHeightMap = function (options) {
  23943. var indices = [];
  23944. var positions = [];
  23945. var normals = [];
  23946. var uvs = [];
  23947. var row, col;
  23948. // Vertices
  23949. for (row = 0; row <= options.subdivisions; row++) {
  23950. for (col = 0; col <= options.subdivisions; col++) {
  23951. 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));
  23952. // Compute height
  23953. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23954. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23955. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23956. var r = options.buffer[pos] / 255.0;
  23957. var g = options.buffer[pos + 1] / 255.0;
  23958. var b = options.buffer[pos + 2] / 255.0;
  23959. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23960. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23961. // Add vertex
  23962. positions.push(position.x, position.y, position.z);
  23963. normals.push(0, 0, 0);
  23964. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23965. }
  23966. }
  23967. // Indices
  23968. for (row = 0; row < options.subdivisions; row++) {
  23969. for (col = 0; col < options.subdivisions; col++) {
  23970. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23971. indices.push(col + 1 + row * (options.subdivisions + 1));
  23972. indices.push(col + row * (options.subdivisions + 1));
  23973. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23974. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23975. indices.push(col + row * (options.subdivisions + 1));
  23976. }
  23977. }
  23978. // Normals
  23979. VertexData.ComputeNormals(positions, indices, normals);
  23980. // Result
  23981. var vertexData = new VertexData();
  23982. vertexData.indices = indices;
  23983. vertexData.positions = positions;
  23984. vertexData.normals = normals;
  23985. vertexData.uvs = uvs;
  23986. return vertexData;
  23987. };
  23988. VertexData.CreatePlane = function (options) {
  23989. var indices = [];
  23990. var positions = [];
  23991. var normals = [];
  23992. var uvs = [];
  23993. var width = options.width || options.size || 1;
  23994. var height = options.height || options.size || 1;
  23995. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23996. // Vertices
  23997. var halfWidth = width / 2.0;
  23998. var halfHeight = height / 2.0;
  23999. positions.push(-halfWidth, -halfHeight, 0);
  24000. normals.push(0, 0, -1.0);
  24001. uvs.push(0.0, 0.0);
  24002. positions.push(halfWidth, -halfHeight, 0);
  24003. normals.push(0, 0, -1.0);
  24004. uvs.push(1.0, 0.0);
  24005. positions.push(halfWidth, halfHeight, 0);
  24006. normals.push(0, 0, -1.0);
  24007. uvs.push(1.0, 1.0);
  24008. positions.push(-halfWidth, halfHeight, 0);
  24009. normals.push(0, 0, -1.0);
  24010. uvs.push(0.0, 1.0);
  24011. // Indices
  24012. indices.push(0);
  24013. indices.push(1);
  24014. indices.push(2);
  24015. indices.push(0);
  24016. indices.push(2);
  24017. indices.push(3);
  24018. // Sides
  24019. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24020. // Result
  24021. var vertexData = new VertexData();
  24022. vertexData.indices = indices;
  24023. vertexData.positions = positions;
  24024. vertexData.normals = normals;
  24025. vertexData.uvs = uvs;
  24026. return vertexData;
  24027. };
  24028. VertexData.CreateDisc = function (options) {
  24029. var positions = [];
  24030. var indices = [];
  24031. var normals = [];
  24032. var uvs = [];
  24033. var radius = options.radius || 0.5;
  24034. var tessellation = options.tessellation || 64;
  24035. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24037. // positions and uvs
  24038. positions.push(0, 0, 0); // disc center first
  24039. uvs.push(0.5, 0.5);
  24040. var theta = Math.PI * 2 * arc;
  24041. var step = theta / tessellation;
  24042. for (var a = 0; a < theta; a += step) {
  24043. var x = Math.cos(a);
  24044. var y = Math.sin(a);
  24045. var u = (x + 1) / 2;
  24046. var v = (1 - y) / 2;
  24047. positions.push(radius * x, radius * y, 0);
  24048. uvs.push(u, v);
  24049. }
  24050. if (arc === 1) {
  24051. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24052. uvs.push(uvs[2], uvs[3]);
  24053. }
  24054. //indices
  24055. var vertexNb = positions.length / 3;
  24056. for (var i = 1; i < vertexNb - 1; i++) {
  24057. indices.push(i + 1, 0, i);
  24058. }
  24059. // result
  24060. VertexData.ComputeNormals(positions, indices, normals);
  24061. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24062. var vertexData = new VertexData();
  24063. vertexData.indices = indices;
  24064. vertexData.positions = positions;
  24065. vertexData.normals = normals;
  24066. vertexData.uvs = uvs;
  24067. return vertexData;
  24068. };
  24069. VertexData.CreateIcoSphere = function (options) {
  24070. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24071. var radius = options.radius || 1;
  24072. var flat = (options.flat === undefined) ? true : options.flat;
  24073. var subdivisions = options.subdivisions || 4;
  24074. var radiusX = options.radiusX || radius;
  24075. var radiusY = options.radiusY || radius;
  24076. var radiusZ = options.radiusZ || radius;
  24077. var t = (1 + Math.sqrt(5)) / 2;
  24078. // 12 vertex x,y,z
  24079. var ico_vertices = [
  24080. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24081. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24082. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24083. ];
  24084. // index of 3 vertex makes a face of icopshere
  24085. var ico_indices = [
  24086. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  24087. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  24088. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  24089. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  24090. ];
  24091. // uv as integer step (not pixels !)
  24092. var ico_vertexuv = [
  24093. 4, 1, 2, 1, 6, 3, 5, 4,
  24094. 4, 3, 3, 2, 7, 4, 3, 0,
  24095. 1, 0, 0, 1, 5, 0, 5, 2 // v8-11
  24096. ];
  24097. // Vertices [0, 1, ...9, A, B] : position on UV plane (7,8,9,10=A have duplicate position)
  24098. // v=5h 9+ 8+ 7+
  24099. // v=4h 9+ 3 6 A+
  24100. // v=3h 9+ 4 2 A+
  24101. // v=2h 9+ 5 B A+
  24102. // v=1h 9 1 0 A+
  24103. // v=0h 8 7 A
  24104. // u=0 1 2 3 4 5 6 7 8 9 *a
  24105. //
  24106. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24107. var ustep = 97 / 1024;
  24108. var vstep = 168 / 1024;
  24109. var uoffset = 50 / 1024;
  24110. var voffset = 51 / 1024;
  24111. var indices = [];
  24112. var positions = [];
  24113. var normals = [];
  24114. var uvs = [];
  24115. var current_indice = 0;
  24116. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24117. var face_vertex_pos = new Array(3);
  24118. var face_vertex_uv = new Array(3);
  24119. var v012;
  24120. for (v012 = 0; v012 < 3; v012++) {
  24121. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24122. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24123. }
  24124. // create all with normals
  24125. for (var face = 0; face < 20; face++) {
  24126. // 3 vertex per face
  24127. for (v012 = 0; v012 < 3; v012++) {
  24128. // look up vertex 0,1,2 to its index in 0 to 11
  24129. var v_id = ico_indices[3 * face + v012];
  24130. // vertex have 3D position (x,y,z)
  24131. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * v_id], ico_vertices[3 * v_id + 1], ico_vertices[3 * v_id + 2]);
  24132. // Normalize to get normal, then scale to radius
  24133. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24134. // uv from vertex ID (may need fix due to unwrap on texture plan, unalias needed)
  24135. // vertex may get to different UV according to belonging face (see fix below)
  24136. var fix = 0;
  24137. // Vertice 9 UV to be fixed
  24138. if (face === 5 && v012 === 2) {
  24139. fix = 1;
  24140. }
  24141. if (face === 15 && v012 === 1) {
  24142. fix = 2;
  24143. }
  24144. if (face === 10 && v012 === 1) {
  24145. fix = 3;
  24146. }
  24147. if (face === 14 && v012 === 2) {
  24148. fix = 4;
  24149. }
  24150. // vertice 10 UV to be fixed
  24151. if (face === 4 && v012 === 1) {
  24152. fix = 1;
  24153. }
  24154. if (face === 7 && v012 === 1) {
  24155. fix = 2;
  24156. }
  24157. if (face === 17 && v012 === 2) {
  24158. fix = 3;
  24159. }
  24160. if (face === 8 && v012 === 0) {
  24161. fix = 4;
  24162. }
  24163. // vertice 7 UV to be fixed
  24164. if (face === 8 && v012 === 1) {
  24165. fix = 5;
  24166. }
  24167. if (face === 18 && v012 === 0) {
  24168. fix = 5;
  24169. }
  24170. // vertice 8 UV to be fixed
  24171. if (face === 13 && v012 === 2) {
  24172. fix = 5;
  24173. }
  24174. if (face === 14 && v012 === 1) {
  24175. fix = 5;
  24176. }
  24177. if (face === 18 && v012 === 2) {
  24178. fix = 5;
  24179. }
  24180. //
  24181. face_vertex_uv[v012].copyFromFloats((ico_vertexuv[2 * v_id] + fix) * ustep + uoffset, (ico_vertexuv[2 * v_id + 1] + fix) * vstep + voffset);
  24182. }
  24183. // Subdivide the face (interpolate pos, norm, uv)
  24184. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24185. // - norm is linear interpolation of vertex corner normal
  24186. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24187. // - uv is linear interpolation
  24188. //
  24189. // Topology is as below for sub-divide by 2
  24190. // vertex shown as v0,v1,v2
  24191. // interp index is i1 to progress in range [v0,v1[
  24192. // interp index is i2 to progress in range [v0,v2[
  24193. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  24194. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24195. //
  24196. //
  24197. // i2 v2
  24198. // ^ ^
  24199. // / / \
  24200. // / / \
  24201. // / / \
  24202. // / / (0,1) \
  24203. // / #---------\
  24204. // / / \ (0,0)'/ \
  24205. // / / \ / \
  24206. // / / \ / \
  24207. // / / (0,0) \ / (1,0) \
  24208. // / #---------#---------\
  24209. // v0 v1
  24210. //
  24211. // --------------------> i1
  24212. //
  24213. // interp of (i1,i2):
  24214. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  24215. // along i1 : lerp(x0,x1, i1/(S-i2))
  24216. //
  24217. // centroid of triangle is needed to get help normal computation
  24218. // (c1,c2) are used for centroid location
  24219. var interp_vertex = function (i1, i2, c1, c2) {
  24220. // vertex is interpolated from
  24221. // - face_vertex_pos[0..2]
  24222. // - face_vertex_uv[0..2]
  24223. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  24224. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  24225. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  24226. pos_interp.normalize();
  24227. pos_interp.x *= radiusX;
  24228. pos_interp.y *= radiusY;
  24229. pos_interp.z *= radiusZ;
  24230. var vertex_normal;
  24231. if (flat) {
  24232. // in flat mode, recalculate normal as face centroid normal
  24233. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  24234. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  24235. var centroid_interp = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  24236. vertex_normal = BABYLON.Vector3.Normalize(centroid_interp);
  24237. }
  24238. else {
  24239. // in smooth mode, recalculate normal from each single vertex position
  24240. vertex_normal = BABYLON.Vector3.Normalize(pos_interp);
  24241. }
  24242. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  24243. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  24244. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  24245. positions.push(pos_interp.x, pos_interp.y, pos_interp.z);
  24246. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  24247. uvs.push(uv_interp.x, uv_interp.y);
  24248. // push each vertex has member of a face
  24249. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  24250. indices.push(current_indice);
  24251. current_indice++;
  24252. };
  24253. for (var i2 = 0; i2 < subdivisions; i2++) {
  24254. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  24255. // face : (i1,i2) for /\ :
  24256. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  24257. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24258. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24259. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  24260. if (i1 + i2 + 1 < subdivisions) {
  24261. // face : (i1,i2)' for \/ :
  24262. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  24263. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24264. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24265. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  24266. }
  24267. }
  24268. }
  24269. }
  24270. // Sides
  24271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24272. // Result
  24273. var vertexData = new VertexData();
  24274. vertexData.indices = indices;
  24275. vertexData.positions = positions;
  24276. vertexData.normals = normals;
  24277. vertexData.uvs = uvs;
  24278. return vertexData;
  24279. };
  24280. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  24281. VertexData.CreatePolyhedron = function (options) {
  24282. // provided polyhedron types :
  24283. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  24284. // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
  24285. var polyhedra = [];
  24286. polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
  24287. polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
  24288. polyhedra[2] = {
  24289. vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
  24290. face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
  24291. };
  24292. polyhedra[3] = {
  24293. vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
  24294. face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
  24295. };
  24296. polyhedra[4] = {
  24297. vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
  24298. face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
  24299. };
  24300. polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
  24301. polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
  24302. polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
  24303. polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
  24304. polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
  24305. polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
  24306. polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
  24307. polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
  24308. polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
  24309. polyhedra[14] = {
  24310. vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
  24311. face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
  24312. };
  24313. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  24314. var size = options.size;
  24315. var sizeX = options.sizeX || size || 1;
  24316. var sizeY = options.sizeY || size || 1;
  24317. var sizeZ = options.sizeZ || size || 1;
  24318. var data = options.custom || polyhedra[type];
  24319. var nbfaces = data.face.length;
  24320. var faceUV = options.faceUV || new Array(nbfaces);
  24321. var faceColors = options.faceColors;
  24322. var flat = (options.flat === undefined) ? true : options.flat;
  24323. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24324. var positions = [];
  24325. var indices = [];
  24326. var normals = [];
  24327. var uvs = [];
  24328. var colors = [];
  24329. var index = 0;
  24330. var faceIdx = 0; // face cursor in the array "indexes"
  24331. var indexes = [];
  24332. var i = 0;
  24333. var f = 0;
  24334. var u, v, ang, x, y, tmp;
  24335. // default face colors and UV if undefined
  24336. if (flat) {
  24337. for (f = 0; f < nbfaces; f++) {
  24338. if (faceColors && faceColors[f] === undefined) {
  24339. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24340. }
  24341. if (faceUV && faceUV[f] === undefined) {
  24342. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24343. }
  24344. }
  24345. }
  24346. if (!flat) {
  24347. for (i = 0; i < data.vertex.length; i++) {
  24348. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  24349. uvs.push(0, 0);
  24350. }
  24351. for (f = 0; f < nbfaces; f++) {
  24352. for (i = 0; i < data.face[f].length - 2; i++) {
  24353. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  24354. }
  24355. }
  24356. }
  24357. else {
  24358. for (f = 0; f < nbfaces; f++) {
  24359. var fl = data.face[f].length; // number of vertices of the current face
  24360. ang = 2 * Math.PI / fl;
  24361. x = 0.5 * Math.tan(ang / 2);
  24362. y = 0.5;
  24363. // positions, uvs, colors
  24364. for (i = 0; i < fl; i++) {
  24365. // positions
  24366. positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
  24367. indexes.push(index);
  24368. index++;
  24369. // uvs
  24370. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  24371. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  24372. uvs.push(u, v);
  24373. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  24374. y = x * Math.sin(ang) + y * Math.cos(ang);
  24375. x = tmp;
  24376. // colors
  24377. if (faceColors) {
  24378. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  24379. }
  24380. }
  24381. // indices from indexes
  24382. for (i = 0; i < fl - 2; i++) {
  24383. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  24384. }
  24385. faceIdx += fl;
  24386. }
  24387. }
  24388. VertexData.ComputeNormals(positions, indices, normals);
  24389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24390. var vertexData = new VertexData();
  24391. vertexData.positions = positions;
  24392. vertexData.indices = indices;
  24393. vertexData.normals = normals;
  24394. vertexData.uvs = uvs;
  24395. if (faceColors && flat) {
  24396. vertexData.colors = colors;
  24397. }
  24398. return vertexData;
  24399. };
  24400. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24401. VertexData.CreateTorusKnot = function (options) {
  24402. var indices = [];
  24403. var positions = [];
  24404. var normals = [];
  24405. var uvs = [];
  24406. var radius = options.radius || 2;
  24407. var tube = options.tube || 0.5;
  24408. var radialSegments = options.radialSegments || 32;
  24409. var tubularSegments = options.tubularSegments || 32;
  24410. var p = options.p || 2;
  24411. var q = options.q || 3;
  24412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24413. // Helper
  24414. var getPos = function (angle) {
  24415. var cu = Math.cos(angle);
  24416. var su = Math.sin(angle);
  24417. var quOverP = q / p * angle;
  24418. var cs = Math.cos(quOverP);
  24419. var tx = radius * (2 + cs) * 0.5 * cu;
  24420. var ty = radius * (2 + cs) * su * 0.5;
  24421. var tz = radius * Math.sin(quOverP) * 0.5;
  24422. return new BABYLON.Vector3(tx, ty, tz);
  24423. };
  24424. // Vertices
  24425. var i;
  24426. var j;
  24427. for (i = 0; i <= radialSegments; i++) {
  24428. var modI = i % radialSegments;
  24429. var u = modI / radialSegments * 2 * p * Math.PI;
  24430. var p1 = getPos(u);
  24431. var p2 = getPos(u + 0.01);
  24432. var tang = p2.subtract(p1);
  24433. var n = p2.add(p1);
  24434. var bitan = BABYLON.Vector3.Cross(tang, n);
  24435. n = BABYLON.Vector3.Cross(bitan, tang);
  24436. bitan.normalize();
  24437. n.normalize();
  24438. for (j = 0; j < tubularSegments; j++) {
  24439. var modJ = j % tubularSegments;
  24440. var v = modJ / tubularSegments * 2 * Math.PI;
  24441. var cx = -tube * Math.cos(v);
  24442. var cy = tube * Math.sin(v);
  24443. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24444. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24445. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24446. uvs.push(i / radialSegments);
  24447. uvs.push(j / tubularSegments);
  24448. }
  24449. }
  24450. for (i = 0; i < radialSegments; i++) {
  24451. for (j = 0; j < tubularSegments; j++) {
  24452. var jNext = (j + 1) % tubularSegments;
  24453. var a = i * tubularSegments + j;
  24454. var b = (i + 1) * tubularSegments + j;
  24455. var c = (i + 1) * tubularSegments + jNext;
  24456. var d = i * tubularSegments + jNext;
  24457. indices.push(d);
  24458. indices.push(b);
  24459. indices.push(a);
  24460. indices.push(d);
  24461. indices.push(c);
  24462. indices.push(b);
  24463. }
  24464. }
  24465. // Normals
  24466. VertexData.ComputeNormals(positions, indices, normals);
  24467. // Sides
  24468. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24469. // Result
  24470. var vertexData = new VertexData();
  24471. vertexData.indices = indices;
  24472. vertexData.positions = positions;
  24473. vertexData.normals = normals;
  24474. vertexData.uvs = uvs;
  24475. return vertexData;
  24476. };
  24477. // Tools
  24478. /**
  24479. * @param {any} - positions (number[] or Float32Array)
  24480. * @param {any} - indices (number[] or Uint16Array)
  24481. * @param {any} - normals (number[] or Float32Array)
  24482. */
  24483. VertexData.ComputeNormals = function (positions, indices, normals) {
  24484. var index = 0;
  24485. // temp Vector3
  24486. var p1p2 = BABYLON.Vector3.Zero();
  24487. var p3p2 = BABYLON.Vector3.Zero();
  24488. var faceNormal = BABYLON.Vector3.Zero();
  24489. var vertexNormali1 = BABYLON.Vector3.Zero();
  24490. for (index = 0; index < positions.length; index++) {
  24491. normals[index] = 0.0;
  24492. }
  24493. // indice triplet = 1 face
  24494. var nbFaces = indices.length / 3;
  24495. for (index = 0; index < nbFaces; index++) {
  24496. var i1 = indices[index * 3];
  24497. var i2 = indices[index * 3 + 1];
  24498. var i3 = indices[index * 3 + 2];
  24499. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  24500. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  24501. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  24502. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  24503. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  24504. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  24505. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24506. faceNormal.normalize();
  24507. normals[i1 * 3] += faceNormal.x;
  24508. normals[i1 * 3 + 1] += faceNormal.y;
  24509. normals[i1 * 3 + 2] += faceNormal.z;
  24510. normals[i2 * 3] += faceNormal.x;
  24511. normals[i2 * 3 + 1] += faceNormal.y;
  24512. normals[i2 * 3 + 2] += faceNormal.z;
  24513. normals[i3 * 3] += faceNormal.x;
  24514. normals[i3 * 3 + 1] += faceNormal.y;
  24515. normals[i3 * 3 + 2] += faceNormal.z;
  24516. }
  24517. // last normalization
  24518. for (index = 0; index < normals.length / 3; index++) {
  24519. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24520. vertexNormali1.normalize();
  24521. normals[index * 3] = vertexNormali1.x;
  24522. normals[index * 3 + 1] = vertexNormali1.y;
  24523. normals[index * 3 + 2] = vertexNormali1.z;
  24524. }
  24525. };
  24526. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24527. var li = indices.length;
  24528. var ln = normals.length;
  24529. var i;
  24530. var n;
  24531. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24532. switch (sideOrientation) {
  24533. case BABYLON.Mesh.FRONTSIDE:
  24534. // nothing changed
  24535. break;
  24536. case BABYLON.Mesh.BACKSIDE:
  24537. var tmp;
  24538. // indices
  24539. for (i = 0; i < li; i += 3) {
  24540. tmp = indices[i];
  24541. indices[i] = indices[i + 2];
  24542. indices[i + 2] = tmp;
  24543. }
  24544. // normals
  24545. for (n = 0; n < ln; n++) {
  24546. normals[n] = -normals[n];
  24547. }
  24548. break;
  24549. case BABYLON.Mesh.DOUBLESIDE:
  24550. // positions
  24551. var lp = positions.length;
  24552. var l = lp / 3;
  24553. for (var p = 0; p < lp; p++) {
  24554. positions[lp + p] = positions[p];
  24555. }
  24556. // indices
  24557. for (i = 0; i < li; i += 3) {
  24558. indices[i + li] = indices[i + 2] + l;
  24559. indices[i + 1 + li] = indices[i + 1] + l;
  24560. indices[i + 2 + li] = indices[i] + l;
  24561. }
  24562. // normals
  24563. for (n = 0; n < ln; n++) {
  24564. normals[ln + n] = -normals[n];
  24565. }
  24566. // uvs
  24567. var lu = uvs.length;
  24568. for (var u = 0; u < lu; u++) {
  24569. uvs[u + lu] = uvs[u];
  24570. }
  24571. break;
  24572. }
  24573. };
  24574. return VertexData;
  24575. })();
  24576. BABYLON.VertexData = VertexData;
  24577. })(BABYLON || (BABYLON = {}));
  24578. var BABYLON;
  24579. (function (BABYLON) {
  24580. var Tags = (function () {
  24581. function Tags() {
  24582. }
  24583. Tags.EnableFor = function (obj) {
  24584. obj._tags = obj._tags || {};
  24585. obj.hasTags = function () {
  24586. return Tags.HasTags(obj);
  24587. };
  24588. obj.addTags = function (tagsString) {
  24589. return Tags.AddTagsTo(obj, tagsString);
  24590. };
  24591. obj.removeTags = function (tagsString) {
  24592. return Tags.RemoveTagsFrom(obj, tagsString);
  24593. };
  24594. obj.matchesTagsQuery = function (tagsQuery) {
  24595. return Tags.MatchesQuery(obj, tagsQuery);
  24596. };
  24597. };
  24598. Tags.DisableFor = function (obj) {
  24599. delete obj._tags;
  24600. delete obj.hasTags;
  24601. delete obj.addTags;
  24602. delete obj.removeTags;
  24603. delete obj.matchesTagsQuery;
  24604. };
  24605. Tags.HasTags = function (obj) {
  24606. if (!obj._tags) {
  24607. return false;
  24608. }
  24609. return !BABYLON.Tools.IsEmpty(obj._tags);
  24610. };
  24611. Tags.GetTags = function (obj) {
  24612. if (!obj._tags) {
  24613. return null;
  24614. }
  24615. return obj._tags;
  24616. };
  24617. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24618. // a tag cannot start with '||', '&&', and '!'
  24619. // it cannot contain whitespaces
  24620. Tags.AddTagsTo = function (obj, tagsString) {
  24621. if (!tagsString) {
  24622. return;
  24623. }
  24624. if (typeof tagsString !== "string") {
  24625. return;
  24626. }
  24627. var tags = tagsString.split(" ");
  24628. for (var t in tags) {
  24629. Tags._AddTagTo(obj, tags[t]);
  24630. }
  24631. };
  24632. Tags._AddTagTo = function (obj, tag) {
  24633. tag = tag.trim();
  24634. if (tag === "" || tag === "true" || tag === "false") {
  24635. return;
  24636. }
  24637. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24638. return;
  24639. }
  24640. Tags.EnableFor(obj);
  24641. obj._tags[tag] = true;
  24642. };
  24643. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24644. if (!Tags.HasTags(obj)) {
  24645. return;
  24646. }
  24647. var tags = tagsString.split(" ");
  24648. for (var t in tags) {
  24649. Tags._RemoveTagFrom(obj, tags[t]);
  24650. }
  24651. };
  24652. Tags._RemoveTagFrom = function (obj, tag) {
  24653. delete obj._tags[tag];
  24654. };
  24655. Tags.MatchesQuery = function (obj, tagsQuery) {
  24656. if (tagsQuery === undefined) {
  24657. return true;
  24658. }
  24659. if (tagsQuery === "") {
  24660. return Tags.HasTags(obj);
  24661. }
  24662. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24663. };
  24664. return Tags;
  24665. })();
  24666. BABYLON.Tags = Tags;
  24667. })(BABYLON || (BABYLON = {}));
  24668. var BABYLON;
  24669. (function (BABYLON) {
  24670. var Internals;
  24671. (function (Internals) {
  24672. var AndOrNotEvaluator = (function () {
  24673. function AndOrNotEvaluator() {
  24674. }
  24675. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24676. if (!query.match(/\([^\(\)]*\)/g)) {
  24677. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24678. }
  24679. else {
  24680. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24681. // remove parenthesis
  24682. r = r.slice(1, r.length - 1);
  24683. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24684. });
  24685. }
  24686. if (query === "true") {
  24687. return true;
  24688. }
  24689. if (query === "false") {
  24690. return false;
  24691. }
  24692. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24693. };
  24694. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24695. evaluateCallback = evaluateCallback || (function (r) {
  24696. return r === "true" ? true : false;
  24697. });
  24698. var result;
  24699. var or = parenthesisContent.split("||");
  24700. for (var i in or) {
  24701. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24702. var and = ori.split("&&");
  24703. if (and.length > 1) {
  24704. for (var j = 0; j < and.length; ++j) {
  24705. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24706. if (andj !== "true" && andj !== "false") {
  24707. if (andj[0] === "!") {
  24708. result = !evaluateCallback(andj.substring(1));
  24709. }
  24710. else {
  24711. result = evaluateCallback(andj);
  24712. }
  24713. }
  24714. else {
  24715. result = andj === "true" ? true : false;
  24716. }
  24717. if (!result) {
  24718. ori = "false";
  24719. break;
  24720. }
  24721. }
  24722. }
  24723. if (result || ori === "true") {
  24724. result = true;
  24725. break;
  24726. }
  24727. // result equals false (or undefined)
  24728. if (ori !== "true" && ori !== "false") {
  24729. if (ori[0] === "!") {
  24730. result = !evaluateCallback(ori.substring(1));
  24731. }
  24732. else {
  24733. result = evaluateCallback(ori);
  24734. }
  24735. }
  24736. else {
  24737. result = ori === "true" ? true : false;
  24738. }
  24739. }
  24740. // the whole parenthesis scope is replaced by 'true' or 'false'
  24741. return result ? "true" : "false";
  24742. };
  24743. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24744. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24745. // remove whitespaces
  24746. r = r.replace(/[\s]/g, function () { return ""; });
  24747. return r.length % 2 ? "!" : "";
  24748. });
  24749. booleanString = booleanString.trim();
  24750. if (booleanString === "!true") {
  24751. booleanString = "false";
  24752. }
  24753. else if (booleanString === "!false") {
  24754. booleanString = "true";
  24755. }
  24756. return booleanString;
  24757. };
  24758. return AndOrNotEvaluator;
  24759. })();
  24760. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24762. })(BABYLON || (BABYLON = {}));
  24763. var BABYLON;
  24764. (function (BABYLON) {
  24765. var PostProcessRenderPass = (function () {
  24766. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24767. this._enabled = true;
  24768. this._refCount = 0;
  24769. this._name = name;
  24770. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24771. this.setRenderList(renderList);
  24772. this._renderTexture.onBeforeRender = beforeRender;
  24773. this._renderTexture.onAfterRender = afterRender;
  24774. this._scene = scene;
  24775. this._renderList = renderList;
  24776. }
  24777. // private
  24778. PostProcessRenderPass.prototype._incRefCount = function () {
  24779. if (this._refCount === 0) {
  24780. this._scene.customRenderTargets.push(this._renderTexture);
  24781. }
  24782. return ++this._refCount;
  24783. };
  24784. PostProcessRenderPass.prototype._decRefCount = function () {
  24785. this._refCount--;
  24786. if (this._refCount <= 0) {
  24787. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24788. }
  24789. return this._refCount;
  24790. };
  24791. PostProcessRenderPass.prototype._update = function () {
  24792. this.setRenderList(this._renderList);
  24793. };
  24794. // public
  24795. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24796. this._renderTexture.renderList = renderList;
  24797. };
  24798. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24799. return this._renderTexture;
  24800. };
  24801. return PostProcessRenderPass;
  24802. })();
  24803. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24804. })(BABYLON || (BABYLON = {}));
  24805. var BABYLON;
  24806. (function (BABYLON) {
  24807. var PostProcessRenderEffect = (function () {
  24808. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24809. this._engine = engine;
  24810. this._name = name;
  24811. this._singleInstance = singleInstance || true;
  24812. this._getPostProcess = getPostProcess;
  24813. this._cameras = [];
  24814. this._indicesForCamera = [];
  24815. this._postProcesses = {};
  24816. this._renderPasses = {};
  24817. this._renderEffectAsPasses = {};
  24818. }
  24819. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  24820. get: function () {
  24821. for (var index in this._postProcesses) {
  24822. if (!this._postProcesses[index].isSupported) {
  24823. return false;
  24824. }
  24825. }
  24826. return true;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. PostProcessRenderEffect.prototype._update = function () {
  24832. for (var renderPassName in this._renderPasses) {
  24833. this._renderPasses[renderPassName]._update();
  24834. }
  24835. };
  24836. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24837. this._renderPasses[renderPass._name] = renderPass;
  24838. this._linkParameters();
  24839. };
  24840. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24841. delete this._renderPasses[renderPass._name];
  24842. this._linkParameters();
  24843. };
  24844. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24845. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24846. this._linkParameters();
  24847. };
  24848. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24849. for (var renderPassName in this._renderPasses) {
  24850. if (renderPassName === passName) {
  24851. return this._renderPasses[passName];
  24852. }
  24853. }
  24854. };
  24855. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24856. this._renderPasses = {};
  24857. this._linkParameters();
  24858. };
  24859. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24860. var cameraKey;
  24861. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24862. for (var i = 0; i < _cam.length; i++) {
  24863. var camera = _cam[i];
  24864. var cameraName = camera.name;
  24865. if (this._singleInstance) {
  24866. cameraKey = 0;
  24867. }
  24868. else {
  24869. cameraKey = cameraName;
  24870. }
  24871. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24872. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24873. if (!this._indicesForCamera[cameraName]) {
  24874. this._indicesForCamera[cameraName] = [];
  24875. }
  24876. this._indicesForCamera[cameraName].push(index);
  24877. if (this._cameras.indexOf(camera) === -1) {
  24878. this._cameras[cameraName] = camera;
  24879. }
  24880. for (var passName in this._renderPasses) {
  24881. this._renderPasses[passName]._incRefCount();
  24882. }
  24883. }
  24884. this._linkParameters();
  24885. };
  24886. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24887. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24888. for (var i = 0; i < _cam.length; i++) {
  24889. var camera = _cam[i];
  24890. var cameraName = camera.name;
  24891. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24892. var index = this._cameras.indexOf(cameraName);
  24893. this._indicesForCamera.splice(index, 1);
  24894. this._cameras.splice(index, 1);
  24895. for (var passName in this._renderPasses) {
  24896. this._renderPasses[passName]._decRefCount();
  24897. }
  24898. }
  24899. };
  24900. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24901. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24902. for (var i = 0; i < _cam.length; i++) {
  24903. var camera = _cam[i];
  24904. var cameraName = camera.name;
  24905. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24906. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24907. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24908. }
  24909. }
  24910. for (var passName in this._renderPasses) {
  24911. this._renderPasses[passName]._incRefCount();
  24912. }
  24913. }
  24914. };
  24915. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24916. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24917. for (var i = 0; i < _cam.length; i++) {
  24918. var camera = _cam[i];
  24919. var cameraName = camera.Name;
  24920. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24921. for (var passName in this._renderPasses) {
  24922. this._renderPasses[passName]._decRefCount();
  24923. }
  24924. }
  24925. };
  24926. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24927. if (this._singleInstance) {
  24928. return this._postProcesses[0];
  24929. }
  24930. else {
  24931. return this._postProcesses[camera.name];
  24932. }
  24933. };
  24934. PostProcessRenderEffect.prototype._linkParameters = function () {
  24935. var _this = this;
  24936. for (var index in this._postProcesses) {
  24937. if (this.applyParameters) {
  24938. this.applyParameters(this._postProcesses[index]);
  24939. }
  24940. this._postProcesses[index].onBeforeRender = function (effect) {
  24941. _this._linkTextures(effect);
  24942. };
  24943. }
  24944. };
  24945. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24946. for (var renderPassName in this._renderPasses) {
  24947. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24948. }
  24949. for (var renderEffectName in this._renderEffectAsPasses) {
  24950. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24951. }
  24952. };
  24953. return PostProcessRenderEffect;
  24954. })();
  24955. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24956. })(BABYLON || (BABYLON = {}));
  24957. var BABYLON;
  24958. (function (BABYLON) {
  24959. var PostProcessRenderPipeline = (function () {
  24960. function PostProcessRenderPipeline(engine, name) {
  24961. this._engine = engine;
  24962. this._name = name;
  24963. this._renderEffects = {};
  24964. this._renderEffectsForIsolatedPass = {};
  24965. this._cameras = [];
  24966. }
  24967. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  24968. get: function () {
  24969. for (var renderEffectName in this._renderEffects) {
  24970. if (!this._renderEffects[renderEffectName].isSupported) {
  24971. return false;
  24972. }
  24973. }
  24974. return true;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24980. this._renderEffects[renderEffect._name] = renderEffect;
  24981. };
  24982. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24983. var renderEffects = this._renderEffects[renderEffectName];
  24984. if (!renderEffects) {
  24985. return;
  24986. }
  24987. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24988. };
  24989. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24990. var renderEffects = this._renderEffects[renderEffectName];
  24991. if (!renderEffects) {
  24992. return;
  24993. }
  24994. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24995. };
  24996. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24997. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24998. var indicesToDelete = [];
  24999. var i;
  25000. for (i = 0; i < _cam.length; i++) {
  25001. var camera = _cam[i];
  25002. var cameraName = camera.name;
  25003. if (this._cameras.indexOf(camera) === -1) {
  25004. this._cameras[cameraName] = camera;
  25005. }
  25006. else if (unique) {
  25007. indicesToDelete.push(i);
  25008. }
  25009. }
  25010. for (i = 0; i < indicesToDelete.length; i++) {
  25011. cameras.splice(indicesToDelete[i], 1);
  25012. }
  25013. for (var renderEffectName in this._renderEffects) {
  25014. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25015. }
  25016. };
  25017. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25018. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25019. for (var renderEffectName in this._renderEffects) {
  25020. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25021. }
  25022. for (var i = 0; i < _cam.length; i++) {
  25023. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25024. }
  25025. };
  25026. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25027. var _this = this;
  25028. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25029. var pass = null;
  25030. var renderEffectName;
  25031. for (renderEffectName in this._renderEffects) {
  25032. pass = this._renderEffects[renderEffectName].getPass(passName);
  25033. if (pass != null) {
  25034. break;
  25035. }
  25036. }
  25037. if (pass === null) {
  25038. return;
  25039. }
  25040. for (renderEffectName in this._renderEffects) {
  25041. this._renderEffects[renderEffectName]._disable(_cam);
  25042. }
  25043. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25044. for (var i = 0; i < _cam.length; i++) {
  25045. var camera = _cam[i];
  25046. var cameraName = camera.name;
  25047. 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); });
  25048. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25049. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25050. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25051. }
  25052. };
  25053. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25054. var _this = this;
  25055. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25056. for (var i = 0; i < _cam.length; i++) {
  25057. var camera = _cam[i];
  25058. var cameraName = camera.name;
  25059. 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); });
  25060. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25061. }
  25062. for (var renderEffectName in this._renderEffects) {
  25063. this._renderEffects[renderEffectName]._enable(_cam);
  25064. }
  25065. };
  25066. PostProcessRenderPipeline.prototype._update = function () {
  25067. for (var renderEffectName in this._renderEffects) {
  25068. this._renderEffects[renderEffectName]._update();
  25069. }
  25070. for (var i = 0; i < this._cameras.length; i++) {
  25071. var cameraName = this._cameras[i].name;
  25072. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25073. this._renderEffectsForIsolatedPass[cameraName]._update();
  25074. }
  25075. }
  25076. };
  25077. PostProcessRenderPipeline.prototype.dispose = function () {
  25078. // Must be implemented by children
  25079. };
  25080. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25081. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25082. return PostProcessRenderPipeline;
  25083. })();
  25084. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25085. })(BABYLON || (BABYLON = {}));
  25086. var BABYLON;
  25087. (function (BABYLON) {
  25088. var PostProcessRenderPipelineManager = (function () {
  25089. function PostProcessRenderPipelineManager() {
  25090. this._renderPipelines = {};
  25091. }
  25092. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25093. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25094. };
  25095. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25096. var renderPipeline = this._renderPipelines[renderPipelineName];
  25097. if (!renderPipeline) {
  25098. return;
  25099. }
  25100. renderPipeline._attachCameras(cameras, unique);
  25101. };
  25102. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25103. var renderPipeline = this._renderPipelines[renderPipelineName];
  25104. if (!renderPipeline) {
  25105. return;
  25106. }
  25107. renderPipeline._detachCameras(cameras);
  25108. };
  25109. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25110. var renderPipeline = this._renderPipelines[renderPipelineName];
  25111. if (!renderPipeline) {
  25112. return;
  25113. }
  25114. renderPipeline._enableEffect(renderEffectName, cameras);
  25115. };
  25116. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25117. var renderPipeline = this._renderPipelines[renderPipelineName];
  25118. if (!renderPipeline) {
  25119. return;
  25120. }
  25121. renderPipeline._disableEffect(renderEffectName, cameras);
  25122. };
  25123. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25124. var renderPipeline = this._renderPipelines[renderPipelineName];
  25125. if (!renderPipeline) {
  25126. return;
  25127. }
  25128. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25129. };
  25130. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25131. var renderPipeline = this._renderPipelines[renderPipelineName];
  25132. if (!renderPipeline) {
  25133. return;
  25134. }
  25135. renderPipeline._disableDisplayOnlyPass(cameras);
  25136. };
  25137. PostProcessRenderPipelineManager.prototype.update = function () {
  25138. for (var renderPipelineName in this._renderPipelines) {
  25139. var pipeline = this._renderPipelines[renderPipelineName];
  25140. if (!pipeline.isSupported) {
  25141. pipeline.dispose();
  25142. delete this._renderPipelines[renderPipelineName];
  25143. }
  25144. else {
  25145. pipeline._update();
  25146. }
  25147. }
  25148. };
  25149. return PostProcessRenderPipelineManager;
  25150. })();
  25151. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25152. })(BABYLON || (BABYLON = {}));
  25153. var BABYLON;
  25154. (function (BABYLON) {
  25155. var BoundingBoxRenderer = (function () {
  25156. function BoundingBoxRenderer(scene) {
  25157. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25158. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25159. this.showBackLines = true;
  25160. this.renderList = new BABYLON.SmartArray(32);
  25161. this._scene = scene;
  25162. }
  25163. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25164. if (this._colorShader) {
  25165. return;
  25166. }
  25167. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25168. attributes: ["position"],
  25169. uniforms: ["worldViewProjection", "color"]
  25170. });
  25171. var engine = this._scene.getEngine();
  25172. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25173. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25174. 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]);
  25175. };
  25176. BoundingBoxRenderer.prototype.reset = function () {
  25177. this.renderList.reset();
  25178. };
  25179. BoundingBoxRenderer.prototype.render = function () {
  25180. if (this.renderList.length === 0) {
  25181. return;
  25182. }
  25183. this._prepareRessources();
  25184. if (!this._colorShader.isReady()) {
  25185. return;
  25186. }
  25187. var engine = this._scene.getEngine();
  25188. engine.setDepthWrite(false);
  25189. this._colorShader._preBind();
  25190. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25191. var boundingBox = this.renderList.data[boundingBoxIndex];
  25192. var min = boundingBox.minimum;
  25193. var max = boundingBox.maximum;
  25194. var diff = max.subtract(min);
  25195. var median = min.add(diff.scale(0.5));
  25196. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  25197. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  25198. .multiply(boundingBox.getWorldMatrix());
  25199. // VBOs
  25200. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25201. if (this.showBackLines) {
  25202. // Back
  25203. engine.setDepthFunctionToGreaterOrEqual();
  25204. this._scene.resetCachedMaterial();
  25205. this._colorShader.setColor4("color", this.backColor.toColor4());
  25206. this._colorShader.bind(worldMatrix);
  25207. // Draw order
  25208. engine.draw(false, 0, 24);
  25209. }
  25210. // Front
  25211. engine.setDepthFunctionToLess();
  25212. this._scene.resetCachedMaterial();
  25213. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25214. this._colorShader.bind(worldMatrix);
  25215. // Draw order
  25216. engine.draw(false, 0, 24);
  25217. }
  25218. this._colorShader.unbind();
  25219. engine.setDepthFunctionToLessOrEqual();
  25220. engine.setDepthWrite(true);
  25221. };
  25222. BoundingBoxRenderer.prototype.dispose = function () {
  25223. if (!this._colorShader) {
  25224. return;
  25225. }
  25226. this._colorShader.dispose();
  25227. this._vb.dispose();
  25228. this._scene.getEngine()._releaseBuffer(this._ib);
  25229. };
  25230. return BoundingBoxRenderer;
  25231. })();
  25232. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25233. })(BABYLON || (BABYLON = {}));
  25234. var BABYLON;
  25235. (function (BABYLON) {
  25236. var Condition = (function () {
  25237. function Condition(actionManager) {
  25238. this._actionManager = actionManager;
  25239. }
  25240. Condition.prototype.isValid = function () {
  25241. return true;
  25242. };
  25243. Condition.prototype._getProperty = function (propertyPath) {
  25244. return this._actionManager._getProperty(propertyPath);
  25245. };
  25246. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25247. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25248. };
  25249. return Condition;
  25250. })();
  25251. BABYLON.Condition = Condition;
  25252. var ValueCondition = (function (_super) {
  25253. __extends(ValueCondition, _super);
  25254. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25255. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25256. _super.call(this, actionManager);
  25257. this.propertyPath = propertyPath;
  25258. this.value = value;
  25259. this.operator = operator;
  25260. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25261. this._property = this._getProperty(this.propertyPath);
  25262. }
  25263. Object.defineProperty(ValueCondition, "IsEqual", {
  25264. get: function () {
  25265. return ValueCondition._IsEqual;
  25266. },
  25267. enumerable: true,
  25268. configurable: true
  25269. });
  25270. Object.defineProperty(ValueCondition, "IsDifferent", {
  25271. get: function () {
  25272. return ValueCondition._IsDifferent;
  25273. },
  25274. enumerable: true,
  25275. configurable: true
  25276. });
  25277. Object.defineProperty(ValueCondition, "IsGreater", {
  25278. get: function () {
  25279. return ValueCondition._IsGreater;
  25280. },
  25281. enumerable: true,
  25282. configurable: true
  25283. });
  25284. Object.defineProperty(ValueCondition, "IsLesser", {
  25285. get: function () {
  25286. return ValueCondition._IsLesser;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. // Methods
  25292. ValueCondition.prototype.isValid = function () {
  25293. switch (this.operator) {
  25294. case ValueCondition.IsGreater:
  25295. return this._target[this._property] > this.value;
  25296. case ValueCondition.IsLesser:
  25297. return this._target[this._property] < this.value;
  25298. case ValueCondition.IsEqual:
  25299. case ValueCondition.IsDifferent:
  25300. var check;
  25301. if (this.value.equals) {
  25302. check = this.value.equals(this._target[this._property]);
  25303. }
  25304. else {
  25305. check = this.value === this._target[this._property];
  25306. }
  25307. return this.operator === ValueCondition.IsEqual ? check : !check;
  25308. }
  25309. return false;
  25310. };
  25311. // Statics
  25312. ValueCondition._IsEqual = 0;
  25313. ValueCondition._IsDifferent = 1;
  25314. ValueCondition._IsGreater = 2;
  25315. ValueCondition._IsLesser = 3;
  25316. return ValueCondition;
  25317. })(Condition);
  25318. BABYLON.ValueCondition = ValueCondition;
  25319. var PredicateCondition = (function (_super) {
  25320. __extends(PredicateCondition, _super);
  25321. function PredicateCondition(actionManager, predicate) {
  25322. _super.call(this, actionManager);
  25323. this.predicate = predicate;
  25324. }
  25325. PredicateCondition.prototype.isValid = function () {
  25326. return this.predicate();
  25327. };
  25328. return PredicateCondition;
  25329. })(Condition);
  25330. BABYLON.PredicateCondition = PredicateCondition;
  25331. var StateCondition = (function (_super) {
  25332. __extends(StateCondition, _super);
  25333. function StateCondition(actionManager, target, value) {
  25334. _super.call(this, actionManager);
  25335. this.value = value;
  25336. this._target = target;
  25337. }
  25338. // Methods
  25339. StateCondition.prototype.isValid = function () {
  25340. return this._target.state === this.value;
  25341. };
  25342. return StateCondition;
  25343. })(Condition);
  25344. BABYLON.StateCondition = StateCondition;
  25345. })(BABYLON || (BABYLON = {}));
  25346. var BABYLON;
  25347. (function (BABYLON) {
  25348. var Action = (function () {
  25349. function Action(triggerOptions, condition) {
  25350. this.triggerOptions = triggerOptions;
  25351. if (triggerOptions.parameter) {
  25352. this.trigger = triggerOptions.trigger;
  25353. this._triggerParameter = triggerOptions.parameter;
  25354. }
  25355. else {
  25356. this.trigger = triggerOptions;
  25357. }
  25358. this._nextActiveAction = this;
  25359. this._condition = condition;
  25360. }
  25361. // Methods
  25362. Action.prototype._prepare = function () {
  25363. };
  25364. Action.prototype.getTriggerParameter = function () {
  25365. return this._triggerParameter;
  25366. };
  25367. Action.prototype._executeCurrent = function (evt) {
  25368. if (this._nextActiveAction._condition) {
  25369. var condition = this._nextActiveAction._condition;
  25370. var currentRenderId = this._actionManager.getScene().getRenderId();
  25371. // We cache the current evaluation for the current frame
  25372. if (condition._evaluationId === currentRenderId) {
  25373. if (!condition._currentResult) {
  25374. return;
  25375. }
  25376. }
  25377. else {
  25378. condition._evaluationId = currentRenderId;
  25379. if (!condition.isValid()) {
  25380. condition._currentResult = false;
  25381. return;
  25382. }
  25383. condition._currentResult = true;
  25384. }
  25385. }
  25386. this._nextActiveAction.execute(evt);
  25387. if (this._nextActiveAction._child) {
  25388. if (!this._nextActiveAction._child._actionManager) {
  25389. this._nextActiveAction._child._actionManager = this._actionManager;
  25390. }
  25391. this._nextActiveAction = this._nextActiveAction._child;
  25392. }
  25393. else {
  25394. this._nextActiveAction = this;
  25395. }
  25396. };
  25397. Action.prototype.execute = function (evt) {
  25398. };
  25399. Action.prototype.then = function (action) {
  25400. this._child = action;
  25401. action._actionManager = this._actionManager;
  25402. action._prepare();
  25403. return action;
  25404. };
  25405. Action.prototype._getProperty = function (propertyPath) {
  25406. return this._actionManager._getProperty(propertyPath);
  25407. };
  25408. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25409. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25410. };
  25411. return Action;
  25412. })();
  25413. BABYLON.Action = Action;
  25414. })(BABYLON || (BABYLON = {}));
  25415. var BABYLON;
  25416. (function (BABYLON) {
  25417. /**
  25418. * ActionEvent is the event beint sent when an action is triggered.
  25419. */
  25420. var ActionEvent = (function () {
  25421. /**
  25422. * @constructor
  25423. * @param source The mesh or sprite that triggered the action.
  25424. * @param pointerX The X mouse cursor position at the time of the event
  25425. * @param pointerY The Y mouse cursor position at the time of the event
  25426. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25427. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25428. */
  25429. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  25430. this.source = source;
  25431. this.pointerX = pointerX;
  25432. this.pointerY = pointerY;
  25433. this.meshUnderPointer = meshUnderPointer;
  25434. this.sourceEvent = sourceEvent;
  25435. this.additionalData = additionalData;
  25436. }
  25437. /**
  25438. * Helper function to auto-create an ActionEvent from a source mesh.
  25439. * @param source The source mesh that triggered the event
  25440. * @param evt {Event} The original (browser) event
  25441. */
  25442. ActionEvent.CreateNew = function (source, evt, additionalData) {
  25443. var scene = source.getScene();
  25444. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25445. };
  25446. /**
  25447. * Helper function to auto-create an ActionEvent from a source mesh.
  25448. * @param source The source sprite that triggered the event
  25449. * @param scene Scene associated with the sprite
  25450. * @param evt {Event} The original (browser) event
  25451. */
  25452. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  25453. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  25454. };
  25455. /**
  25456. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25457. * @param scene the scene where the event occurred
  25458. * @param evt {Event} The original (browser) event
  25459. */
  25460. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25461. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25462. };
  25463. return ActionEvent;
  25464. })();
  25465. BABYLON.ActionEvent = ActionEvent;
  25466. /**
  25467. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25468. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25469. */
  25470. var ActionManager = (function () {
  25471. function ActionManager(scene) {
  25472. // Members
  25473. this.actions = new Array();
  25474. this._scene = scene;
  25475. scene._actionManagers.push(this);
  25476. }
  25477. Object.defineProperty(ActionManager, "NothingTrigger", {
  25478. get: function () {
  25479. return ActionManager._NothingTrigger;
  25480. },
  25481. enumerable: true,
  25482. configurable: true
  25483. });
  25484. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25485. get: function () {
  25486. return ActionManager._OnPickTrigger;
  25487. },
  25488. enumerable: true,
  25489. configurable: true
  25490. });
  25491. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25492. get: function () {
  25493. return ActionManager._OnLeftPickTrigger;
  25494. },
  25495. enumerable: true,
  25496. configurable: true
  25497. });
  25498. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25499. get: function () {
  25500. return ActionManager._OnRightPickTrigger;
  25501. },
  25502. enumerable: true,
  25503. configurable: true
  25504. });
  25505. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  25506. get: function () {
  25507. return ActionManager._OnCenterPickTrigger;
  25508. },
  25509. enumerable: true,
  25510. configurable: true
  25511. });
  25512. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  25513. get: function () {
  25514. return ActionManager._OnPointerOverTrigger;
  25515. },
  25516. enumerable: true,
  25517. configurable: true
  25518. });
  25519. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  25520. get: function () {
  25521. return ActionManager._OnPointerOutTrigger;
  25522. },
  25523. enumerable: true,
  25524. configurable: true
  25525. });
  25526. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  25527. get: function () {
  25528. return ActionManager._OnEveryFrameTrigger;
  25529. },
  25530. enumerable: true,
  25531. configurable: true
  25532. });
  25533. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  25534. get: function () {
  25535. return ActionManager._OnIntersectionEnterTrigger;
  25536. },
  25537. enumerable: true,
  25538. configurable: true
  25539. });
  25540. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  25541. get: function () {
  25542. return ActionManager._OnIntersectionExitTrigger;
  25543. },
  25544. enumerable: true,
  25545. configurable: true
  25546. });
  25547. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  25548. get: function () {
  25549. return ActionManager._OnKeyDownTrigger;
  25550. },
  25551. enumerable: true,
  25552. configurable: true
  25553. });
  25554. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25555. get: function () {
  25556. return ActionManager._OnKeyUpTrigger;
  25557. },
  25558. enumerable: true,
  25559. configurable: true
  25560. });
  25561. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  25562. get: function () {
  25563. return ActionManager._OnPickUpTrigger;
  25564. },
  25565. enumerable: true,
  25566. configurable: true
  25567. });
  25568. // Methods
  25569. ActionManager.prototype.dispose = function () {
  25570. var index = this._scene._actionManagers.indexOf(this);
  25571. if (index > -1) {
  25572. this._scene._actionManagers.splice(index, 1);
  25573. }
  25574. };
  25575. ActionManager.prototype.getScene = function () {
  25576. return this._scene;
  25577. };
  25578. /**
  25579. * Does this action manager handles actions of any of the given triggers
  25580. * @param {number[]} triggers - the triggers to be tested
  25581. * @return {boolean} whether one (or more) of the triggers is handeled
  25582. */
  25583. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25584. for (var index = 0; index < this.actions.length; index++) {
  25585. var action = this.actions[index];
  25586. if (triggers.indexOf(action.trigger) > -1) {
  25587. return true;
  25588. }
  25589. }
  25590. return false;
  25591. };
  25592. /**
  25593. * Does this action manager handles actions of a given trigger
  25594. * @param {number} trigger - the trigger to be tested
  25595. * @return {boolean} whether the trigger is handeled
  25596. */
  25597. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  25598. for (var index = 0; index < this.actions.length; index++) {
  25599. var action = this.actions[index];
  25600. if (action.trigger === trigger) {
  25601. return true;
  25602. }
  25603. }
  25604. return false;
  25605. };
  25606. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25607. /**
  25608. * Does this action manager has pointer triggers
  25609. * @return {boolean} whether or not it has pointer triggers
  25610. */
  25611. get: function () {
  25612. for (var index = 0; index < this.actions.length; index++) {
  25613. var action = this.actions[index];
  25614. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25615. return true;
  25616. }
  25617. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25618. return true;
  25619. }
  25620. }
  25621. return false;
  25622. },
  25623. enumerable: true,
  25624. configurable: true
  25625. });
  25626. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25627. /**
  25628. * Does this action manager has pick triggers
  25629. * @return {boolean} whether or not it has pick triggers
  25630. */
  25631. get: function () {
  25632. for (var index = 0; index < this.actions.length; index++) {
  25633. var action = this.actions[index];
  25634. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25635. return true;
  25636. }
  25637. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25638. return true;
  25639. }
  25640. }
  25641. return false;
  25642. },
  25643. enumerable: true,
  25644. configurable: true
  25645. });
  25646. /**
  25647. * Registers an action to this action manager
  25648. * @param {BABYLON.Action} action - the action to be registered
  25649. * @return {BABYLON.Action} the action amended (prepared) after registration
  25650. */
  25651. ActionManager.prototype.registerAction = function (action) {
  25652. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25653. if (this.getScene().actionManager !== this) {
  25654. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25655. return null;
  25656. }
  25657. }
  25658. this.actions.push(action);
  25659. action._actionManager = this;
  25660. action._prepare();
  25661. return action;
  25662. };
  25663. /**
  25664. * Process a specific trigger
  25665. * @param {number} trigger - the trigger to process
  25666. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25667. */
  25668. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25669. for (var index = 0; index < this.actions.length; index++) {
  25670. var action = this.actions[index];
  25671. if (action.trigger === trigger) {
  25672. if (trigger === ActionManager.OnKeyUpTrigger
  25673. || trigger === ActionManager.OnKeyDownTrigger) {
  25674. var parameter = action.getTriggerParameter();
  25675. if (parameter) {
  25676. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25677. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25678. if (actualkey !== parameter.toLowerCase()) {
  25679. continue;
  25680. }
  25681. }
  25682. }
  25683. action._executeCurrent(evt);
  25684. }
  25685. }
  25686. };
  25687. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25688. var properties = propertyPath.split(".");
  25689. for (var index = 0; index < properties.length - 1; index++) {
  25690. target = target[properties[index]];
  25691. }
  25692. return target;
  25693. };
  25694. ActionManager.prototype._getProperty = function (propertyPath) {
  25695. var properties = propertyPath.split(".");
  25696. return properties[properties.length - 1];
  25697. };
  25698. // Statics
  25699. ActionManager._NothingTrigger = 0;
  25700. ActionManager._OnPickTrigger = 1;
  25701. ActionManager._OnLeftPickTrigger = 2;
  25702. ActionManager._OnRightPickTrigger = 3;
  25703. ActionManager._OnCenterPickTrigger = 4;
  25704. ActionManager._OnPointerOverTrigger = 5;
  25705. ActionManager._OnPointerOutTrigger = 6;
  25706. ActionManager._OnEveryFrameTrigger = 7;
  25707. ActionManager._OnIntersectionEnterTrigger = 8;
  25708. ActionManager._OnIntersectionExitTrigger = 9;
  25709. ActionManager._OnKeyDownTrigger = 10;
  25710. ActionManager._OnKeyUpTrigger = 11;
  25711. ActionManager._OnPickUpTrigger = 12;
  25712. return ActionManager;
  25713. })();
  25714. BABYLON.ActionManager = ActionManager;
  25715. })(BABYLON || (BABYLON = {}));
  25716. var BABYLON;
  25717. (function (BABYLON) {
  25718. var InterpolateValueAction = (function (_super) {
  25719. __extends(InterpolateValueAction, _super);
  25720. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25721. if (duration === void 0) { duration = 1000; }
  25722. _super.call(this, triggerOptions, condition);
  25723. this.propertyPath = propertyPath;
  25724. this.value = value;
  25725. this.duration = duration;
  25726. this.stopOtherAnimations = stopOtherAnimations;
  25727. this.onInterpolationDone = onInterpolationDone;
  25728. this._target = target;
  25729. }
  25730. InterpolateValueAction.prototype._prepare = function () {
  25731. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25732. this._property = this._getProperty(this.propertyPath);
  25733. };
  25734. InterpolateValueAction.prototype.execute = function () {
  25735. var scene = this._actionManager.getScene();
  25736. var keys = [
  25737. {
  25738. frame: 0,
  25739. value: this._target[this._property]
  25740. }, {
  25741. frame: 100,
  25742. value: this.value
  25743. }
  25744. ];
  25745. var dataType;
  25746. if (typeof this.value === "number") {
  25747. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25748. }
  25749. else if (this.value instanceof BABYLON.Color3) {
  25750. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25751. }
  25752. else if (this.value instanceof BABYLON.Vector3) {
  25753. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25754. }
  25755. else if (this.value instanceof BABYLON.Matrix) {
  25756. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25757. }
  25758. else if (this.value instanceof BABYLON.Quaternion) {
  25759. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25760. }
  25761. else {
  25762. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25763. return;
  25764. }
  25765. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25766. animation.setKeys(keys);
  25767. if (this.stopOtherAnimations) {
  25768. scene.stopAnimation(this._target);
  25769. }
  25770. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25771. };
  25772. return InterpolateValueAction;
  25773. })(BABYLON.Action);
  25774. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25775. })(BABYLON || (BABYLON = {}));
  25776. var BABYLON;
  25777. (function (BABYLON) {
  25778. var SwitchBooleanAction = (function (_super) {
  25779. __extends(SwitchBooleanAction, _super);
  25780. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25781. _super.call(this, triggerOptions, condition);
  25782. this.propertyPath = propertyPath;
  25783. this._target = target;
  25784. }
  25785. SwitchBooleanAction.prototype._prepare = function () {
  25786. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25787. this._property = this._getProperty(this.propertyPath);
  25788. };
  25789. SwitchBooleanAction.prototype.execute = function () {
  25790. this._target[this._property] = !this._target[this._property];
  25791. };
  25792. return SwitchBooleanAction;
  25793. })(BABYLON.Action);
  25794. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25795. var SetStateAction = (function (_super) {
  25796. __extends(SetStateAction, _super);
  25797. function SetStateAction(triggerOptions, target, value, condition) {
  25798. _super.call(this, triggerOptions, condition);
  25799. this.value = value;
  25800. this._target = target;
  25801. }
  25802. SetStateAction.prototype.execute = function () {
  25803. this._target.state = this.value;
  25804. };
  25805. return SetStateAction;
  25806. })(BABYLON.Action);
  25807. BABYLON.SetStateAction = SetStateAction;
  25808. var SetValueAction = (function (_super) {
  25809. __extends(SetValueAction, _super);
  25810. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25811. _super.call(this, triggerOptions, condition);
  25812. this.propertyPath = propertyPath;
  25813. this.value = value;
  25814. this._target = target;
  25815. }
  25816. SetValueAction.prototype._prepare = function () {
  25817. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25818. this._property = this._getProperty(this.propertyPath);
  25819. };
  25820. SetValueAction.prototype.execute = function () {
  25821. this._target[this._property] = this.value;
  25822. };
  25823. return SetValueAction;
  25824. })(BABYLON.Action);
  25825. BABYLON.SetValueAction = SetValueAction;
  25826. var IncrementValueAction = (function (_super) {
  25827. __extends(IncrementValueAction, _super);
  25828. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25829. _super.call(this, triggerOptions, condition);
  25830. this.propertyPath = propertyPath;
  25831. this.value = value;
  25832. this._target = target;
  25833. }
  25834. IncrementValueAction.prototype._prepare = function () {
  25835. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25836. this._property = this._getProperty(this.propertyPath);
  25837. if (typeof this._target[this._property] !== "number") {
  25838. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25839. }
  25840. };
  25841. IncrementValueAction.prototype.execute = function () {
  25842. this._target[this._property] += this.value;
  25843. };
  25844. return IncrementValueAction;
  25845. })(BABYLON.Action);
  25846. BABYLON.IncrementValueAction = IncrementValueAction;
  25847. var PlayAnimationAction = (function (_super) {
  25848. __extends(PlayAnimationAction, _super);
  25849. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25850. _super.call(this, triggerOptions, condition);
  25851. this.from = from;
  25852. this.to = to;
  25853. this.loop = loop;
  25854. this._target = target;
  25855. }
  25856. PlayAnimationAction.prototype._prepare = function () {
  25857. };
  25858. PlayAnimationAction.prototype.execute = function () {
  25859. var scene = this._actionManager.getScene();
  25860. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25861. };
  25862. return PlayAnimationAction;
  25863. })(BABYLON.Action);
  25864. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25865. var StopAnimationAction = (function (_super) {
  25866. __extends(StopAnimationAction, _super);
  25867. function StopAnimationAction(triggerOptions, target, condition) {
  25868. _super.call(this, triggerOptions, condition);
  25869. this._target = target;
  25870. }
  25871. StopAnimationAction.prototype._prepare = function () {
  25872. };
  25873. StopAnimationAction.prototype.execute = function () {
  25874. var scene = this._actionManager.getScene();
  25875. scene.stopAnimation(this._target);
  25876. };
  25877. return StopAnimationAction;
  25878. })(BABYLON.Action);
  25879. BABYLON.StopAnimationAction = StopAnimationAction;
  25880. var DoNothingAction = (function (_super) {
  25881. __extends(DoNothingAction, _super);
  25882. function DoNothingAction(triggerOptions, condition) {
  25883. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25884. _super.call(this, triggerOptions, condition);
  25885. }
  25886. DoNothingAction.prototype.execute = function () {
  25887. };
  25888. return DoNothingAction;
  25889. })(BABYLON.Action);
  25890. BABYLON.DoNothingAction = DoNothingAction;
  25891. var CombineAction = (function (_super) {
  25892. __extends(CombineAction, _super);
  25893. function CombineAction(triggerOptions, children, condition) {
  25894. _super.call(this, triggerOptions, condition);
  25895. this.children = children;
  25896. }
  25897. CombineAction.prototype._prepare = function () {
  25898. for (var index = 0; index < this.children.length; index++) {
  25899. this.children[index]._actionManager = this._actionManager;
  25900. this.children[index]._prepare();
  25901. }
  25902. };
  25903. CombineAction.prototype.execute = function (evt) {
  25904. for (var index = 0; index < this.children.length; index++) {
  25905. this.children[index].execute(evt);
  25906. }
  25907. };
  25908. return CombineAction;
  25909. })(BABYLON.Action);
  25910. BABYLON.CombineAction = CombineAction;
  25911. var ExecuteCodeAction = (function (_super) {
  25912. __extends(ExecuteCodeAction, _super);
  25913. function ExecuteCodeAction(triggerOptions, func, condition) {
  25914. _super.call(this, triggerOptions, condition);
  25915. this.func = func;
  25916. }
  25917. ExecuteCodeAction.prototype.execute = function (evt) {
  25918. this.func(evt);
  25919. };
  25920. return ExecuteCodeAction;
  25921. })(BABYLON.Action);
  25922. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25923. var SetParentAction = (function (_super) {
  25924. __extends(SetParentAction, _super);
  25925. function SetParentAction(triggerOptions, target, parent, condition) {
  25926. _super.call(this, triggerOptions, condition);
  25927. this._target = target;
  25928. this._parent = parent;
  25929. }
  25930. SetParentAction.prototype._prepare = function () {
  25931. };
  25932. SetParentAction.prototype.execute = function () {
  25933. if (this._target.parent === this._parent) {
  25934. return;
  25935. }
  25936. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25937. invertParentWorldMatrix.invert();
  25938. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25939. this._target.parent = this._parent;
  25940. };
  25941. return SetParentAction;
  25942. })(BABYLON.Action);
  25943. BABYLON.SetParentAction = SetParentAction;
  25944. var PlaySoundAction = (function (_super) {
  25945. __extends(PlaySoundAction, _super);
  25946. function PlaySoundAction(triggerOptions, sound, condition) {
  25947. _super.call(this, triggerOptions, condition);
  25948. this._sound = sound;
  25949. }
  25950. PlaySoundAction.prototype._prepare = function () {
  25951. };
  25952. PlaySoundAction.prototype.execute = function () {
  25953. if (this._sound !== undefined)
  25954. this._sound.play();
  25955. };
  25956. return PlaySoundAction;
  25957. })(BABYLON.Action);
  25958. BABYLON.PlaySoundAction = PlaySoundAction;
  25959. var StopSoundAction = (function (_super) {
  25960. __extends(StopSoundAction, _super);
  25961. function StopSoundAction(triggerOptions, sound, condition) {
  25962. _super.call(this, triggerOptions, condition);
  25963. this._sound = sound;
  25964. }
  25965. StopSoundAction.prototype._prepare = function () {
  25966. };
  25967. StopSoundAction.prototype.execute = function () {
  25968. if (this._sound !== undefined)
  25969. this._sound.stop();
  25970. };
  25971. return StopSoundAction;
  25972. })(BABYLON.Action);
  25973. BABYLON.StopSoundAction = StopSoundAction;
  25974. })(BABYLON || (BABYLON = {}));
  25975. var BABYLON;
  25976. (function (BABYLON) {
  25977. var Geometry = (function () {
  25978. function Geometry(id, scene, vertexData, updatable, mesh) {
  25979. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25980. this._totalVertices = 0;
  25981. this._isDisposed = false;
  25982. this.id = id;
  25983. this._engine = scene.getEngine();
  25984. this._meshes = [];
  25985. this._scene = scene;
  25986. //Init vertex buffer cache
  25987. this._vertexBuffers = {};
  25988. this._indices = [];
  25989. // vertexData
  25990. if (vertexData) {
  25991. this.setAllVerticesData(vertexData, updatable);
  25992. }
  25993. else {
  25994. this._totalVertices = 0;
  25995. this._indices = [];
  25996. }
  25997. // applyToMesh
  25998. if (mesh) {
  25999. this.applyToMesh(mesh);
  26000. mesh.computeWorldMatrix(true);
  26001. }
  26002. }
  26003. Object.defineProperty(Geometry.prototype, "extend", {
  26004. get: function () {
  26005. return this._extend;
  26006. },
  26007. enumerable: true,
  26008. configurable: true
  26009. });
  26010. Geometry.prototype.getScene = function () {
  26011. return this._scene;
  26012. };
  26013. Geometry.prototype.getEngine = function () {
  26014. return this._engine;
  26015. };
  26016. Geometry.prototype.isReady = function () {
  26017. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26018. };
  26019. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26020. vertexData.applyToGeometry(this, updatable);
  26021. this.notifyUpdate();
  26022. };
  26023. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26024. if (this._vertexBuffers[kind]) {
  26025. this._vertexBuffers[kind].dispose();
  26026. }
  26027. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26028. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26029. stride = this._vertexBuffers[kind].getStrideSize();
  26030. this._totalVertices = data.length / stride;
  26031. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26032. var meshes = this._meshes;
  26033. var numOfMeshes = meshes.length;
  26034. for (var index = 0; index < numOfMeshes; index++) {
  26035. var mesh = meshes[index];
  26036. mesh._resetPointsArrayCache();
  26037. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26038. mesh._createGlobalSubMesh();
  26039. mesh.computeWorldMatrix(true);
  26040. }
  26041. }
  26042. this.notifyUpdate(kind);
  26043. };
  26044. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26045. var vertexBuffer = this.getVertexBuffer(kind);
  26046. if (!vertexBuffer) {
  26047. return;
  26048. }
  26049. vertexBuffer.updateDirectly(data, offset);
  26050. this.notifyUpdate(kind);
  26051. };
  26052. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26053. var vertexBuffer = this.getVertexBuffer(kind);
  26054. if (!vertexBuffer) {
  26055. return;
  26056. }
  26057. vertexBuffer.update(data);
  26058. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26059. var stride = vertexBuffer.getStrideSize();
  26060. this._totalVertices = data.length / stride;
  26061. if (updateExtends) {
  26062. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26063. }
  26064. var meshes = this._meshes;
  26065. var numOfMeshes = meshes.length;
  26066. for (var index = 0; index < numOfMeshes; index++) {
  26067. var mesh = meshes[index];
  26068. mesh._resetPointsArrayCache();
  26069. if (updateExtends) {
  26070. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26071. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26072. var subMesh = mesh.subMeshes[subIndex];
  26073. subMesh.refreshBoundingInfo();
  26074. }
  26075. }
  26076. }
  26077. }
  26078. this.notifyUpdate(kind);
  26079. };
  26080. Geometry.prototype.getTotalVertices = function () {
  26081. if (!this.isReady()) {
  26082. return 0;
  26083. }
  26084. return this._totalVertices;
  26085. };
  26086. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26087. var vertexBuffer = this.getVertexBuffer(kind);
  26088. if (!vertexBuffer) {
  26089. return null;
  26090. }
  26091. var orig = vertexBuffer.getData();
  26092. if (!copyWhenShared || this._meshes.length === 1) {
  26093. return orig;
  26094. }
  26095. else {
  26096. var len = orig.length;
  26097. var copy = [];
  26098. for (var i = 0; i < len; i++) {
  26099. copy.push(orig[i]);
  26100. }
  26101. return copy;
  26102. }
  26103. };
  26104. Geometry.prototype.getVertexBuffer = function (kind) {
  26105. if (!this.isReady()) {
  26106. return null;
  26107. }
  26108. return this._vertexBuffers[kind];
  26109. };
  26110. Geometry.prototype.getVertexBuffers = function () {
  26111. if (!this.isReady()) {
  26112. return null;
  26113. }
  26114. return this._vertexBuffers;
  26115. };
  26116. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26117. if (!this._vertexBuffers) {
  26118. if (this._delayInfo) {
  26119. return this._delayInfo.indexOf(kind) !== -1;
  26120. }
  26121. return false;
  26122. }
  26123. return this._vertexBuffers[kind] !== undefined;
  26124. };
  26125. Geometry.prototype.getVerticesDataKinds = function () {
  26126. var result = [];
  26127. var kind;
  26128. if (!this._vertexBuffers && this._delayInfo) {
  26129. for (kind in this._delayInfo) {
  26130. result.push(kind);
  26131. }
  26132. }
  26133. else {
  26134. for (kind in this._vertexBuffers) {
  26135. result.push(kind);
  26136. }
  26137. }
  26138. return result;
  26139. };
  26140. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26141. if (this._indexBuffer) {
  26142. this._engine._releaseBuffer(this._indexBuffer);
  26143. }
  26144. this._indices = indices;
  26145. if (this._meshes.length !== 0 && this._indices) {
  26146. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26147. }
  26148. if (totalVertices !== undefined) {
  26149. this._totalVertices = totalVertices;
  26150. }
  26151. var meshes = this._meshes;
  26152. var numOfMeshes = meshes.length;
  26153. for (var index = 0; index < numOfMeshes; index++) {
  26154. meshes[index]._createGlobalSubMesh();
  26155. }
  26156. this.notifyUpdate();
  26157. };
  26158. Geometry.prototype.getTotalIndices = function () {
  26159. if (!this.isReady()) {
  26160. return 0;
  26161. }
  26162. return this._indices.length;
  26163. };
  26164. Geometry.prototype.getIndices = function (copyWhenShared) {
  26165. if (!this.isReady()) {
  26166. return null;
  26167. }
  26168. var orig = this._indices;
  26169. if (!copyWhenShared || this._meshes.length === 1) {
  26170. return orig;
  26171. }
  26172. else {
  26173. var len = orig.length;
  26174. var copy = [];
  26175. for (var i = 0; i < len; i++) {
  26176. copy.push(orig[i]);
  26177. }
  26178. return copy;
  26179. }
  26180. };
  26181. Geometry.prototype.getIndexBuffer = function () {
  26182. if (!this.isReady()) {
  26183. return null;
  26184. }
  26185. return this._indexBuffer;
  26186. };
  26187. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26188. var meshes = this._meshes;
  26189. var index = meshes.indexOf(mesh);
  26190. if (index === -1) {
  26191. return;
  26192. }
  26193. for (var kind in this._vertexBuffers) {
  26194. this._vertexBuffers[kind].dispose();
  26195. }
  26196. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26197. this._indexBuffer = null;
  26198. }
  26199. meshes.splice(index, 1);
  26200. mesh._geometry = null;
  26201. if (meshes.length === 0 && shouldDispose) {
  26202. this.dispose();
  26203. }
  26204. };
  26205. Geometry.prototype.applyToMesh = function (mesh) {
  26206. if (mesh._geometry === this) {
  26207. return;
  26208. }
  26209. var previousGeometry = mesh._geometry;
  26210. if (previousGeometry) {
  26211. previousGeometry.releaseForMesh(mesh);
  26212. }
  26213. var meshes = this._meshes;
  26214. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26215. mesh._geometry = this;
  26216. this._scene.pushGeometry(this);
  26217. meshes.push(mesh);
  26218. if (this.isReady()) {
  26219. this._applyToMesh(mesh);
  26220. }
  26221. else {
  26222. mesh._boundingInfo = this._boundingInfo;
  26223. }
  26224. };
  26225. Geometry.prototype._applyToMesh = function (mesh) {
  26226. var numOfMeshes = this._meshes.length;
  26227. // vertexBuffers
  26228. for (var kind in this._vertexBuffers) {
  26229. if (numOfMeshes === 1) {
  26230. this._vertexBuffers[kind].create();
  26231. }
  26232. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26233. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26234. mesh._resetPointsArrayCache();
  26235. if (!this._extend) {
  26236. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26237. }
  26238. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26239. mesh._createGlobalSubMesh();
  26240. //bounding info was just created again, world matrix should be applied again.
  26241. mesh._updateBoundingInfo();
  26242. }
  26243. }
  26244. // indexBuffer
  26245. if (numOfMeshes === 1 && this._indices) {
  26246. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26247. }
  26248. if (this._indexBuffer) {
  26249. this._indexBuffer.references = numOfMeshes;
  26250. }
  26251. };
  26252. Geometry.prototype.notifyUpdate = function (kind) {
  26253. if (this.onGeometryUpdated) {
  26254. this.onGeometryUpdated(this, kind);
  26255. }
  26256. };
  26257. Geometry.prototype.load = function (scene, onLoaded) {
  26258. var _this = this;
  26259. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26260. return;
  26261. }
  26262. if (this.isReady()) {
  26263. if (onLoaded) {
  26264. onLoaded();
  26265. }
  26266. return;
  26267. }
  26268. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26269. scene._addPendingData(this);
  26270. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26271. _this._delayLoadingFunction(JSON.parse(data), _this);
  26272. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26273. _this._delayInfo = [];
  26274. scene._removePendingData(_this);
  26275. var meshes = _this._meshes;
  26276. var numOfMeshes = meshes.length;
  26277. for (var index = 0; index < numOfMeshes; index++) {
  26278. _this._applyToMesh(meshes[index]);
  26279. }
  26280. if (onLoaded) {
  26281. onLoaded();
  26282. }
  26283. }, function () { }, scene.database);
  26284. };
  26285. Geometry.prototype.isDisposed = function () {
  26286. return this._isDisposed;
  26287. };
  26288. Geometry.prototype.dispose = function () {
  26289. var meshes = this._meshes;
  26290. var numOfMeshes = meshes.length;
  26291. var index;
  26292. for (index = 0; index < numOfMeshes; index++) {
  26293. this.releaseForMesh(meshes[index]);
  26294. }
  26295. this._meshes = [];
  26296. for (var kind in this._vertexBuffers) {
  26297. this._vertexBuffers[kind].dispose();
  26298. }
  26299. this._vertexBuffers = [];
  26300. this._totalVertices = 0;
  26301. if (this._indexBuffer) {
  26302. this._engine._releaseBuffer(this._indexBuffer);
  26303. }
  26304. this._indexBuffer = null;
  26305. this._indices = [];
  26306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26307. this.delayLoadingFile = null;
  26308. this._delayLoadingFunction = null;
  26309. this._delayInfo = [];
  26310. this._boundingInfo = null;
  26311. this._scene.removeGeometry(this);
  26312. this._isDisposed = true;
  26313. };
  26314. Geometry.prototype.copy = function (id) {
  26315. var vertexData = new BABYLON.VertexData();
  26316. vertexData.indices = [];
  26317. var indices = this.getIndices();
  26318. for (var index = 0; index < indices.length; index++) {
  26319. vertexData.indices.push(indices[index]);
  26320. }
  26321. var updatable = false;
  26322. var stopChecking = false;
  26323. var kind;
  26324. for (kind in this._vertexBuffers) {
  26325. // using slice() to make a copy of the array and not just reference it
  26326. var data = this.getVerticesData(kind);
  26327. if (data instanceof Float32Array) {
  26328. vertexData.set(new Float32Array(data), kind);
  26329. }
  26330. else {
  26331. vertexData.set(data.slice(0), kind);
  26332. }
  26333. if (!stopChecking) {
  26334. updatable = this.getVertexBuffer(kind).isUpdatable();
  26335. stopChecking = !updatable;
  26336. }
  26337. }
  26338. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26339. geometry.delayLoadState = this.delayLoadState;
  26340. geometry.delayLoadingFile = this.delayLoadingFile;
  26341. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26342. for (kind in this._delayInfo) {
  26343. geometry._delayInfo = geometry._delayInfo || [];
  26344. geometry._delayInfo.push(kind);
  26345. }
  26346. // Bounding info
  26347. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26348. return geometry;
  26349. };
  26350. // Statics
  26351. Geometry.ExtractFromMesh = function (mesh, id) {
  26352. var geometry = mesh._geometry;
  26353. if (!geometry) {
  26354. return null;
  26355. }
  26356. return geometry.copy(id);
  26357. };
  26358. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26359. // be aware Math.random() could cause collisions
  26360. Geometry.RandomId = function () {
  26361. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26362. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26363. return v.toString(16);
  26364. });
  26365. };
  26366. return Geometry;
  26367. })();
  26368. BABYLON.Geometry = Geometry;
  26369. /////// Primitives //////////////////////////////////////////////
  26370. var Geometry;
  26371. (function (Geometry) {
  26372. var Primitives;
  26373. (function (Primitives) {
  26374. /// Abstract class
  26375. var _Primitive = (function (_super) {
  26376. __extends(_Primitive, _super);
  26377. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26378. this._beingRegenerated = true;
  26379. this._canBeRegenerated = canBeRegenerated;
  26380. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26381. this._beingRegenerated = false;
  26382. }
  26383. _Primitive.prototype.canBeRegenerated = function () {
  26384. return this._canBeRegenerated;
  26385. };
  26386. _Primitive.prototype.regenerate = function () {
  26387. if (!this._canBeRegenerated) {
  26388. return;
  26389. }
  26390. this._beingRegenerated = true;
  26391. this.setAllVerticesData(this._regenerateVertexData(), false);
  26392. this._beingRegenerated = false;
  26393. };
  26394. _Primitive.prototype.asNewGeometry = function (id) {
  26395. return _super.prototype.copy.call(this, id);
  26396. };
  26397. // overrides
  26398. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26399. if (!this._beingRegenerated) {
  26400. return;
  26401. }
  26402. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26403. };
  26404. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26405. if (!this._beingRegenerated) {
  26406. return;
  26407. }
  26408. _super.prototype.setVerticesData.call(this, kind, data, false);
  26409. };
  26410. // to override
  26411. // protected
  26412. _Primitive.prototype._regenerateVertexData = function () {
  26413. throw new Error("Abstract method");
  26414. };
  26415. _Primitive.prototype.copy = function (id) {
  26416. throw new Error("Must be overriden in sub-classes.");
  26417. };
  26418. return _Primitive;
  26419. })(Geometry);
  26420. Primitives._Primitive = _Primitive;
  26421. var Ribbon = (function (_super) {
  26422. __extends(Ribbon, _super);
  26423. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26424. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26425. this.pathArray = pathArray;
  26426. this.closeArray = closeArray;
  26427. this.closePath = closePath;
  26428. this.offset = offset;
  26429. this.side = side;
  26430. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26431. }
  26432. Ribbon.prototype._regenerateVertexData = function () {
  26433. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26434. };
  26435. Ribbon.prototype.copy = function (id) {
  26436. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26437. };
  26438. return Ribbon;
  26439. })(_Primitive);
  26440. Primitives.Ribbon = Ribbon;
  26441. var Box = (function (_super) {
  26442. __extends(Box, _super);
  26443. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26444. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26445. this.size = size;
  26446. this.side = side;
  26447. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26448. }
  26449. Box.prototype._regenerateVertexData = function () {
  26450. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26451. };
  26452. Box.prototype.copy = function (id) {
  26453. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26454. };
  26455. return Box;
  26456. })(_Primitive);
  26457. Primitives.Box = Box;
  26458. var Sphere = (function (_super) {
  26459. __extends(Sphere, _super);
  26460. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26461. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26462. this.segments = segments;
  26463. this.diameter = diameter;
  26464. this.side = side;
  26465. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26466. }
  26467. Sphere.prototype._regenerateVertexData = function () {
  26468. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26469. };
  26470. Sphere.prototype.copy = function (id) {
  26471. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26472. };
  26473. return Sphere;
  26474. })(_Primitive);
  26475. Primitives.Sphere = Sphere;
  26476. var Disc = (function (_super) {
  26477. __extends(Disc, _super);
  26478. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26479. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26480. this.radius = radius;
  26481. this.tessellation = tessellation;
  26482. this.side = side;
  26483. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26484. }
  26485. Disc.prototype._regenerateVertexData = function () {
  26486. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26487. };
  26488. Disc.prototype.copy = function (id) {
  26489. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26490. };
  26491. return Disc;
  26492. })(_Primitive);
  26493. Primitives.Disc = Disc;
  26494. var Cylinder = (function (_super) {
  26495. __extends(Cylinder, _super);
  26496. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26497. if (subdivisions === void 0) { subdivisions = 1; }
  26498. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26499. this.height = height;
  26500. this.diameterTop = diameterTop;
  26501. this.diameterBottom = diameterBottom;
  26502. this.tessellation = tessellation;
  26503. this.subdivisions = subdivisions;
  26504. this.side = side;
  26505. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26506. }
  26507. Cylinder.prototype._regenerateVertexData = function () {
  26508. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26509. };
  26510. Cylinder.prototype.copy = function (id) {
  26511. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26512. };
  26513. return Cylinder;
  26514. })(_Primitive);
  26515. Primitives.Cylinder = Cylinder;
  26516. var Torus = (function (_super) {
  26517. __extends(Torus, _super);
  26518. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26519. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26520. this.diameter = diameter;
  26521. this.thickness = thickness;
  26522. this.tessellation = tessellation;
  26523. this.side = side;
  26524. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26525. }
  26526. Torus.prototype._regenerateVertexData = function () {
  26527. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26528. };
  26529. Torus.prototype.copy = function (id) {
  26530. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26531. };
  26532. return Torus;
  26533. })(_Primitive);
  26534. Primitives.Torus = Torus;
  26535. var Ground = (function (_super) {
  26536. __extends(Ground, _super);
  26537. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26538. this.width = width;
  26539. this.height = height;
  26540. this.subdivisions = subdivisions;
  26541. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26542. }
  26543. Ground.prototype._regenerateVertexData = function () {
  26544. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26545. };
  26546. Ground.prototype.copy = function (id) {
  26547. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26548. };
  26549. return Ground;
  26550. })(_Primitive);
  26551. Primitives.Ground = Ground;
  26552. var TiledGround = (function (_super) {
  26553. __extends(TiledGround, _super);
  26554. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26555. this.xmin = xmin;
  26556. this.zmin = zmin;
  26557. this.xmax = xmax;
  26558. this.zmax = zmax;
  26559. this.subdivisions = subdivisions;
  26560. this.precision = precision;
  26561. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26562. }
  26563. TiledGround.prototype._regenerateVertexData = function () {
  26564. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26565. };
  26566. TiledGround.prototype.copy = function (id) {
  26567. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26568. };
  26569. return TiledGround;
  26570. })(_Primitive);
  26571. Primitives.TiledGround = TiledGround;
  26572. var Plane = (function (_super) {
  26573. __extends(Plane, _super);
  26574. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26575. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26576. this.size = size;
  26577. this.side = side;
  26578. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26579. }
  26580. Plane.prototype._regenerateVertexData = function () {
  26581. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26582. };
  26583. Plane.prototype.copy = function (id) {
  26584. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26585. };
  26586. return Plane;
  26587. })(_Primitive);
  26588. Primitives.Plane = Plane;
  26589. var TorusKnot = (function (_super) {
  26590. __extends(TorusKnot, _super);
  26591. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26592. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26593. this.radius = radius;
  26594. this.tube = tube;
  26595. this.radialSegments = radialSegments;
  26596. this.tubularSegments = tubularSegments;
  26597. this.p = p;
  26598. this.q = q;
  26599. this.side = side;
  26600. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26601. }
  26602. TorusKnot.prototype._regenerateVertexData = function () {
  26603. 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 });
  26604. };
  26605. TorusKnot.prototype.copy = function (id) {
  26606. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26607. };
  26608. return TorusKnot;
  26609. })(_Primitive);
  26610. Primitives.TorusKnot = TorusKnot;
  26611. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26612. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26613. })(BABYLON || (BABYLON = {}));
  26614. var BABYLON;
  26615. (function (BABYLON) {
  26616. var GroundMesh = (function (_super) {
  26617. __extends(GroundMesh, _super);
  26618. function GroundMesh(name, scene) {
  26619. _super.call(this, name, scene);
  26620. this.generateOctree = false;
  26621. this._worldInverse = new BABYLON.Matrix();
  26622. }
  26623. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26624. get: function () {
  26625. return this._subdivisions;
  26626. },
  26627. enumerable: true,
  26628. configurable: true
  26629. });
  26630. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26631. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26632. this._subdivisions = chunksCount;
  26633. this.subdivide(this._subdivisions);
  26634. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26635. };
  26636. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26637. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26638. this.getWorldMatrix().invertToRef(this._worldInverse);
  26639. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26640. var pickInfo = this.intersects(ray);
  26641. if (pickInfo.hit) {
  26642. return pickInfo.pickedPoint.y;
  26643. }
  26644. return 0;
  26645. };
  26646. return GroundMesh;
  26647. })(BABYLON.Mesh);
  26648. BABYLON.GroundMesh = GroundMesh;
  26649. })(BABYLON || (BABYLON = {}));
  26650. var BABYLON;
  26651. (function (BABYLON) {
  26652. var LinesMesh = (function (_super) {
  26653. __extends(LinesMesh, _super);
  26654. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26655. if (parent === void 0) { parent = null; }
  26656. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26657. this.color = new BABYLON.Color3(1, 1, 1);
  26658. this.alpha = 1;
  26659. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26660. attributes: ["position"],
  26661. uniforms: ["worldViewProjection", "color"],
  26662. needAlphaBlending: true
  26663. });
  26664. }
  26665. Object.defineProperty(LinesMesh.prototype, "material", {
  26666. get: function () {
  26667. return this._colorShader;
  26668. },
  26669. enumerable: true,
  26670. configurable: true
  26671. });
  26672. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26673. get: function () {
  26674. return false;
  26675. },
  26676. enumerable: true,
  26677. configurable: true
  26678. });
  26679. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26680. get: function () {
  26681. return false;
  26682. },
  26683. enumerable: true,
  26684. configurable: true
  26685. });
  26686. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26687. var engine = this.getScene().getEngine();
  26688. var indexToBind = this._geometry.getIndexBuffer();
  26689. // VBOs
  26690. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26691. // Color
  26692. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26693. };
  26694. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26695. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26696. return;
  26697. }
  26698. var engine = this.getScene().getEngine();
  26699. // Draw order
  26700. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26701. };
  26702. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26703. return null;
  26704. };
  26705. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26706. this._colorShader.dispose();
  26707. _super.prototype.dispose.call(this, doNotRecurse);
  26708. };
  26709. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26710. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26711. };
  26712. return LinesMesh;
  26713. })(BABYLON.Mesh);
  26714. BABYLON.LinesMesh = LinesMesh;
  26715. })(BABYLON || (BABYLON = {}));
  26716. var BABYLON;
  26717. (function (BABYLON) {
  26718. var DebugLayer = (function () {
  26719. function DebugLayer(scene) {
  26720. var _this = this;
  26721. this._transformationMatrix = BABYLON.Matrix.Identity();
  26722. this._enabled = false;
  26723. this._labelsEnabled = false;
  26724. this._displayStatistics = true;
  26725. this._displayTree = false;
  26726. this._displayLogs = false;
  26727. this._identityMatrix = BABYLON.Matrix.Identity();
  26728. this.axisRatio = 0.02;
  26729. this.accentColor = "orange";
  26730. this._scene = scene;
  26731. this._syncPositions = function () {
  26732. var engine = _this._scene.getEngine();
  26733. var canvasRect = engine.getRenderingCanvasClientRect();
  26734. if (_this._showUI) {
  26735. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26736. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26737. _this._statsDiv.style.width = "400px";
  26738. _this._statsDiv.style.height = "auto";
  26739. _this._statsSubsetDiv.style.maxHeight = "240px";
  26740. _this._optionsDiv.style.left = "0px";
  26741. _this._optionsDiv.style.top = "10px";
  26742. _this._optionsDiv.style.width = "200px";
  26743. _this._optionsDiv.style.height = "auto";
  26744. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26745. _this._logDiv.style.left = "0px";
  26746. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26747. _this._logDiv.style.width = "600px";
  26748. _this._logDiv.style.height = "160px";
  26749. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26750. _this._treeDiv.style.top = "10px";
  26751. _this._treeDiv.style.width = "300px";
  26752. _this._treeDiv.style.height = "auto";
  26753. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26754. }
  26755. _this._globalDiv.style.left = canvasRect.left + "px";
  26756. _this._globalDiv.style.top = canvasRect.top + "px";
  26757. _this._drawingCanvas.style.left = "0px";
  26758. _this._drawingCanvas.style.top = "0px";
  26759. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26760. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26761. var devicePixelRatio = window.devicePixelRatio || 1;
  26762. var context = _this._drawingContext;
  26763. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26764. context.mozBackingStorePixelRatio ||
  26765. context.msBackingStorePixelRatio ||
  26766. context.oBackingStorePixelRatio ||
  26767. context.backingStorePixelRatio || 1;
  26768. _this._ratio = devicePixelRatio / backingStoreRatio;
  26769. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26770. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26771. };
  26772. this._onCanvasClick = function (evt) {
  26773. _this._clickPosition = {
  26774. x: evt.clientX * _this._ratio,
  26775. y: evt.clientY * _this._ratio
  26776. };
  26777. };
  26778. this._syncUI = function () {
  26779. if (_this._showUI) {
  26780. if (_this._displayStatistics) {
  26781. _this._displayStats();
  26782. _this._statsDiv.style.display = "";
  26783. }
  26784. else {
  26785. _this._statsDiv.style.display = "none";
  26786. }
  26787. if (_this._displayLogs) {
  26788. _this._logDiv.style.display = "";
  26789. }
  26790. else {
  26791. _this._logDiv.style.display = "none";
  26792. }
  26793. if (_this._displayTree) {
  26794. _this._treeDiv.style.display = "";
  26795. if (_this._needToRefreshMeshesTree) {
  26796. _this._needToRefreshMeshesTree = false;
  26797. _this._refreshMeshesTreeContent();
  26798. }
  26799. }
  26800. else {
  26801. _this._treeDiv.style.display = "none";
  26802. }
  26803. }
  26804. };
  26805. this._syncData = function () {
  26806. if (_this._labelsEnabled || !_this._showUI) {
  26807. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26808. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26809. var engine = _this._scene.getEngine();
  26810. var viewport = _this._camera.viewport;
  26811. var globalViewport = viewport.toGlobal(engine);
  26812. // Meshes
  26813. var meshes = _this._camera.getActiveMeshes();
  26814. for (var index = 0; index < meshes.length; index++) {
  26815. var mesh = meshes.data[index];
  26816. var position = mesh.getBoundingInfo().boundingSphere.center;
  26817. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26818. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26819. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26820. }
  26821. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26822. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26823. }
  26824. }
  26825. // Cameras
  26826. var cameras = _this._scene.cameras;
  26827. for (index = 0; index < cameras.length; index++) {
  26828. var camera = cameras[index];
  26829. if (camera === _this._camera) {
  26830. continue;
  26831. }
  26832. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26833. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26834. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26835. _this._camera.detachControl(engine.getRenderingCanvas());
  26836. _this._camera = camera;
  26837. _this._camera.attachControl(engine.getRenderingCanvas());
  26838. }, function () { return "purple"; });
  26839. }
  26840. }
  26841. // Lights
  26842. var lights = _this._scene.lights;
  26843. for (index = 0; index < lights.length; index++) {
  26844. var light = lights[index];
  26845. if (light.position) {
  26846. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26847. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26848. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26849. light.setEnabled(!light.isEnabled());
  26850. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26851. }
  26852. }
  26853. }
  26854. }
  26855. _this._clickPosition = undefined;
  26856. };
  26857. }
  26858. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26859. while (this._treeSubsetDiv.hasChildNodes()) {
  26860. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26861. }
  26862. // Add meshes
  26863. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26864. sortedArray.sort(function (a, b) {
  26865. if (a.name === b.name) {
  26866. return 0;
  26867. }
  26868. return (a.name > b.name) ? 1 : -1;
  26869. });
  26870. for (var index = 0; index < sortedArray.length; index++) {
  26871. var mesh = sortedArray[index];
  26872. if (!mesh.isEnabled()) {
  26873. continue;
  26874. }
  26875. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26876. m.isVisible = element.checked;
  26877. }, mesh);
  26878. }
  26879. };
  26880. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26881. this._drawingContext.beginPath();
  26882. this._drawingContext.moveTo(zero.x, zero.y);
  26883. this._drawingContext.lineTo(unit.x, unit.y);
  26884. this._drawingContext.strokeStyle = color;
  26885. this._drawingContext.lineWidth = 4;
  26886. this._drawingContext.stroke();
  26887. this._drawingContext.font = "normal 14px Segoe UI";
  26888. this._drawingContext.fillStyle = color;
  26889. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26890. };
  26891. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26892. var position = mesh.getBoundingInfo().boundingSphere.center;
  26893. var worldMatrix = mesh.getWorldMatrix();
  26894. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26895. var unit = (unprojectedVector.subtract(position)).length();
  26896. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26897. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26898. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26899. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26900. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26901. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26902. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26903. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26904. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26905. };
  26906. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26907. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26908. this._drawingContext.font = "normal 12px Segoe UI";
  26909. var textMetrics = this._drawingContext.measureText(text);
  26910. var centerX = projectedPosition.x - textMetrics.width / 2;
  26911. var centerY = projectedPosition.y;
  26912. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26913. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26914. onClick();
  26915. }
  26916. this._drawingContext.beginPath();
  26917. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26918. this._drawingContext.fillStyle = getFillStyle();
  26919. this._drawingContext.globalAlpha = 0.5;
  26920. this._drawingContext.fill();
  26921. this._drawingContext.globalAlpha = 1.0;
  26922. this._drawingContext.strokeStyle = '#FFFFFF';
  26923. this._drawingContext.lineWidth = 1;
  26924. this._drawingContext.stroke();
  26925. this._drawingContext.fillStyle = "#FFFFFF";
  26926. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26927. this._drawingContext.beginPath();
  26928. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26929. this._drawingContext.fill();
  26930. }
  26931. };
  26932. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26933. if (!this._clickPosition) {
  26934. return false;
  26935. }
  26936. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26937. return false;
  26938. }
  26939. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26940. return false;
  26941. }
  26942. return true;
  26943. };
  26944. DebugLayer.prototype.isVisible = function () {
  26945. return this._enabled;
  26946. };
  26947. DebugLayer.prototype.hide = function () {
  26948. if (!this._enabled) {
  26949. return;
  26950. }
  26951. this._enabled = false;
  26952. var engine = this._scene.getEngine();
  26953. this._scene.unregisterBeforeRender(this._syncData);
  26954. this._scene.unregisterAfterRender(this._syncUI);
  26955. this._rootElement.removeChild(this._globalDiv);
  26956. this._scene.forceShowBoundingBoxes = false;
  26957. this._scene.forceWireframe = false;
  26958. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26959. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26960. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26961. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26962. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26963. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26964. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26965. BABYLON.StandardMaterial.LightmapEnabled = true;
  26966. this._scene.shadowsEnabled = true;
  26967. this._scene.particlesEnabled = true;
  26968. this._scene.postProcessesEnabled = true;
  26969. this._scene.collisionsEnabled = true;
  26970. this._scene.lightsEnabled = true;
  26971. this._scene.texturesEnabled = true;
  26972. this._scene.lensFlaresEnabled = true;
  26973. this._scene.proceduralTexturesEnabled = true;
  26974. this._scene.renderTargetsEnabled = true;
  26975. this._scene.probesEnabled = true;
  26976. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26977. };
  26978. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26979. if (showUI === void 0) { showUI = true; }
  26980. if (camera === void 0) { camera = null; }
  26981. if (rootElement === void 0) { rootElement = null; }
  26982. if (this._enabled) {
  26983. return;
  26984. }
  26985. this._enabled = true;
  26986. if (camera) {
  26987. this._camera = camera;
  26988. }
  26989. else {
  26990. this._camera = this._scene.activeCamera;
  26991. }
  26992. this._showUI = showUI;
  26993. var engine = this._scene.getEngine();
  26994. this._globalDiv = document.createElement("div");
  26995. this._rootElement = rootElement || document.body;
  26996. this._rootElement.appendChild(this._globalDiv);
  26997. this._generateDOMelements();
  26998. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26999. this._syncPositions();
  27000. this._scene.registerBeforeRender(this._syncData);
  27001. this._scene.registerAfterRender(this._syncUI);
  27002. };
  27003. DebugLayer.prototype._clearLabels = function () {
  27004. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27005. for (var index = 0; index < this._scene.meshes.length; index++) {
  27006. var mesh = this._scene.meshes[index];
  27007. mesh.renderOverlay = false;
  27008. }
  27009. };
  27010. DebugLayer.prototype._generateheader = function (root, text) {
  27011. var header = document.createElement("div");
  27012. header.innerHTML = text + "&nbsp;";
  27013. header.style.textAlign = "right";
  27014. header.style.width = "100%";
  27015. header.style.color = "white";
  27016. header.style.backgroundColor = "Black";
  27017. header.style.padding = "5px 5px 4px 0px";
  27018. header.style.marginLeft = "-5px";
  27019. header.style.fontWeight = "bold";
  27020. root.appendChild(header);
  27021. };
  27022. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27023. var label = document.createElement("label");
  27024. label.innerHTML = title;
  27025. label.style.color = color;
  27026. root.appendChild(label);
  27027. root.appendChild(document.createElement("br"));
  27028. };
  27029. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27030. if (tag === void 0) { tag = null; }
  27031. var label = document.createElement("label");
  27032. var boundingBoxesCheckbox = document.createElement("input");
  27033. boundingBoxesCheckbox.type = "checkbox";
  27034. boundingBoxesCheckbox.checked = initialState;
  27035. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27036. task(evt.target, tag);
  27037. });
  27038. label.appendChild(boundingBoxesCheckbox);
  27039. var container = document.createElement("span");
  27040. var leftPart = document.createElement("span");
  27041. var rightPart = document.createElement("span");
  27042. rightPart.style.cssFloat = "right";
  27043. leftPart.innerHTML = leftTitle;
  27044. rightPart.innerHTML = rightTitle;
  27045. rightPart.style.fontSize = "12px";
  27046. rightPart.style.maxWidth = "200px";
  27047. container.appendChild(leftPart);
  27048. container.appendChild(rightPart);
  27049. label.appendChild(container);
  27050. root.appendChild(label);
  27051. root.appendChild(document.createElement("br"));
  27052. };
  27053. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27054. if (tag === void 0) { tag = null; }
  27055. var label = document.createElement("label");
  27056. var checkBox = document.createElement("input");
  27057. checkBox.type = "checkbox";
  27058. checkBox.checked = initialState;
  27059. checkBox.addEventListener("change", function (evt) {
  27060. task(evt.target, tag);
  27061. });
  27062. label.appendChild(checkBox);
  27063. label.appendChild(document.createTextNode(title));
  27064. root.appendChild(label);
  27065. root.appendChild(document.createElement("br"));
  27066. };
  27067. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27068. if (tag === void 0) { tag = null; }
  27069. var button = document.createElement("button");
  27070. button.innerHTML = title;
  27071. button.style.height = "24px";
  27072. button.style.width = "150px";
  27073. button.style.marginBottom = "5px";
  27074. button.style.color = "#444444";
  27075. button.style.border = "1px solid white";
  27076. button.className = "debugLayerButton";
  27077. button.addEventListener("click", function (evt) {
  27078. task(evt.target, tag);
  27079. });
  27080. root.appendChild(button);
  27081. root.appendChild(document.createElement("br"));
  27082. };
  27083. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27084. if (tag === void 0) { tag = null; }
  27085. var label = document.createElement("label");
  27086. var boundingBoxesRadio = document.createElement("input");
  27087. boundingBoxesRadio.type = "radio";
  27088. boundingBoxesRadio.name = name;
  27089. boundingBoxesRadio.checked = initialState;
  27090. boundingBoxesRadio.addEventListener("change", function (evt) {
  27091. task(evt.target, tag);
  27092. });
  27093. label.appendChild(boundingBoxesRadio);
  27094. label.appendChild(document.createTextNode(title));
  27095. root.appendChild(label);
  27096. root.appendChild(document.createElement("br"));
  27097. };
  27098. DebugLayer.prototype._generateDOMelements = function () {
  27099. var _this = this;
  27100. this._globalDiv.id = "DebugLayer";
  27101. this._globalDiv.style.position = "absolute";
  27102. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27103. this._globalDiv.style.fontSize = "14px";
  27104. this._globalDiv.style.color = "white";
  27105. // Drawing canvas
  27106. this._drawingCanvas = document.createElement("canvas");
  27107. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27108. this._drawingCanvas.style.position = "absolute";
  27109. this._drawingCanvas.style.pointerEvents = "none";
  27110. this._drawingCanvas.style.backgroundColor = "transparent";
  27111. this._drawingContext = this._drawingCanvas.getContext("2d");
  27112. this._globalDiv.appendChild(this._drawingCanvas);
  27113. if (this._showUI) {
  27114. var background = "rgba(128, 128, 128, 0.4)";
  27115. var border = "rgb(180, 180, 180) solid 1px";
  27116. // Stats
  27117. this._statsDiv = document.createElement("div");
  27118. this._statsDiv.id = "DebugLayerStats";
  27119. this._statsDiv.style.border = border;
  27120. this._statsDiv.style.position = "absolute";
  27121. this._statsDiv.style.background = background;
  27122. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27123. this._generateheader(this._statsDiv, "STATISTICS");
  27124. this._statsSubsetDiv = document.createElement("div");
  27125. this._statsSubsetDiv.style.paddingTop = "5px";
  27126. this._statsSubsetDiv.style.paddingBottom = "5px";
  27127. this._statsSubsetDiv.style.overflowY = "auto";
  27128. this._statsDiv.appendChild(this._statsSubsetDiv);
  27129. // Tree
  27130. this._treeDiv = document.createElement("div");
  27131. this._treeDiv.id = "DebugLayerTree";
  27132. this._treeDiv.style.border = border;
  27133. this._treeDiv.style.position = "absolute";
  27134. this._treeDiv.style.background = background;
  27135. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27136. this._treeDiv.style.display = "none";
  27137. this._generateheader(this._treeDiv, "MESHES TREE");
  27138. this._treeSubsetDiv = document.createElement("div");
  27139. this._treeSubsetDiv.style.paddingTop = "5px";
  27140. this._treeSubsetDiv.style.paddingRight = "5px";
  27141. this._treeSubsetDiv.style.overflowY = "auto";
  27142. this._treeSubsetDiv.style.maxHeight = "300px";
  27143. this._treeDiv.appendChild(this._treeSubsetDiv);
  27144. this._needToRefreshMeshesTree = true;
  27145. // Logs
  27146. this._logDiv = document.createElement("div");
  27147. this._logDiv.style.border = border;
  27148. this._logDiv.id = "DebugLayerLogs";
  27149. this._logDiv.style.position = "absolute";
  27150. this._logDiv.style.background = background;
  27151. this._logDiv.style.padding = "0px 0px 0px 5px";
  27152. this._logDiv.style.display = "none";
  27153. this._generateheader(this._logDiv, "LOGS");
  27154. this._logSubsetDiv = document.createElement("div");
  27155. this._logSubsetDiv.style.height = "127px";
  27156. this._logSubsetDiv.style.paddingTop = "5px";
  27157. this._logSubsetDiv.style.overflowY = "auto";
  27158. this._logSubsetDiv.style.fontSize = "12px";
  27159. this._logSubsetDiv.style.fontFamily = "consolas";
  27160. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27161. this._logDiv.appendChild(this._logSubsetDiv);
  27162. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27163. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27164. };
  27165. // Options
  27166. this._optionsDiv = document.createElement("div");
  27167. this._optionsDiv.id = "DebugLayerOptions";
  27168. this._optionsDiv.style.border = border;
  27169. this._optionsDiv.style.position = "absolute";
  27170. this._optionsDiv.style.background = background;
  27171. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27172. this._optionsDiv.style.overflowY = "auto";
  27173. this._generateheader(this._optionsDiv, "OPTIONS");
  27174. this._optionsSubsetDiv = document.createElement("div");
  27175. this._optionsSubsetDiv.style.paddingTop = "5px";
  27176. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27177. this._optionsSubsetDiv.style.overflowY = "auto";
  27178. this._optionsSubsetDiv.style.maxHeight = "200px";
  27179. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27180. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27181. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  27182. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  27183. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27184. _this._displayTree = element.checked;
  27185. _this._needToRefreshMeshesTree = true;
  27186. });
  27187. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27188. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27189. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  27190. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27191. _this._labelsEnabled = element.checked;
  27192. if (!_this._labelsEnabled) {
  27193. _this._clearLabels();
  27194. }
  27195. });
  27196. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27197. if (element.checked) {
  27198. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27199. }
  27200. else {
  27201. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27202. }
  27203. });
  27204. ;
  27205. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27206. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27207. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27208. if (element.checked) {
  27209. _this._scene.forceWireframe = false;
  27210. _this._scene.forcePointsCloud = false;
  27211. }
  27212. });
  27213. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27214. if (element.checked) {
  27215. _this._scene.forceWireframe = true;
  27216. _this._scene.forcePointsCloud = false;
  27217. }
  27218. });
  27219. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27220. if (element.checked) {
  27221. _this._scene.forceWireframe = false;
  27222. _this._scene.forcePointsCloud = true;
  27223. }
  27224. });
  27225. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27226. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27227. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  27228. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  27229. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  27230. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  27231. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  27232. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  27233. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  27234. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  27235. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  27236. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27237. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27238. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  27239. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  27240. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  27241. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  27242. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  27243. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  27244. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  27245. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  27246. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  27247. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  27248. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  27249. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  27250. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  27251. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  27252. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  27253. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27254. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27255. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27256. if (element.checked) {
  27257. _this._scene.headphone = true;
  27258. }
  27259. });
  27260. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27261. if (element.checked) {
  27262. _this._scene.headphone = false;
  27263. }
  27264. });
  27265. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27266. _this._scene.audioEnabled = !element.checked;
  27267. });
  27268. }
  27269. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27270. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27271. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  27272. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  27273. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27274. this._globalDiv.appendChild(this._statsDiv);
  27275. this._globalDiv.appendChild(this._logDiv);
  27276. this._globalDiv.appendChild(this._optionsDiv);
  27277. this._globalDiv.appendChild(this._treeDiv);
  27278. }
  27279. };
  27280. DebugLayer.prototype._displayStats = function () {
  27281. var scene = this._scene;
  27282. var engine = scene.getEngine();
  27283. var glInfo = engine.getGlInfo();
  27284. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  27285. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27286. + "<b>Count</b><br>"
  27287. + "Total meshes: " + scene.meshes.length + "<br>"
  27288. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  27289. + "Total materials: " + scene.materials.length + "<br>"
  27290. + "Total textures: " + scene.textures.length + "<br>"
  27291. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  27292. + "Active indices: " + scene.getActiveIndices() + "<br>"
  27293. + "Active bones: " + scene.getActiveBones() + "<br>"
  27294. + "Active particles: " + scene.getActiveParticles() + "<br>"
  27295. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  27296. + "<b>Duration</b><br>"
  27297. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  27298. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  27299. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  27300. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  27301. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  27302. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  27303. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  27304. + "</div>"
  27305. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  27306. + "<b>Extensions</b><br>"
  27307. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  27308. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  27309. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  27310. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  27311. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  27312. + "<b>Caps.</b><br>"
  27313. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  27314. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  27315. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  27316. + "</div><br>"
  27317. + "<b>Info</b><br>"
  27318. + glInfo.version + "<br>"
  27319. + glInfo.renderer + "<br>";
  27320. if (this.customStatsFunction) {
  27321. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27322. }
  27323. };
  27324. return DebugLayer;
  27325. })();
  27326. BABYLON.DebugLayer = DebugLayer;
  27327. })(BABYLON || (BABYLON = {}));
  27328. var BABYLON;
  27329. (function (BABYLON) {
  27330. var DefaultLoadingScreen = (function () {
  27331. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  27332. var _this = this;
  27333. if (_loadingText === void 0) { _loadingText = ""; }
  27334. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  27335. this._renderingCanvas = _renderingCanvas;
  27336. this._loadingText = _loadingText;
  27337. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  27338. // Resize
  27339. this._resizeLoadingUI = function () {
  27340. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  27341. _this._loadingDiv.style.position = "absolute";
  27342. _this._loadingDiv.style.left = canvasRect.left + "px";
  27343. _this._loadingDiv.style.top = canvasRect.top + "px";
  27344. _this._loadingDiv.style.width = canvasRect.width + "px";
  27345. _this._loadingDiv.style.height = canvasRect.height + "px";
  27346. };
  27347. }
  27348. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  27349. var _this = this;
  27350. this._loadingDiv = document.createElement("div");
  27351. this._loadingDiv.style.opacity = "0";
  27352. this._loadingDiv.style.transition = "opacity 1.5s ease";
  27353. // Loading text
  27354. this._loadingTextDiv = document.createElement("div");
  27355. this._loadingTextDiv.style.position = "absolute";
  27356. this._loadingTextDiv.style.left = "0";
  27357. this._loadingTextDiv.style.top = "50%";
  27358. this._loadingTextDiv.style.marginTop = "80px";
  27359. this._loadingTextDiv.style.width = "100%";
  27360. this._loadingTextDiv.style.height = "20px";
  27361. this._loadingTextDiv.style.fontFamily = "Arial";
  27362. this._loadingTextDiv.style.fontSize = "14px";
  27363. this._loadingTextDiv.style.color = "white";
  27364. this._loadingTextDiv.style.textAlign = "center";
  27365. this._loadingTextDiv.innerHTML = "Loading";
  27366. this._loadingDiv.appendChild(this._loadingTextDiv);
  27367. //set the predefined text
  27368. this._loadingTextDiv.innerHTML = this._loadingText;
  27369. // Loading img
  27370. var imgBack = new Image();
  27371. 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==";
  27372. imgBack.style.position = "absolute";
  27373. imgBack.style.left = "50%";
  27374. imgBack.style.top = "50%";
  27375. imgBack.style.marginLeft = "-50px";
  27376. imgBack.style.marginTop = "-50px";
  27377. imgBack.style.transition = "transform 1.0s ease";
  27378. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  27379. var deg = 360;
  27380. var onTransitionEnd = function () {
  27381. deg += 360;
  27382. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  27383. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  27384. };
  27385. imgBack.addEventListener("transitionend", onTransitionEnd);
  27386. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  27387. this._loadingDiv.appendChild(imgBack);
  27388. // front image
  27389. var imgFront = new Image();
  27390. 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=";
  27391. imgFront.style.position = "absolute";
  27392. imgFront.style.left = "50%";
  27393. imgFront.style.top = "50%";
  27394. imgFront.style.marginLeft = "-50px";
  27395. imgFront.style.marginTop = "-50px";
  27396. this._loadingDiv.appendChild(imgFront);
  27397. this._resizeLoadingUI();
  27398. window.addEventListener("resize", this._resizeLoadingUI);
  27399. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27400. document.body.appendChild(this._loadingDiv);
  27401. setTimeout(function () {
  27402. _this._loadingDiv.style.opacity = "1";
  27403. imgBack.style.transform = "rotateZ(360deg)";
  27404. imgBack.style.webkitTransform = "rotateZ(360deg)";
  27405. }, 0);
  27406. };
  27407. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  27408. var _this = this;
  27409. if (!this._loadingDiv) {
  27410. return;
  27411. }
  27412. var onTransitionEnd = function () {
  27413. if (!_this._loadingDiv) {
  27414. return;
  27415. }
  27416. document.body.removeChild(_this._loadingDiv);
  27417. window.removeEventListener("resize", _this._resizeLoadingUI);
  27418. _this._loadingDiv = null;
  27419. };
  27420. this._loadingDiv.style.opacity = "0";
  27421. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  27422. };
  27423. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  27424. set: function (text) {
  27425. this._loadingText = text;
  27426. if (this._loadingTextDiv) {
  27427. this._loadingTextDiv.innerHTML = this._loadingText;
  27428. }
  27429. },
  27430. enumerable: true,
  27431. configurable: true
  27432. });
  27433. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  27434. get: function () {
  27435. return this._loadingDivBackgroundColor;
  27436. },
  27437. set: function (color) {
  27438. this._loadingDivBackgroundColor = color;
  27439. if (!this._loadingDiv) {
  27440. return;
  27441. }
  27442. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  27443. },
  27444. enumerable: true,
  27445. configurable: true
  27446. });
  27447. return DefaultLoadingScreen;
  27448. })();
  27449. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  27450. })(BABYLON || (BABYLON = {}));
  27451. var BABYLON;
  27452. (function (BABYLON) {
  27453. var SIMDVector3 = (function () {
  27454. function SIMDVector3() {
  27455. }
  27456. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  27457. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  27458. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27459. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27460. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27461. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27462. 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));
  27463. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27464. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27465. };
  27466. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  27467. var v0 = SIMD.float32x4.splat(x);
  27468. var v1 = SIMD.float32x4.splat(y);
  27469. var v2 = SIMD.float32x4.splat(z);
  27470. var m0 = SIMD.float32x4.load(transformation.m, 0);
  27471. var m1 = SIMD.float32x4.load(transformation.m, 4);
  27472. var m2 = SIMD.float32x4.load(transformation.m, 8);
  27473. var m3 = SIMD.float32x4.load(transformation.m, 12);
  27474. 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));
  27475. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  27476. SIMD.float32x4.storeXYZ(result._data, 0, r);
  27477. };
  27478. return SIMDVector3;
  27479. })();
  27480. BABYLON.SIMDVector3 = SIMDVector3;
  27481. var SIMDMatrix = (function () {
  27482. function SIMDMatrix() {
  27483. }
  27484. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  27485. if (offset === void 0) { offset = 0; }
  27486. var tm = this.m;
  27487. var om = other.m;
  27488. var om0 = SIMD.float32x4.load(om, 0);
  27489. var om1 = SIMD.float32x4.load(om, 4);
  27490. var om2 = SIMD.float32x4.load(om, 8);
  27491. var om3 = SIMD.float32x4.load(om, 12);
  27492. var tm0 = SIMD.float32x4.load(tm, 0);
  27493. 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)))));
  27494. var tm1 = SIMD.float32x4.load(tm, 4);
  27495. 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)))));
  27496. var tm2 = SIMD.float32x4.load(tm, 8);
  27497. 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)))));
  27498. var tm3 = SIMD.float32x4.load(tm, 12);
  27499. 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)))));
  27500. };
  27501. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  27502. var src = this.m;
  27503. var dest = other.m;
  27504. var row0, row1, row2, row3;
  27505. var tmp1;
  27506. var minor0, minor1, minor2, minor3;
  27507. var det;
  27508. // Load the 4 rows
  27509. var src0 = SIMD.float32x4.load(src, 0);
  27510. var src1 = SIMD.float32x4.load(src, 4);
  27511. var src2 = SIMD.float32x4.load(src, 8);
  27512. var src3 = SIMD.float32x4.load(src, 12);
  27513. // Transpose the source matrix. Sort of. Not a true transpose operation
  27514. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27515. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27516. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  27517. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  27518. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27519. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27520. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  27521. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  27522. // This is a true transposition, but it will lead to an incorrect result
  27523. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  27524. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  27525. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27526. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27527. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  27528. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  27529. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  27530. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  27531. // ----
  27532. tmp1 = SIMD.float32x4.mul(row2, row3);
  27533. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27534. minor0 = SIMD.float32x4.mul(row1, tmp1);
  27535. minor1 = SIMD.float32x4.mul(row0, tmp1);
  27536. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27537. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  27538. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  27539. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  27540. // ----
  27541. tmp1 = SIMD.float32x4.mul(row1, row2);
  27542. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27543. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  27544. minor3 = SIMD.float32x4.mul(row0, tmp1);
  27545. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27546. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  27547. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  27548. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  27549. // ----
  27550. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  27551. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27552. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  27553. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  27554. minor2 = SIMD.float32x4.mul(row0, tmp1);
  27555. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27556. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  27557. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  27558. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  27559. // ----
  27560. tmp1 = SIMD.float32x4.mul(row0, row1);
  27561. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27562. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  27563. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  27564. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27565. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  27566. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  27567. // ----
  27568. tmp1 = SIMD.float32x4.mul(row0, row3);
  27569. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27570. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  27571. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  27572. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27573. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  27574. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  27575. // ----
  27576. tmp1 = SIMD.float32x4.mul(row0, row2);
  27577. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  27578. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  27579. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  27580. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  27581. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  27582. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  27583. // Compute determinant
  27584. det = SIMD.float32x4.mul(row0, minor0);
  27585. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  27586. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  27587. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  27588. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  27589. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  27590. // These shuffles aren't necessary if the faulty transposition is done
  27591. // up at the top of this function.
  27592. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  27593. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  27594. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  27595. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  27596. // Compute final values by multiplying with 1/det
  27597. minor0 = SIMD.float32x4.mul(det, minor0);
  27598. minor1 = SIMD.float32x4.mul(det, minor1);
  27599. minor2 = SIMD.float32x4.mul(det, minor2);
  27600. minor3 = SIMD.float32x4.mul(det, minor3);
  27601. SIMD.float32x4.store(dest, 0, minor0);
  27602. SIMD.float32x4.store(dest, 4, minor1);
  27603. SIMD.float32x4.store(dest, 8, minor2);
  27604. SIMD.float32x4.store(dest, 12, minor3);
  27605. return this;
  27606. };
  27607. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  27608. var out = result.m;
  27609. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  27610. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  27611. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  27612. // cc.kmVec3Subtract(f, pCenter, pEye);
  27613. var f = SIMD.float32x4.sub(center, eye);
  27614. // cc.kmVec3Normalize(f, f);
  27615. var tmp = SIMD.float32x4.mul(f, f);
  27616. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27617. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27618. // cc.kmVec3Assign(up, pUp);
  27619. // cc.kmVec3Normalize(up, up);
  27620. tmp = SIMD.float32x4.mul(up, up);
  27621. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27622. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27623. // cc.kmVec3Cross(s, f, up);
  27624. 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)));
  27625. // cc.kmVec3Normalize(s, s);
  27626. tmp = SIMD.float32x4.mul(s, s);
  27627. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27628. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27629. // cc.kmVec3Cross(u, s, f);
  27630. 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)));
  27631. // cc.kmVec3Normalize(s, s);
  27632. tmp = SIMD.float32x4.mul(s, s);
  27633. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27634. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27635. var zero = SIMD.float32x4.splat(0.0);
  27636. s = SIMD.float32x4.neg(s);
  27637. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27638. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27639. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27640. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27641. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27642. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27643. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27644. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27645. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27646. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27647. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27648. var b3 = SIMD.float32x4.neg(eye);
  27649. b3 = SIMD.float32x4.withW(b3, 1.0);
  27650. 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)))));
  27651. 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)))));
  27652. 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)))));
  27653. 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)))));
  27654. };
  27655. return SIMDMatrix;
  27656. })();
  27657. BABYLON.SIMDMatrix = SIMDMatrix;
  27658. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27659. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27660. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27661. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27662. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27663. var SIMDHelper = (function () {
  27664. function SIMDHelper() {
  27665. }
  27666. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27667. get: function () {
  27668. return SIMDHelper._isEnabled;
  27669. },
  27670. enumerable: true,
  27671. configurable: true
  27672. });
  27673. SIMDHelper.DisableSIMD = function () {
  27674. // Replace functions
  27675. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27676. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27677. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27678. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27679. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27680. SIMDHelper._isEnabled = false;
  27681. };
  27682. SIMDHelper.EnableSIMD = function () {
  27683. if (window.SIMD === undefined) {
  27684. return;
  27685. }
  27686. // Replace functions
  27687. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27688. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27689. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27690. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27691. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27692. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27693. get: function () { return this._data[0]; },
  27694. set: function (value) {
  27695. if (!this._data) {
  27696. this._data = new Float32Array(3);
  27697. }
  27698. this._data[0] = value;
  27699. }
  27700. });
  27701. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27702. get: function () { return this._data[1]; },
  27703. set: function (value) {
  27704. this._data[1] = value;
  27705. }
  27706. });
  27707. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27708. get: function () { return this._data[2]; },
  27709. set: function (value) {
  27710. this._data[2] = value;
  27711. }
  27712. });
  27713. SIMDHelper._isEnabled = true;
  27714. };
  27715. SIMDHelper._isEnabled = false;
  27716. return SIMDHelper;
  27717. })();
  27718. BABYLON.SIMDHelper = SIMDHelper;
  27719. })(BABYLON || (BABYLON = {}));
  27720. var BABYLON;
  27721. (function (BABYLON) {
  27722. var ShaderMaterial = (function (_super) {
  27723. __extends(ShaderMaterial, _super);
  27724. function ShaderMaterial(name, scene, shaderPath, options) {
  27725. _super.call(this, name, scene);
  27726. this._textures = new Array();
  27727. this._floats = new Array();
  27728. this._floatsArrays = {};
  27729. this._colors3 = new Array();
  27730. this._colors4 = new Array();
  27731. this._vectors2 = new Array();
  27732. this._vectors3 = new Array();
  27733. this._vectors4 = new Array();
  27734. this._matrices = new Array();
  27735. this._matrices3x3 = new Array();
  27736. this._matrices2x2 = new Array();
  27737. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27738. this._shaderPath = shaderPath;
  27739. options.needAlphaBlending = options.needAlphaBlending || false;
  27740. options.needAlphaTesting = options.needAlphaTesting || false;
  27741. options.attributes = options.attributes || ["position", "normal", "uv"];
  27742. options.uniforms = options.uniforms || ["worldViewProjection"];
  27743. options.samplers = options.samplers || [];
  27744. options.defines = options.defines || [];
  27745. this._options = options;
  27746. }
  27747. ShaderMaterial.prototype.needAlphaBlending = function () {
  27748. return this._options.needAlphaBlending;
  27749. };
  27750. ShaderMaterial.prototype.needAlphaTesting = function () {
  27751. return this._options.needAlphaTesting;
  27752. };
  27753. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27754. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27755. this._options.uniforms.push(uniformName);
  27756. }
  27757. };
  27758. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27759. if (this._options.samplers.indexOf(name) === -1) {
  27760. this._options.samplers.push(name);
  27761. }
  27762. this._textures[name] = texture;
  27763. return this;
  27764. };
  27765. ShaderMaterial.prototype.setFloat = function (name, value) {
  27766. this._checkUniform(name);
  27767. this._floats[name] = value;
  27768. return this;
  27769. };
  27770. ShaderMaterial.prototype.setFloats = function (name, value) {
  27771. this._checkUniform(name);
  27772. this._floatsArrays[name] = value;
  27773. return this;
  27774. };
  27775. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27776. this._checkUniform(name);
  27777. this._colors3[name] = value;
  27778. return this;
  27779. };
  27780. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27781. this._checkUniform(name);
  27782. this._colors4[name] = value;
  27783. return this;
  27784. };
  27785. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27786. this._checkUniform(name);
  27787. this._vectors2[name] = value;
  27788. return this;
  27789. };
  27790. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27791. this._checkUniform(name);
  27792. this._vectors3[name] = value;
  27793. return this;
  27794. };
  27795. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27796. this._checkUniform(name);
  27797. this._vectors4[name] = value;
  27798. return this;
  27799. };
  27800. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27801. this._checkUniform(name);
  27802. this._matrices[name] = value;
  27803. return this;
  27804. };
  27805. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27806. this._checkUniform(name);
  27807. this._matrices3x3[name] = value;
  27808. return this;
  27809. };
  27810. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27811. this._checkUniform(name);
  27812. this._matrices2x2[name] = value;
  27813. return this;
  27814. };
  27815. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27816. var scene = this.getScene();
  27817. var engine = scene.getEngine();
  27818. if (!this.checkReadyOnEveryCall) {
  27819. if (this._renderId === scene.getRenderId()) {
  27820. return true;
  27821. }
  27822. }
  27823. // Instances
  27824. var defines = [];
  27825. var fallbacks = new BABYLON.EffectFallbacks();
  27826. if (useInstances) {
  27827. defines.push("#define INSTANCES");
  27828. }
  27829. for (var index = 0; index < this._options.defines.length; index++) {
  27830. defines.push(this._options.defines[index]);
  27831. }
  27832. // Bones
  27833. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  27835. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27836. fallbacks.addCPUSkinningFallback(0, mesh);
  27837. }
  27838. // Alpha test
  27839. if (engine.getAlphaTesting()) {
  27840. defines.push("#define ALPHATEST");
  27841. }
  27842. var previousEffect = this._effect;
  27843. var join = defines.join("\n");
  27844. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27845. if (!this._effect.isReady()) {
  27846. return false;
  27847. }
  27848. if (previousEffect !== this._effect) {
  27849. scene.resetCachedMaterial();
  27850. }
  27851. this._renderId = scene.getRenderId();
  27852. return true;
  27853. };
  27854. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27855. var scene = this.getScene();
  27856. if (this._options.uniforms.indexOf("world") !== -1) {
  27857. this._effect.setMatrix("world", world);
  27858. }
  27859. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27860. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27861. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27862. }
  27863. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27864. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27865. }
  27866. };
  27867. ShaderMaterial.prototype.bind = function (world, mesh) {
  27868. // Std values
  27869. this.bindOnlyWorldMatrix(world);
  27870. if (this.getScene().getCachedMaterial() !== this) {
  27871. if (this._options.uniforms.indexOf("view") !== -1) {
  27872. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27873. }
  27874. if (this._options.uniforms.indexOf("projection") !== -1) {
  27875. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27876. }
  27877. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27878. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27879. }
  27880. // Bones
  27881. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27882. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27883. }
  27884. // Texture
  27885. for (var name in this._textures) {
  27886. this._effect.setTexture(name, this._textures[name]);
  27887. }
  27888. // Float
  27889. for (name in this._floats) {
  27890. this._effect.setFloat(name, this._floats[name]);
  27891. }
  27892. // Float s
  27893. for (name in this._floatsArrays) {
  27894. this._effect.setArray(name, this._floatsArrays[name]);
  27895. }
  27896. // Color3
  27897. for (name in this._colors3) {
  27898. this._effect.setColor3(name, this._colors3[name]);
  27899. }
  27900. // Color4
  27901. for (name in this._colors4) {
  27902. var color = this._colors4[name];
  27903. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27904. }
  27905. // Vector2
  27906. for (name in this._vectors2) {
  27907. this._effect.setVector2(name, this._vectors2[name]);
  27908. }
  27909. // Vector3
  27910. for (name in this._vectors3) {
  27911. this._effect.setVector3(name, this._vectors3[name]);
  27912. }
  27913. // Vector4
  27914. for (name in this._vectors4) {
  27915. this._effect.setVector4(name, this._vectors4[name]);
  27916. }
  27917. // Matrix
  27918. for (name in this._matrices) {
  27919. this._effect.setMatrix(name, this._matrices[name]);
  27920. }
  27921. // Matrix 3x3
  27922. for (name in this._matrices3x3) {
  27923. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27924. }
  27925. // Matrix 2x2
  27926. for (name in this._matrices2x2) {
  27927. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27928. }
  27929. }
  27930. _super.prototype.bind.call(this, world, mesh);
  27931. };
  27932. ShaderMaterial.prototype.clone = function (name) {
  27933. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27934. return newShaderMaterial;
  27935. };
  27936. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27937. for (var name in this._textures) {
  27938. this._textures[name].dispose();
  27939. }
  27940. this._textures = [];
  27941. _super.prototype.dispose.call(this, forceDisposeEffect);
  27942. };
  27943. return ShaderMaterial;
  27944. })(BABYLON.Material);
  27945. BABYLON.ShaderMaterial = ShaderMaterial;
  27946. })(BABYLON || (BABYLON = {}));
  27947. var BABYLON;
  27948. (function (BABYLON) {
  27949. var Internals;
  27950. (function (Internals) {
  27951. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27952. // All values and structures referenced from:
  27953. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27954. var DDS_MAGIC = 0x20534444;
  27955. 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;
  27956. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27957. 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;
  27958. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27959. function FourCCToInt32(value) {
  27960. return value.charCodeAt(0) +
  27961. (value.charCodeAt(1) << 8) +
  27962. (value.charCodeAt(2) << 16) +
  27963. (value.charCodeAt(3) << 24);
  27964. }
  27965. function Int32ToFourCC(value) {
  27966. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27967. }
  27968. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27969. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27970. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27971. var headerLengthInt = 31; // The header length in 32 bit ints
  27972. // Offsets into the header array
  27973. var off_magic = 0;
  27974. var off_size = 1;
  27975. var off_flags = 2;
  27976. var off_height = 3;
  27977. var off_width = 4;
  27978. var off_mipmapCount = 7;
  27979. var off_pfFlags = 20;
  27980. var off_pfFourCC = 21;
  27981. var off_RGBbpp = 22;
  27982. var off_RMask = 23;
  27983. var off_GMask = 24;
  27984. var off_BMask = 25;
  27985. var off_AMask = 26;
  27986. var off_caps1 = 27;
  27987. var off_caps2 = 28;
  27988. ;
  27989. var DDSTools = (function () {
  27990. function DDSTools() {
  27991. }
  27992. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27993. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27994. var mipmapCount = 1;
  27995. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27996. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27997. }
  27998. return {
  27999. width: header[off_width],
  28000. height: header[off_height],
  28001. mipmapCount: mipmapCount,
  28002. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  28003. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  28004. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  28005. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  28006. };
  28007. };
  28008. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28009. var byteArray = new Uint8Array(dataLength);
  28010. var srcData = new Uint8Array(arrayBuffer);
  28011. var index = 0;
  28012. for (var y = height - 1; y >= 0; y--) {
  28013. for (var x = 0; x < width; x++) {
  28014. var srcPos = dataOffset + (x + y * width) * 4;
  28015. byteArray[index + 2] = srcData[srcPos];
  28016. byteArray[index + 1] = srcData[srcPos + 1];
  28017. byteArray[index] = srcData[srcPos + 2];
  28018. byteArray[index + 3] = srcData[srcPos + 3];
  28019. index += 4;
  28020. }
  28021. }
  28022. return byteArray;
  28023. };
  28024. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28025. var byteArray = new Uint8Array(dataLength);
  28026. var srcData = new Uint8Array(arrayBuffer);
  28027. var index = 0;
  28028. for (var y = height - 1; y >= 0; y--) {
  28029. for (var x = 0; x < width; x++) {
  28030. var srcPos = dataOffset + (x + y * width) * 3;
  28031. byteArray[index + 2] = srcData[srcPos];
  28032. byteArray[index + 1] = srcData[srcPos + 1];
  28033. byteArray[index] = srcData[srcPos + 2];
  28034. index += 3;
  28035. }
  28036. }
  28037. return byteArray;
  28038. };
  28039. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  28040. var byteArray = new Uint8Array(dataLength);
  28041. var srcData = new Uint8Array(arrayBuffer);
  28042. var index = 0;
  28043. for (var y = height - 1; y >= 0; y--) {
  28044. for (var x = 0; x < width; x++) {
  28045. var srcPos = dataOffset + (x + y * width);
  28046. byteArray[index] = srcData[srcPos];
  28047. index++;
  28048. }
  28049. }
  28050. return byteArray;
  28051. };
  28052. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  28053. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  28054. if (header[off_magic] != DDS_MAGIC) {
  28055. BABYLON.Tools.Error("Invalid magic number in DDS header");
  28056. return;
  28057. }
  28058. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  28059. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  28060. return;
  28061. }
  28062. if (info.isFourCC) {
  28063. fourCC = header[off_pfFourCC];
  28064. switch (fourCC) {
  28065. case FOURCC_DXT1:
  28066. blockBytes = 8;
  28067. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  28068. break;
  28069. case FOURCC_DXT3:
  28070. blockBytes = 16;
  28071. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  28072. break;
  28073. case FOURCC_DXT5:
  28074. blockBytes = 16;
  28075. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  28076. break;
  28077. default:
  28078. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  28079. return;
  28080. }
  28081. }
  28082. mipmapCount = 1;
  28083. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  28084. mipmapCount = Math.max(1, header[off_mipmapCount]);
  28085. }
  28086. var bpp = header[off_RGBbpp];
  28087. for (var face = 0; face < faces; face++) {
  28088. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  28089. width = header[off_width];
  28090. height = header[off_height];
  28091. dataOffset = header[off_size] + 4;
  28092. for (i = 0; i < mipmapCount; ++i) {
  28093. if (info.isRGB) {
  28094. if (bpp === 24) {
  28095. dataLength = width * height * 3;
  28096. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28097. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  28098. }
  28099. else {
  28100. dataLength = width * height * 4;
  28101. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28102. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  28103. }
  28104. }
  28105. else if (info.isLuminance) {
  28106. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  28107. var unpaddedRowSize = width;
  28108. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  28109. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  28110. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  28111. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  28112. }
  28113. else {
  28114. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  28115. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  28116. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  28117. }
  28118. dataOffset += dataLength;
  28119. width *= 0.5;
  28120. height *= 0.5;
  28121. width = Math.max(1.0, width);
  28122. height = Math.max(1.0, height);
  28123. }
  28124. }
  28125. };
  28126. return DDSTools;
  28127. })();
  28128. Internals.DDSTools = DDSTools;
  28129. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28130. })(BABYLON || (BABYLON = {}));
  28131. var BABYLON;
  28132. (function (BABYLON) {
  28133. var CannonJSPlugin = (function () {
  28134. function CannonJSPlugin() {
  28135. this._registeredMeshes = [];
  28136. this._physicsMaterials = [];
  28137. this.updateBodyPosition = function (mesh) {
  28138. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28139. var registeredMesh = this._registeredMeshes[index];
  28140. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28141. var body = registeredMesh.body;
  28142. var center = mesh.getBoundingInfo().boundingBox.center;
  28143. body.position.set(center.x, center.y, center.z);
  28144. body.quaternion.copy(mesh.rotationQuaternion);
  28145. if (registeredMesh.deltaRotation) {
  28146. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28147. body.quaternion = body.quaternion.mult(tmpQ);
  28148. }
  28149. if (registeredMesh.heightmap) {
  28150. //calculate the correct body position:
  28151. var rotationQuaternion = mesh.rotationQuaternion;
  28152. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28153. mesh.computeWorldMatrix(true);
  28154. //get original center with no rotation
  28155. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28156. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28157. //rotation is back
  28158. mesh.rotationQuaternion = rotationQuaternion;
  28159. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28160. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28161. mesh.setPivotMatrix(p);
  28162. mesh.computeWorldMatrix(true);
  28163. //calculate the translation
  28164. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28165. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28166. //add it inverted to the delta
  28167. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28168. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28169. mesh.setPivotMatrix(oldPivot);
  28170. mesh.computeWorldMatrix(true);
  28171. }
  28172. return;
  28173. }
  28174. }
  28175. };
  28176. }
  28177. CannonJSPlugin.prototype.initialize = function (iterations) {
  28178. if (iterations === void 0) { iterations = 10; }
  28179. this._world = new CANNON.World();
  28180. this._world.broadphase = new CANNON.NaiveBroadphase();
  28181. this._world.solver.iterations = iterations;
  28182. };
  28183. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  28184. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28185. };
  28186. CannonJSPlugin.prototype.runOneStep = function (delta) {
  28187. var _this = this;
  28188. this._world.step(delta);
  28189. this._registeredMeshes.forEach(function (registeredMesh) {
  28190. // Body position
  28191. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  28192. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  28193. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  28194. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  28195. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  28196. if (registeredMesh.deltaRotation) {
  28197. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  28198. }
  28199. //is the physics collision callback is set?
  28200. if (registeredMesh.mesh.onPhysicsCollide) {
  28201. if (!registeredMesh.collisionFunction) {
  28202. registeredMesh.collisionFunction = function (e) {
  28203. //find the mesh that collided with the registered mesh
  28204. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  28205. if (_this._registeredMeshes[idx].body == e.body) {
  28206. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh);
  28207. }
  28208. }
  28209. };
  28210. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  28211. }
  28212. }
  28213. else {
  28214. //unregister, in case the function was removed for some reason
  28215. if (registeredMesh.collisionFunction) {
  28216. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  28217. }
  28218. }
  28219. });
  28220. };
  28221. CannonJSPlugin.prototype.setGravity = function (gravity) {
  28222. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  28223. };
  28224. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28225. this.unregisterMesh(mesh);
  28226. if (!mesh.rotationQuaternion) {
  28227. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28228. }
  28229. mesh.computeWorldMatrix(true);
  28230. var shape = this._createShape(mesh, impostor);
  28231. return this._createRigidBodyFromShape(shape, mesh, options);
  28232. };
  28233. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  28234. //get the correct bounding box
  28235. var oldQuaternion = mesh.rotationQuaternion;
  28236. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28237. mesh.computeWorldMatrix(true);
  28238. var returnValue;
  28239. switch (impostor) {
  28240. case BABYLON.PhysicsEngine.SphereImpostor:
  28241. var bbox = mesh.getBoundingInfo().boundingBox;
  28242. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28243. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28244. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28245. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  28246. break;
  28247. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  28248. case BABYLON.PhysicsEngine.CylinderImpostor:
  28249. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  28250. case BABYLON.PhysicsEngine.BoxImpostor:
  28251. bbox = mesh.getBoundingInfo().boundingBox;
  28252. var min = bbox.minimumWorld;
  28253. var max = bbox.maximumWorld;
  28254. var box = max.subtract(min).scale(0.5);
  28255. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  28256. break;
  28257. case BABYLON.PhysicsEngine.PlaneImpostor:
  28258. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  28259. returnValue = new CANNON.Plane();
  28260. break;
  28261. case BABYLON.PhysicsEngine.MeshImpostor:
  28262. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28263. var rawFaces = mesh.getIndices();
  28264. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  28265. break;
  28266. case BABYLON.PhysicsEngine.HeightmapImpostor:
  28267. returnValue = this._createHeightmap(mesh);
  28268. break;
  28269. }
  28270. mesh.rotationQuaternion = oldQuaternion;
  28271. return returnValue;
  28272. };
  28273. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  28274. var verts = [], faces = [];
  28275. mesh.computeWorldMatrix(true);
  28276. //reuse this variable
  28277. var transformed = BABYLON.Vector3.Zero();
  28278. // Get vertices
  28279. for (var i = 0; i < rawVerts.length; i += 3) {
  28280. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  28281. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  28282. }
  28283. // Get faces
  28284. for (var j = 0; j < rawFaces.length; j += 3) {
  28285. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  28286. }
  28287. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  28288. return shape;
  28289. };
  28290. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  28291. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28292. var matrix = [];
  28293. //For now pointDepth will not be used and will be automatically calculated.
  28294. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  28295. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  28296. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  28297. var elementSize = dim * 2 / arraySize;
  28298. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  28299. for (var i = 0; i < pos.length; i = i + 3) {
  28300. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  28301. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  28302. var y = pos[i + 1] + minY;
  28303. if (!matrix[x]) {
  28304. matrix[x] = [];
  28305. }
  28306. if (!matrix[x][z]) {
  28307. matrix[x][z] = y;
  28308. }
  28309. matrix[x][z] = Math.max(y, matrix[x][z]);
  28310. }
  28311. for (var x = 0; x <= arraySize; ++x) {
  28312. if (!matrix[x]) {
  28313. var loc = 1;
  28314. while (!matrix[(x + loc) % arraySize]) {
  28315. loc++;
  28316. }
  28317. matrix[x] = matrix[(x + loc) % arraySize].slice();
  28318. }
  28319. for (var z = 0; z <= arraySize; ++z) {
  28320. if (!matrix[x][z]) {
  28321. var loc = 1;
  28322. var newValue;
  28323. while (newValue === undefined) {
  28324. newValue = matrix[x][(z + loc++) % arraySize];
  28325. }
  28326. matrix[x][z] = newValue;
  28327. }
  28328. }
  28329. }
  28330. var shape = new CANNON.Heightfield(matrix, {
  28331. elementSize: elementSize
  28332. });
  28333. //For future reference, needed for body transformation
  28334. shape.minY = minY;
  28335. return shape;
  28336. };
  28337. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  28338. var index;
  28339. var mat;
  28340. for (index = 0; index < this._physicsMaterials.length; index++) {
  28341. mat = this._physicsMaterials[index];
  28342. if (mat.friction === friction && mat.restitution === restitution) {
  28343. return mat;
  28344. }
  28345. }
  28346. var currentMat = new CANNON.Material("mat");
  28347. this._physicsMaterials.push(currentMat);
  28348. for (index = 0; index < this._physicsMaterials.length; index++) {
  28349. mat = this._physicsMaterials[index];
  28350. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  28351. this._world.addContactMaterial(contactMaterial);
  28352. }
  28353. return currentMat;
  28354. };
  28355. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  28356. if (!mesh.rotationQuaternion) {
  28357. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28358. }
  28359. // The delta between the mesh position and the mesh bounding box center
  28360. var bbox = mesh.getBoundingInfo().boundingBox;
  28361. var deltaPosition = mesh.position.subtract(bbox.center);
  28362. var deltaRotation;
  28363. var material = this._addMaterial(options.friction, options.restitution);
  28364. var body = new CANNON.Body({
  28365. mass: options.mass,
  28366. material: material,
  28367. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  28368. });
  28369. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  28370. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  28371. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28372. //-90 DEG in X, precalculated
  28373. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  28374. body.quaternion = body.quaternion.mult(tmpQ);
  28375. //Invert! (Precalculated, 90 deg in X)
  28376. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  28377. }
  28378. //If it is a heightfield, if should be centered.
  28379. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  28380. //calculate the correct body position:
  28381. var rotationQuaternion = mesh.rotationQuaternion;
  28382. mesh.rotationQuaternion = new BABYLON.Quaternion();
  28383. mesh.computeWorldMatrix(true);
  28384. //get original center with no rotation
  28385. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  28386. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  28387. //rotation is back
  28388. mesh.rotationQuaternion = rotationQuaternion;
  28389. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  28390. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  28391. mesh.setPivotMatrix(p);
  28392. mesh.computeWorldMatrix(true);
  28393. //calculate the translation
  28394. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  28395. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  28396. //add it inverted to the delta
  28397. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  28398. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  28399. mesh.setPivotMatrix(oldPivot);
  28400. mesh.computeWorldMatrix(true);
  28401. }
  28402. //add the shape
  28403. body.addShape(shape);
  28404. this._world.add(body);
  28405. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, heightmap: shape.type === CANNON.Shape.types.HEIGHTFIELD });
  28406. return body;
  28407. };
  28408. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28409. var initialMesh = parts[0].mesh;
  28410. this.unregisterMesh(initialMesh);
  28411. initialMesh.computeWorldMatrix(true);
  28412. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  28413. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  28414. for (var index = 1; index < parts.length; index++) {
  28415. var mesh = parts[index].mesh;
  28416. mesh.computeWorldMatrix(true);
  28417. var shape = this._createShape(mesh, parts[index].impostor);
  28418. var localPosition = mesh.position;
  28419. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  28420. }
  28421. return body;
  28422. };
  28423. CannonJSPlugin.prototype._unbindBody = function (body) {
  28424. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28425. var registeredMesh = this._registeredMeshes[index];
  28426. if (registeredMesh.body === body) {
  28427. this._world.remove(registeredMesh.body);
  28428. registeredMesh.body = null;
  28429. registeredMesh.delta = null;
  28430. registeredMesh.deltaRotation = null;
  28431. }
  28432. }
  28433. };
  28434. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  28435. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28436. var registeredMesh = this._registeredMeshes[index];
  28437. if (registeredMesh.mesh === mesh) {
  28438. // Remove body
  28439. if (registeredMesh.body) {
  28440. this._unbindBody(registeredMesh.body);
  28441. }
  28442. this._registeredMeshes.splice(index, 1);
  28443. return;
  28444. }
  28445. }
  28446. };
  28447. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28448. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  28449. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28450. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28451. var registeredMesh = this._registeredMeshes[index];
  28452. if (registeredMesh.mesh === mesh) {
  28453. registeredMesh.body.applyImpulse(impulse, worldPoint);
  28454. return;
  28455. }
  28456. }
  28457. };
  28458. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  28459. var body1 = null, body2 = null;
  28460. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28461. var registeredMesh = this._registeredMeshes[index];
  28462. if (registeredMesh.mesh === mesh1) {
  28463. body1 = registeredMesh.body;
  28464. }
  28465. else if (registeredMesh.mesh === mesh2) {
  28466. body2 = registeredMesh.body;
  28467. }
  28468. }
  28469. if (!body1 || !body2) {
  28470. return false;
  28471. }
  28472. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  28473. this._world.addConstraint(constraint);
  28474. return true;
  28475. };
  28476. CannonJSPlugin.prototype.dispose = function () {
  28477. while (this._registeredMeshes.length) {
  28478. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28479. }
  28480. };
  28481. CannonJSPlugin.prototype.isSupported = function () {
  28482. return window.CANNON !== undefined;
  28483. };
  28484. CannonJSPlugin.prototype.getWorldObject = function () {
  28485. return this._world;
  28486. };
  28487. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28488. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28489. var registeredMesh = this._registeredMeshes[index];
  28490. if (registeredMesh.mesh === mesh) {
  28491. return registeredMesh.body;
  28492. }
  28493. }
  28494. return null;
  28495. };
  28496. return CannonJSPlugin;
  28497. })();
  28498. BABYLON.CannonJSPlugin = CannonJSPlugin;
  28499. })(BABYLON || (BABYLON = {}));
  28500. var BABYLON;
  28501. (function (BABYLON) {
  28502. var OimoJSPlugin = (function () {
  28503. function OimoJSPlugin() {
  28504. this._registeredMeshes = [];
  28505. /**
  28506. * Update the body position according to the mesh position
  28507. * @param mesh
  28508. */
  28509. this.updateBodyPosition = function (mesh) {
  28510. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28511. var registeredMesh = this._registeredMeshes[index];
  28512. var body = registeredMesh.body.body;
  28513. var updated = false;
  28514. var newPosition;
  28515. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28516. mesh.computeWorldMatrix(true);
  28517. newPosition = mesh.getBoundingInfo().boundingBox.center;
  28518. updated = true;
  28519. }
  28520. else if (registeredMesh.mesh.parent === mesh) {
  28521. mesh.computeWorldMatrix(true);
  28522. registeredMesh.mesh.computeWorldMatrix(true);
  28523. newPosition = registeredMesh.mesh.getAbsolutePosition();
  28524. updated = true;
  28525. }
  28526. if (updated) {
  28527. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  28528. body.setQuaternion(mesh.rotationQuaternion);
  28529. body.sleeping = false;
  28530. //force Oimo to update the body's position
  28531. body.updatePosition(1);
  28532. }
  28533. }
  28534. };
  28535. }
  28536. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  28537. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  28538. };
  28539. OimoJSPlugin.prototype.initialize = function (iterations) {
  28540. this._world = new OIMO.World(null, null, iterations);
  28541. this._world.clear();
  28542. };
  28543. OimoJSPlugin.prototype.setGravity = function (gravity) {
  28544. this._world.gravity = gravity;
  28545. };
  28546. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  28547. this.unregisterMesh(mesh);
  28548. if (!mesh.rotationQuaternion) {
  28549. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28550. }
  28551. mesh.computeWorldMatrix(true);
  28552. var bbox = mesh.getBoundingInfo().boundingBox;
  28553. // The delta between the mesh position and the mesh bounding box center
  28554. var deltaPosition = mesh.position.subtract(bbox.center);
  28555. //calculate rotation to fit Oimo's needs (Euler...)
  28556. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28557. //get the correct bounding box
  28558. var oldQuaternion = mesh.rotationQuaternion;
  28559. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28560. mesh.computeWorldMatrix(true);
  28561. var bodyConfig = {
  28562. name: mesh.uniqueId,
  28563. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  28564. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  28565. move: options.mass != 0,
  28566. config: [options.mass, options.friction, options.restitution],
  28567. world: this._world
  28568. };
  28569. // register mesh
  28570. switch (impostor) {
  28571. case BABYLON.PhysicsEngine.SphereImpostor:
  28572. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28573. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28574. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28575. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28576. bodyConfig.type = 'sphere';
  28577. bodyConfig.size = [size];
  28578. break;
  28579. case BABYLON.PhysicsEngine.PlaneImpostor:
  28580. //Oimo "fakes" a cylinder as a box, so why don't we!
  28581. case BABYLON.PhysicsEngine.CylinderImpostor:
  28582. case BABYLON.PhysicsEngine.BoxImpostor:
  28583. var min = bbox.minimumWorld;
  28584. var max = bbox.maximumWorld;
  28585. var box = max.subtract(min);
  28586. var sizeX = this._checkWithEpsilon(box.x);
  28587. var sizeY = this._checkWithEpsilon(box.y);
  28588. var sizeZ = this._checkWithEpsilon(box.z);
  28589. bodyConfig.type = 'box';
  28590. bodyConfig.size = [sizeX, sizeY, sizeZ];
  28591. break;
  28592. }
  28593. var body = new OIMO.Body(bodyConfig);
  28594. //We have to access the rigid body's properties to set the quaternion.
  28595. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  28596. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  28597. //TEST
  28598. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  28599. //update the internal rotation matrix
  28600. //body.body.syncShapes();
  28601. this._registeredMeshes.push({
  28602. mesh: mesh,
  28603. body: body,
  28604. delta: deltaPosition
  28605. });
  28606. //for the sake of consistency.
  28607. mesh.rotationQuaternion = oldQuaternion;
  28608. return body;
  28609. };
  28610. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  28611. var types = [], sizes = [], positions = [], rotations = [];
  28612. var initialMesh = parts[0].mesh;
  28613. for (var index = 0; index < parts.length; index++) {
  28614. var part = parts[index];
  28615. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  28616. types.push(bodyParameters.type);
  28617. sizes.push.apply(sizes, bodyParameters.size);
  28618. positions.push.apply(positions, bodyParameters.pos);
  28619. rotations.push.apply(rotations, bodyParameters.rot);
  28620. }
  28621. var body = new OIMO.Body({
  28622. name: initialMesh.uniqueId,
  28623. type: types,
  28624. size: sizes,
  28625. pos: positions,
  28626. rot: rotations,
  28627. move: options.mass != 0,
  28628. config: [options.mass, options.friction, options.restitution],
  28629. world: this._world
  28630. });
  28631. //Reset the body's rotation to be of the initial mesh's.
  28632. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  28633. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  28634. this._registeredMeshes.push({
  28635. mesh: initialMesh,
  28636. body: body
  28637. });
  28638. return body;
  28639. };
  28640. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  28641. var mesh = part.mesh;
  28642. if (!mesh.rotationQuaternion) {
  28643. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  28644. }
  28645. // We need the bounding box/sphere info to compute the physics body
  28646. mesh.computeWorldMatrix(true);
  28647. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  28648. var bodyParameters = {
  28649. name: mesh.uniqueId,
  28650. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  28651. //A bug in Oimo (Body class) prevents us from using rot directly.
  28652. rot: [0, 0, 0],
  28653. //For future reference, if the bug will ever be fixed.
  28654. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  28655. };
  28656. var oldQuaternion = mesh.rotationQuaternion;
  28657. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  28658. mesh.computeWorldMatrix(true);
  28659. switch (part.impostor) {
  28660. case BABYLON.PhysicsEngine.SphereImpostor:
  28661. var bbox = mesh.getBoundingInfo().boundingBox;
  28662. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  28663. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  28664. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  28665. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  28666. bodyParameters.type = 'sphere';
  28667. bodyParameters.size = [size, size, size];
  28668. break;
  28669. case BABYLON.PhysicsEngine.PlaneImpostor:
  28670. case BABYLON.PhysicsEngine.CylinderImpostor:
  28671. case BABYLON.PhysicsEngine.BoxImpostor:
  28672. bbox = mesh.getBoundingInfo().boundingBox;
  28673. var min = bbox.minimumWorld;
  28674. var max = bbox.maximumWorld;
  28675. var box = max.subtract(min);
  28676. var sizeX = this._checkWithEpsilon(box.x);
  28677. var sizeY = this._checkWithEpsilon(box.y);
  28678. var sizeZ = this._checkWithEpsilon(box.z);
  28679. bodyParameters.type = 'box';
  28680. bodyParameters.size = [sizeX, sizeY, sizeZ];
  28681. break;
  28682. }
  28683. mesh.rotationQuaternion = oldQuaternion;
  28684. return bodyParameters;
  28685. };
  28686. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  28687. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28688. var registeredMesh = this._registeredMeshes[index];
  28689. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28690. if (registeredMesh.body) {
  28691. this._world.removeRigidBody(registeredMesh.body.body);
  28692. this._unbindBody(registeredMesh.body);
  28693. }
  28694. this._registeredMeshes.splice(index, 1);
  28695. return;
  28696. }
  28697. }
  28698. };
  28699. OimoJSPlugin.prototype._unbindBody = function (body) {
  28700. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28701. var registeredMesh = this._registeredMeshes[index];
  28702. if (registeredMesh.body === body) {
  28703. registeredMesh.body = null;
  28704. }
  28705. }
  28706. };
  28707. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28708. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28709. var registeredMesh = this._registeredMeshes[index];
  28710. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28711. // Get object mass to have a behaviour similar to cannon.js
  28712. var mass = registeredMesh.body.body.massInfo.mass;
  28713. // The force is scaled with the mass of object
  28714. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28715. return;
  28716. }
  28717. }
  28718. };
  28719. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28720. var body1 = null, body2 = null;
  28721. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28722. var registeredMesh = this._registeredMeshes[index];
  28723. if (registeredMesh.mesh === mesh1) {
  28724. body1 = registeredMesh.body.body;
  28725. }
  28726. else if (registeredMesh.mesh === mesh2) {
  28727. body2 = registeredMesh.body.body;
  28728. }
  28729. }
  28730. if (!body1 || !body2) {
  28731. return false;
  28732. }
  28733. if (!options) {
  28734. options = {};
  28735. }
  28736. new OIMO.Link({
  28737. type: options.type,
  28738. body1: body1,
  28739. body2: body2,
  28740. min: options.min,
  28741. max: options.max,
  28742. axe1: options.axe1,
  28743. axe2: options.axe2,
  28744. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28745. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28746. collision: options.collision,
  28747. spring: options.spring,
  28748. world: this._world
  28749. });
  28750. return true;
  28751. };
  28752. OimoJSPlugin.prototype.dispose = function () {
  28753. this._world.clear();
  28754. while (this._registeredMeshes.length) {
  28755. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28756. }
  28757. };
  28758. OimoJSPlugin.prototype.isSupported = function () {
  28759. return OIMO !== undefined;
  28760. };
  28761. OimoJSPlugin.prototype.getWorldObject = function () {
  28762. return this._world;
  28763. };
  28764. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28765. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28766. var registeredMesh = this._registeredMeshes[index];
  28767. if (registeredMesh.mesh === mesh) {
  28768. return registeredMesh.body;
  28769. }
  28770. }
  28771. return null;
  28772. };
  28773. OimoJSPlugin.prototype._getLastShape = function (body) {
  28774. var lastShape = body.shapes;
  28775. while (lastShape.next) {
  28776. lastShape = lastShape.next;
  28777. }
  28778. return lastShape;
  28779. };
  28780. OimoJSPlugin.prototype.runOneStep = function (time) {
  28781. this._world.step();
  28782. // Update the position of all registered meshes
  28783. var i = this._registeredMeshes.length;
  28784. var m;
  28785. while (i--) {
  28786. var body = this._registeredMeshes[i].body.body;
  28787. var mesh = this._registeredMeshes[i].mesh;
  28788. if (!this._registeredMeshes[i].delta) {
  28789. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28790. }
  28791. if (!body.sleeping) {
  28792. //TODO check that
  28793. if (body.shapes.next) {
  28794. var parentShape = this._getLastShape(body);
  28795. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28796. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28797. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28798. }
  28799. else {
  28800. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28801. }
  28802. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28803. mesh.computeWorldMatrix();
  28804. }
  28805. //check if the collide callback is set.
  28806. if (mesh.onPhysicsCollide) {
  28807. var meshUniqueName = mesh.uniqueId;
  28808. var contact = this._world.contacts;
  28809. while (contact !== null) {
  28810. //is this body colliding with any other?
  28811. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  28812. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  28813. //get the mesh and execute the callback
  28814. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  28815. if (otherMesh)
  28816. mesh.onPhysicsCollide(otherMesh);
  28817. }
  28818. contact = contact.next;
  28819. }
  28820. }
  28821. }
  28822. };
  28823. return OimoJSPlugin;
  28824. })();
  28825. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28826. })(BABYLON || (BABYLON = {}));
  28827. var BABYLON;
  28828. (function (BABYLON) {
  28829. var DisplayPassPostProcess = (function (_super) {
  28830. __extends(DisplayPassPostProcess, _super);
  28831. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28832. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28833. }
  28834. return DisplayPassPostProcess;
  28835. })(BABYLON.PostProcess);
  28836. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28837. })(BABYLON || (BABYLON = {}));
  28838. var BABYLON;
  28839. (function (BABYLON) {
  28840. var SimplificationSettings = (function () {
  28841. function SimplificationSettings(quality, distance, optimizeMesh) {
  28842. this.quality = quality;
  28843. this.distance = distance;
  28844. this.optimizeMesh = optimizeMesh;
  28845. }
  28846. return SimplificationSettings;
  28847. })();
  28848. BABYLON.SimplificationSettings = SimplificationSettings;
  28849. var SimplificationQueue = (function () {
  28850. function SimplificationQueue() {
  28851. this.running = false;
  28852. this._simplificationArray = [];
  28853. }
  28854. SimplificationQueue.prototype.addTask = function (task) {
  28855. this._simplificationArray.push(task);
  28856. };
  28857. SimplificationQueue.prototype.executeNext = function () {
  28858. var task = this._simplificationArray.pop();
  28859. if (task) {
  28860. this.running = true;
  28861. this.runSimplification(task);
  28862. }
  28863. else {
  28864. this.running = false;
  28865. }
  28866. };
  28867. SimplificationQueue.prototype.runSimplification = function (task) {
  28868. var _this = this;
  28869. if (task.parallelProcessing) {
  28870. //parallel simplifier
  28871. task.settings.forEach(function (setting) {
  28872. var simplifier = _this.getSimplifier(task);
  28873. simplifier.simplify(setting, function (newMesh) {
  28874. task.mesh.addLODLevel(setting.distance, newMesh);
  28875. newMesh.isVisible = true;
  28876. //check if it is the last
  28877. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28878. //all done, run the success callback.
  28879. task.successCallback();
  28880. }
  28881. _this.executeNext();
  28882. });
  28883. });
  28884. }
  28885. else {
  28886. //single simplifier.
  28887. var simplifier = this.getSimplifier(task);
  28888. var runDecimation = function (setting, callback) {
  28889. simplifier.simplify(setting, function (newMesh) {
  28890. task.mesh.addLODLevel(setting.distance, newMesh);
  28891. newMesh.isVisible = true;
  28892. //run the next quality level
  28893. callback();
  28894. });
  28895. };
  28896. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28897. runDecimation(task.settings[loop.index], function () {
  28898. loop.executeNext();
  28899. });
  28900. }, function () {
  28901. //execution ended, run the success callback.
  28902. if (task.successCallback) {
  28903. task.successCallback();
  28904. }
  28905. _this.executeNext();
  28906. });
  28907. }
  28908. };
  28909. SimplificationQueue.prototype.getSimplifier = function (task) {
  28910. switch (task.simplificationType) {
  28911. case SimplificationType.QUADRATIC:
  28912. default:
  28913. return new QuadraticErrorSimplification(task.mesh);
  28914. }
  28915. };
  28916. return SimplificationQueue;
  28917. })();
  28918. BABYLON.SimplificationQueue = SimplificationQueue;
  28919. /**
  28920. * The implemented types of simplification.
  28921. * At the moment only Quadratic Error Decimation is implemented.
  28922. */
  28923. (function (SimplificationType) {
  28924. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28925. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28926. var SimplificationType = BABYLON.SimplificationType;
  28927. var DecimationTriangle = (function () {
  28928. function DecimationTriangle(vertices) {
  28929. this.vertices = vertices;
  28930. this.error = new Array(4);
  28931. this.deleted = false;
  28932. this.isDirty = false;
  28933. this.deletePending = false;
  28934. this.borderFactor = 0;
  28935. }
  28936. return DecimationTriangle;
  28937. })();
  28938. BABYLON.DecimationTriangle = DecimationTriangle;
  28939. var DecimationVertex = (function () {
  28940. function DecimationVertex(position, id) {
  28941. this.position = position;
  28942. this.id = id;
  28943. this.isBorder = true;
  28944. this.q = new QuadraticMatrix();
  28945. this.triangleCount = 0;
  28946. this.triangleStart = 0;
  28947. this.originalOffsets = [];
  28948. }
  28949. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28950. this.position.copyFrom(newPosition);
  28951. };
  28952. return DecimationVertex;
  28953. })();
  28954. BABYLON.DecimationVertex = DecimationVertex;
  28955. var QuadraticMatrix = (function () {
  28956. function QuadraticMatrix(data) {
  28957. this.data = new Array(10);
  28958. for (var i = 0; i < 10; ++i) {
  28959. if (data && data[i]) {
  28960. this.data[i] = data[i];
  28961. }
  28962. else {
  28963. this.data[i] = 0;
  28964. }
  28965. }
  28966. }
  28967. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28968. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28969. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28970. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28971. return det;
  28972. };
  28973. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28974. for (var i = 0; i < 10; ++i) {
  28975. this.data[i] += matrix.data[i];
  28976. }
  28977. };
  28978. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28979. for (var i = 0; i < 10; ++i) {
  28980. this.data[i] += data[i];
  28981. }
  28982. };
  28983. QuadraticMatrix.prototype.add = function (matrix) {
  28984. var m = new QuadraticMatrix();
  28985. for (var i = 0; i < 10; ++i) {
  28986. m.data[i] = this.data[i] + matrix.data[i];
  28987. }
  28988. return m;
  28989. };
  28990. QuadraticMatrix.FromData = function (a, b, c, d) {
  28991. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28992. };
  28993. //returning an array to avoid garbage collection
  28994. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28995. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28996. };
  28997. return QuadraticMatrix;
  28998. })();
  28999. BABYLON.QuadraticMatrix = QuadraticMatrix;
  29000. var Reference = (function () {
  29001. function Reference(vertexId, triangleId) {
  29002. this.vertexId = vertexId;
  29003. this.triangleId = triangleId;
  29004. }
  29005. return Reference;
  29006. })();
  29007. BABYLON.Reference = Reference;
  29008. /**
  29009. * An implementation of the Quadratic Error simplification algorithm.
  29010. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  29011. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  29012. * @author RaananW
  29013. */
  29014. var QuadraticErrorSimplification = (function () {
  29015. function QuadraticErrorSimplification(_mesh) {
  29016. this._mesh = _mesh;
  29017. this.initialized = false;
  29018. this.syncIterations = 5000;
  29019. this.aggressiveness = 7;
  29020. this.decimationIterations = 100;
  29021. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  29022. }
  29023. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  29024. var _this = this;
  29025. this.initDecimatedMesh();
  29026. //iterating through the submeshes array, one after the other.
  29027. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  29028. _this.initWithMesh(loop.index, function () {
  29029. _this.runDecimation(settings, loop.index, function () {
  29030. loop.executeNext();
  29031. });
  29032. }, settings.optimizeMesh);
  29033. }, function () {
  29034. setTimeout(function () {
  29035. successCallback(_this._reconstructedMesh);
  29036. }, 0);
  29037. });
  29038. };
  29039. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  29040. var _this = this;
  29041. var gCount = 0;
  29042. triangle.vertices.forEach(function (vertex) {
  29043. var count = 0;
  29044. var vPos = vertex.position;
  29045. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  29046. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  29047. ++count;
  29048. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  29049. ++count;
  29050. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  29051. ++count;
  29052. if (count > 1) {
  29053. ++gCount;
  29054. }
  29055. ;
  29056. });
  29057. if (gCount > 1) {
  29058. console.log(triangle, gCount);
  29059. }
  29060. return gCount > 1;
  29061. };
  29062. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  29063. var _this = this;
  29064. var targetCount = ~~(this.triangles.length * settings.quality);
  29065. var deletedTriangles = 0;
  29066. var triangleCount = this.triangles.length;
  29067. var iterationFunction = function (iteration, callback) {
  29068. setTimeout(function () {
  29069. if (iteration % 5 === 0) {
  29070. _this.updateMesh(iteration === 0);
  29071. }
  29072. for (var i = 0; i < _this.triangles.length; ++i) {
  29073. _this.triangles[i].isDirty = false;
  29074. }
  29075. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  29076. var trianglesIterator = function (i) {
  29077. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  29078. var t = _this.triangles[tIdx];
  29079. if (!t)
  29080. return;
  29081. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  29082. return;
  29083. }
  29084. for (var j = 0; j < 3; ++j) {
  29085. if (t.error[j] < threshold) {
  29086. var deleted0 = [];
  29087. var deleted1 = [];
  29088. var v0 = t.vertices[j];
  29089. var v1 = t.vertices[(j + 1) % 3];
  29090. if (v0.isBorder !== v1.isBorder)
  29091. continue;
  29092. var p = BABYLON.Vector3.Zero();
  29093. var n = BABYLON.Vector3.Zero();
  29094. var uv = BABYLON.Vector2.Zero();
  29095. var color = new BABYLON.Color4(0, 0, 0, 1);
  29096. _this.calculateError(v0, v1, p, n, uv, color);
  29097. var delTr = [];
  29098. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  29099. continue;
  29100. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  29101. continue;
  29102. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  29103. continue;
  29104. var uniqueArray = [];
  29105. delTr.forEach(function (deletedT) {
  29106. if (uniqueArray.indexOf(deletedT) === -1) {
  29107. deletedT.deletePending = true;
  29108. uniqueArray.push(deletedT);
  29109. }
  29110. });
  29111. if (uniqueArray.length % 2 !== 0) {
  29112. continue;
  29113. }
  29114. v0.q = v1.q.add(v0.q);
  29115. v0.updatePosition(p);
  29116. var tStart = _this.references.length;
  29117. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  29118. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  29119. var tCount = _this.references.length - tStart;
  29120. if (tCount <= v0.triangleCount) {
  29121. if (tCount) {
  29122. for (var c = 0; c < tCount; c++) {
  29123. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  29124. }
  29125. }
  29126. }
  29127. else {
  29128. v0.triangleStart = tStart;
  29129. }
  29130. v0.triangleCount = tCount;
  29131. break;
  29132. }
  29133. }
  29134. };
  29135. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  29136. }, 0);
  29137. };
  29138. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29139. if (triangleCount - deletedTriangles <= targetCount)
  29140. loop.breakLoop();
  29141. else {
  29142. iterationFunction(loop.index, function () {
  29143. loop.executeNext();
  29144. });
  29145. }
  29146. }, function () {
  29147. setTimeout(function () {
  29148. //reconstruct this part of the mesh
  29149. _this.reconstructMesh(submeshIndex);
  29150. successCallback();
  29151. }, 0);
  29152. });
  29153. };
  29154. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29155. var _this = this;
  29156. this.vertices = [];
  29157. this.triangles = [];
  29158. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29159. var indices = this._mesh.getIndices();
  29160. var submesh = this._mesh.subMeshes[submeshIndex];
  29161. var findInVertices = function (positionToSearch) {
  29162. if (optimizeMesh) {
  29163. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29164. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29165. return _this.vertices[ii];
  29166. }
  29167. }
  29168. }
  29169. return null;
  29170. };
  29171. var vertexReferences = [];
  29172. var vertexInit = function (i) {
  29173. var offset = i + submesh.verticesStart;
  29174. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29175. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29176. vertex.originalOffsets.push(offset);
  29177. if (vertex.id === _this.vertices.length) {
  29178. _this.vertices.push(vertex);
  29179. }
  29180. vertexReferences.push(vertex.id);
  29181. };
  29182. //var totalVertices = mesh.getTotalVertices();
  29183. var totalVertices = submesh.verticesCount;
  29184. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29185. var indicesInit = function (i) {
  29186. var offset = (submesh.indexStart / 3) + i;
  29187. var pos = (offset * 3);
  29188. var i0 = indices[pos + 0];
  29189. var i1 = indices[pos + 1];
  29190. var i2 = indices[pos + 2];
  29191. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29192. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29193. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29194. var triangle = new DecimationTriangle([v0, v1, v2]);
  29195. triangle.originalOffset = pos;
  29196. _this.triangles.push(triangle);
  29197. };
  29198. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29199. _this.init(callback);
  29200. });
  29201. });
  29202. };
  29203. QuadraticErrorSimplification.prototype.init = function (callback) {
  29204. var _this = this;
  29205. var triangleInit1 = function (i) {
  29206. var t = _this.triangles[i];
  29207. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29208. for (var j = 0; j < 3; j++) {
  29209. 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))));
  29210. }
  29211. };
  29212. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29213. var triangleInit2 = function (i) {
  29214. var t = _this.triangles[i];
  29215. for (var j = 0; j < 3; ++j) {
  29216. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29217. }
  29218. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29219. };
  29220. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29221. _this.initialized = true;
  29222. callback();
  29223. });
  29224. });
  29225. };
  29226. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29227. var newTriangles = [];
  29228. var i;
  29229. for (i = 0; i < this.vertices.length; ++i) {
  29230. this.vertices[i].triangleCount = 0;
  29231. }
  29232. var t;
  29233. var j;
  29234. for (i = 0; i < this.triangles.length; ++i) {
  29235. if (!this.triangles[i].deleted) {
  29236. t = this.triangles[i];
  29237. for (j = 0; j < 3; ++j) {
  29238. t.vertices[j].triangleCount = 1;
  29239. }
  29240. newTriangles.push(t);
  29241. }
  29242. }
  29243. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  29244. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  29245. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  29246. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  29247. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29248. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29249. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29250. var vertexCount = 0;
  29251. for (i = 0; i < this.vertices.length; ++i) {
  29252. var vertex = this.vertices[i];
  29253. vertex.id = vertexCount;
  29254. if (vertex.triangleCount) {
  29255. vertex.originalOffsets.forEach(function (originalOffset) {
  29256. newPositionData.push(vertex.position.x);
  29257. newPositionData.push(vertex.position.y);
  29258. newPositionData.push(vertex.position.z);
  29259. newNormalData.push(normalData[originalOffset * 3]);
  29260. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29261. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29262. if (uvs && uvs.length) {
  29263. newUVsData.push(uvs[(originalOffset * 2)]);
  29264. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29265. }
  29266. else if (colorsData && colorsData.length) {
  29267. newColorsData.push(colorsData[(originalOffset * 4)]);
  29268. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29269. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29270. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29271. }
  29272. ++vertexCount;
  29273. });
  29274. }
  29275. }
  29276. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29277. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29278. var submeshesArray = this._reconstructedMesh.subMeshes;
  29279. this._reconstructedMesh.subMeshes = [];
  29280. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29281. var originalIndices = this._mesh.getIndices();
  29282. for (i = 0; i < newTriangles.length; ++i) {
  29283. t = newTriangles[i]; //now get the new referencing point for each vertex
  29284. [0, 1, 2].forEach(function (idx) {
  29285. var id = originalIndices[t.originalOffset + idx];
  29286. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29287. if (offset < 0)
  29288. offset = 0;
  29289. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29290. });
  29291. }
  29292. //overwriting the old vertex buffers and indices.
  29293. this._reconstructedMesh.setIndices(newIndicesArray);
  29294. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29295. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29296. if (newUVsData.length > 0)
  29297. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29298. if (newColorsData.length > 0)
  29299. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29300. //create submesh
  29301. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29302. if (submeshIndex > 0) {
  29303. this._reconstructedMesh.subMeshes = [];
  29304. submeshesArray.forEach(function (submesh) {
  29305. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29306. });
  29307. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29308. }
  29309. };
  29310. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29311. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29312. this._reconstructedMesh.material = this._mesh.material;
  29313. this._reconstructedMesh.parent = this._mesh.parent;
  29314. this._reconstructedMesh.isVisible = false;
  29315. };
  29316. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29317. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29318. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29319. if (t.deleted)
  29320. continue;
  29321. var s = this.references[vertex1.triangleStart + i].vertexId;
  29322. var v1 = t.vertices[(s + 1) % 3];
  29323. var v2 = t.vertices[(s + 2) % 3];
  29324. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  29325. deletedArray[i] = true;
  29326. delTr.push(t);
  29327. continue;
  29328. }
  29329. var d1 = v1.position.subtract(point);
  29330. d1 = d1.normalize();
  29331. var d2 = v2.position.subtract(point);
  29332. d2 = d2.normalize();
  29333. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29334. return true;
  29335. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29336. deletedArray[i] = false;
  29337. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29338. return true;
  29339. }
  29340. return false;
  29341. };
  29342. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29343. var newDeleted = deletedTriangles;
  29344. for (var i = 0; i < vertex.triangleCount; ++i) {
  29345. var ref = this.references[vertex.triangleStart + i];
  29346. var t = this.triangles[ref.triangleId];
  29347. if (t.deleted)
  29348. continue;
  29349. if (deletedArray[i] && t.deletePending) {
  29350. t.deleted = true;
  29351. newDeleted++;
  29352. continue;
  29353. }
  29354. t.vertices[ref.vertexId] = origVertex;
  29355. t.isDirty = true;
  29356. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29357. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29358. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29359. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29360. this.references.push(ref);
  29361. }
  29362. return newDeleted;
  29363. };
  29364. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29365. for (var i = 0; i < this.vertices.length; ++i) {
  29366. var vCount = [];
  29367. var vId = [];
  29368. var v = this.vertices[i];
  29369. var j;
  29370. for (j = 0; j < v.triangleCount; ++j) {
  29371. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29372. for (var ii = 0; ii < 3; ii++) {
  29373. var ofs = 0;
  29374. var vv = triangle.vertices[ii];
  29375. while (ofs < vCount.length) {
  29376. if (vId[ofs] === vv.id)
  29377. break;
  29378. ++ofs;
  29379. }
  29380. if (ofs === vCount.length) {
  29381. vCount.push(1);
  29382. vId.push(vv.id);
  29383. }
  29384. else {
  29385. vCount[ofs]++;
  29386. }
  29387. }
  29388. }
  29389. for (j = 0; j < vCount.length; ++j) {
  29390. if (vCount[j] === 1) {
  29391. this.vertices[vId[j]].isBorder = true;
  29392. }
  29393. else {
  29394. this.vertices[vId[j]].isBorder = false;
  29395. }
  29396. }
  29397. }
  29398. };
  29399. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29400. if (identifyBorders === void 0) { identifyBorders = false; }
  29401. var i;
  29402. if (!identifyBorders) {
  29403. var newTrianglesVector = [];
  29404. for (i = 0; i < this.triangles.length; ++i) {
  29405. if (!this.triangles[i].deleted) {
  29406. newTrianglesVector.push(this.triangles[i]);
  29407. }
  29408. }
  29409. this.triangles = newTrianglesVector;
  29410. }
  29411. for (i = 0; i < this.vertices.length; ++i) {
  29412. this.vertices[i].triangleCount = 0;
  29413. this.vertices[i].triangleStart = 0;
  29414. }
  29415. var t;
  29416. var j;
  29417. var v;
  29418. for (i = 0; i < this.triangles.length; ++i) {
  29419. t = this.triangles[i];
  29420. for (j = 0; j < 3; ++j) {
  29421. v = t.vertices[j];
  29422. v.triangleCount++;
  29423. }
  29424. }
  29425. var tStart = 0;
  29426. for (i = 0; i < this.vertices.length; ++i) {
  29427. this.vertices[i].triangleStart = tStart;
  29428. tStart += this.vertices[i].triangleCount;
  29429. this.vertices[i].triangleCount = 0;
  29430. }
  29431. var newReferences = new Array(this.triangles.length * 3);
  29432. for (i = 0; i < this.triangles.length; ++i) {
  29433. t = this.triangles[i];
  29434. for (j = 0; j < 3; ++j) {
  29435. v = t.vertices[j];
  29436. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29437. v.triangleCount++;
  29438. }
  29439. }
  29440. this.references = newReferences;
  29441. if (identifyBorders) {
  29442. this.identifyBorder();
  29443. }
  29444. };
  29445. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29446. var x = point.x;
  29447. var y = point.y;
  29448. var z = point.z;
  29449. 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
  29450. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  29451. };
  29452. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29453. var q = vertex1.q.add(vertex2.q);
  29454. var border = vertex1.isBorder && vertex2.isBorder;
  29455. var error = 0;
  29456. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29457. if (qDet !== 0 && !border) {
  29458. if (!pointResult) {
  29459. pointResult = BABYLON.Vector3.Zero();
  29460. }
  29461. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29462. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29463. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29464. error = this.vertexError(q, pointResult);
  29465. }
  29466. else {
  29467. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29468. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29469. var error1 = this.vertexError(q, vertex1.position);
  29470. var error2 = this.vertexError(q, vertex2.position);
  29471. var error3 = this.vertexError(q, p3);
  29472. error = Math.min(error1, error2, error3);
  29473. if (error === error1) {
  29474. if (pointResult) {
  29475. pointResult.copyFrom(vertex1.position);
  29476. }
  29477. }
  29478. else if (error === error2) {
  29479. if (pointResult) {
  29480. pointResult.copyFrom(vertex2.position);
  29481. }
  29482. }
  29483. else {
  29484. if (pointResult) {
  29485. pointResult.copyFrom(p3);
  29486. }
  29487. }
  29488. }
  29489. return error;
  29490. };
  29491. return QuadraticErrorSimplification;
  29492. })();
  29493. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29494. })(BABYLON || (BABYLON = {}));
  29495. var BABYLON;
  29496. (function (BABYLON) {
  29497. var serializeLight = function (light) {
  29498. var serializationObject = {};
  29499. serializationObject.name = light.name;
  29500. serializationObject.id = light.id;
  29501. serializationObject.tags = BABYLON.Tags.GetTags(light);
  29502. if (light instanceof BABYLON.PointLight) {
  29503. serializationObject.type = 0;
  29504. serializationObject.position = (light).position.asArray();
  29505. }
  29506. else if (light instanceof BABYLON.DirectionalLight) {
  29507. serializationObject.type = 1;
  29508. var directionalLight = light;
  29509. serializationObject.position = directionalLight.position.asArray();
  29510. serializationObject.direction = directionalLight.direction.asArray();
  29511. }
  29512. else if (light instanceof BABYLON.SpotLight) {
  29513. serializationObject.type = 2;
  29514. var spotLight = light;
  29515. serializationObject.position = spotLight.position.asArray();
  29516. serializationObject.direction = spotLight.position.asArray();
  29517. serializationObject.angle = spotLight.angle;
  29518. serializationObject.exponent = spotLight.exponent;
  29519. }
  29520. else if (light instanceof BABYLON.HemisphericLight) {
  29521. serializationObject.type = 3;
  29522. var hemisphericLight = light;
  29523. serializationObject.direction = hemisphericLight.direction.asArray();
  29524. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  29525. }
  29526. if (light.intensity) {
  29527. serializationObject.intensity = light.intensity;
  29528. }
  29529. serializationObject.range = light.range;
  29530. serializationObject.diffuse = light.diffuse.asArray();
  29531. serializationObject.specular = light.specular.asArray();
  29532. return serializationObject;
  29533. };
  29534. var serializeFresnelParameter = function (fresnelParameter) {
  29535. var serializationObject = {};
  29536. serializationObject.isEnabled = fresnelParameter.isEnabled;
  29537. serializationObject.leftColor = fresnelParameter.leftColor;
  29538. serializationObject.rightColor = fresnelParameter.rightColor;
  29539. serializationObject.bias = fresnelParameter.bias;
  29540. serializationObject.power = fresnelParameter.power;
  29541. return serializationObject;
  29542. };
  29543. var serializeAnimation;
  29544. var appendAnimations = function (source, destination) {
  29545. if (source.animations) {
  29546. destination.animations = [];
  29547. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29548. var animation = source.animations[animationIndex];
  29549. destination.animations.push(serializeAnimation(animation));
  29550. }
  29551. }
  29552. };
  29553. var serializeCamera = function (camera) {
  29554. var serializationObject = {};
  29555. serializationObject.name = camera.name;
  29556. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  29557. serializationObject.id = camera.id;
  29558. serializationObject.position = camera.position.asArray();
  29559. // Parent
  29560. if (camera.parent) {
  29561. serializationObject.parentId = camera.parent.id;
  29562. }
  29563. serializationObject.fov = camera.fov;
  29564. serializationObject.minZ = camera.minZ;
  29565. serializationObject.maxZ = camera.maxZ;
  29566. serializationObject.inertia = camera.inertia;
  29567. //setting the type
  29568. if (camera instanceof BABYLON.FreeCamera) {
  29569. serializationObject.type = "FreeCamera";
  29570. }
  29571. else if (camera instanceof BABYLON.ArcRotateCamera) {
  29572. serializationObject.type = "ArcRotateCamera";
  29573. }
  29574. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29575. serializationObject.type = "AnaglyphArcRotateCamera";
  29576. }
  29577. else if (camera instanceof BABYLON.GamepadCamera) {
  29578. serializationObject.type = "GamepadCamera";
  29579. }
  29580. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  29581. serializationObject.type = "AnaglyphFreeCamera";
  29582. }
  29583. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  29584. serializationObject.type = "DeviceOrientationCamera";
  29585. }
  29586. else if (camera instanceof BABYLON.FollowCamera) {
  29587. serializationObject.type = "FollowCamera";
  29588. }
  29589. else if (camera instanceof BABYLON.TouchCamera) {
  29590. serializationObject.type = "TouchCamera";
  29591. }
  29592. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  29593. serializationObject.type = "VirtualJoysticksCamera";
  29594. }
  29595. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  29596. serializationObject.type = "WebVRFreeCamera";
  29597. }
  29598. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  29599. serializationObject.type = "VRDeviceOrientationFreeCamera";
  29600. }
  29601. //special properties of specific cameras
  29602. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29603. var arcCamera = camera;
  29604. serializationObject.alpha = arcCamera.alpha;
  29605. serializationObject.beta = arcCamera.beta;
  29606. serializationObject.radius = arcCamera.radius;
  29607. if (arcCamera.target && arcCamera.target.id) {
  29608. serializationObject.lockedTargetId = arcCamera.target.id;
  29609. }
  29610. }
  29611. else if (camera instanceof BABYLON.FollowCamera) {
  29612. var followCam = camera;
  29613. serializationObject.radius = followCam.radius;
  29614. serializationObject.heightOffset = followCam.heightOffset;
  29615. serializationObject.rotationOffset = followCam.rotationOffset;
  29616. }
  29617. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  29618. //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.
  29619. if (camera['_interaxialDistance'] !== undefined) {
  29620. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  29621. }
  29622. }
  29623. //general properties that not all cameras have. The [] is due to typescript's type safety
  29624. if (camera['speed'] !== undefined) {
  29625. serializationObject.speed = camera['speed'];
  29626. }
  29627. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  29628. serializationObject.target = camera['target'].asArray();
  29629. }
  29630. // Target
  29631. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  29632. serializationObject.rotation = camera['rotation'].asArray();
  29633. }
  29634. // Locked target
  29635. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  29636. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  29637. }
  29638. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  29639. serializationObject.applyGravity = camera['applyGravity'] || false;
  29640. if (camera['ellipsoid']) {
  29641. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  29642. }
  29643. // Animations
  29644. appendAnimations(camera, serializationObject);
  29645. // Layer mask
  29646. serializationObject.layerMask = camera.layerMask;
  29647. return serializationObject;
  29648. };
  29649. serializeAnimation = function (animation) {
  29650. var serializationObject = {};
  29651. serializationObject.name = animation.name;
  29652. serializationObject.property = animation.targetProperty;
  29653. serializationObject.framePerSecond = animation.framePerSecond;
  29654. serializationObject.dataType = animation.dataType;
  29655. serializationObject.loopBehavior = animation.loopMode;
  29656. var dataType = animation.dataType;
  29657. serializationObject.keys = [];
  29658. var keys = animation.getKeys();
  29659. for (var index = 0; index < keys.length; index++) {
  29660. var animationKey = keys[index];
  29661. var key = {};
  29662. key.frame = animationKey.frame;
  29663. switch (dataType) {
  29664. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  29665. key.values = [animationKey.value];
  29666. break;
  29667. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  29668. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  29669. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  29670. key.values = animationKey.value.asArray();
  29671. break;
  29672. }
  29673. serializationObject.keys.push(key);
  29674. }
  29675. return serializationObject;
  29676. };
  29677. var serializeMultiMaterial = function (material) {
  29678. var serializationObject = {};
  29679. serializationObject.name = material.name;
  29680. serializationObject.id = material.id;
  29681. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29682. serializationObject.materials = [];
  29683. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  29684. var subMat = material.subMaterials[matIndex];
  29685. if (subMat) {
  29686. serializationObject.materials.push(subMat.id);
  29687. }
  29688. else {
  29689. serializationObject.materials.push(null);
  29690. }
  29691. }
  29692. return serializationObject;
  29693. };
  29694. var serializeTexture;
  29695. var serializeMaterial = function (material) {
  29696. var serializationObject = {};
  29697. serializationObject.name = material.name;
  29698. serializationObject.ambient = material.ambientColor.asArray();
  29699. serializationObject.diffuse = material.diffuseColor.asArray();
  29700. serializationObject.specular = material.specularColor.asArray();
  29701. serializationObject.specularPower = material.specularPower;
  29702. serializationObject.emissive = material.emissiveColor.asArray();
  29703. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  29704. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  29705. serializationObject.alpha = material.alpha;
  29706. serializationObject.id = material.id;
  29707. serializationObject.tags = BABYLON.Tags.GetTags(material);
  29708. serializationObject.backFaceCulling = material.backFaceCulling;
  29709. if (material.diffuseTexture) {
  29710. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29711. }
  29712. if (material.diffuseFresnelParameters) {
  29713. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29714. }
  29715. if (material.ambientTexture) {
  29716. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29717. }
  29718. if (material.opacityTexture) {
  29719. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29720. }
  29721. if (material.opacityFresnelParameters) {
  29722. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29723. }
  29724. if (material.reflectionTexture) {
  29725. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29726. }
  29727. if (material.reflectionFresnelParameters) {
  29728. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29729. }
  29730. if (material.emissiveTexture) {
  29731. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29732. }
  29733. if (material.lightmapTexture) {
  29734. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29735. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29736. }
  29737. if (material.emissiveFresnelParameters) {
  29738. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29739. }
  29740. if (material.specularTexture) {
  29741. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29742. }
  29743. if (material.bumpTexture) {
  29744. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29745. }
  29746. return serializationObject;
  29747. };
  29748. serializeTexture = function (texture) {
  29749. var serializationObject = {};
  29750. if (!texture.name) {
  29751. return null;
  29752. }
  29753. if (texture instanceof BABYLON.CubeTexture) {
  29754. serializationObject.name = texture.name;
  29755. serializationObject.hasAlpha = texture.hasAlpha;
  29756. serializationObject.isCube = true;
  29757. serializationObject.level = texture.level;
  29758. serializationObject.coordinatesMode = texture.coordinatesMode;
  29759. return serializationObject;
  29760. }
  29761. var index;
  29762. if (texture instanceof BABYLON.MirrorTexture) {
  29763. var mirrorTexture = texture;
  29764. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29765. serializationObject.renderList = [];
  29766. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29767. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29768. }
  29769. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29770. }
  29771. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29772. var renderTargetTexture = texture;
  29773. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29774. serializationObject.renderList = [];
  29775. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29776. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29777. }
  29778. }
  29779. var regularTexture = texture;
  29780. serializationObject.name = texture.name;
  29781. serializationObject.hasAlpha = texture.hasAlpha;
  29782. serializationObject.level = texture.level;
  29783. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29784. serializationObject.coordinatesMode = texture.coordinatesMode;
  29785. serializationObject.uOffset = regularTexture.uOffset;
  29786. serializationObject.vOffset = regularTexture.vOffset;
  29787. serializationObject.uScale = regularTexture.uScale;
  29788. serializationObject.vScale = regularTexture.vScale;
  29789. serializationObject.uAng = regularTexture.uAng;
  29790. serializationObject.vAng = regularTexture.vAng;
  29791. serializationObject.wAng = regularTexture.wAng;
  29792. serializationObject.wrapU = texture.wrapU;
  29793. serializationObject.wrapV = texture.wrapV;
  29794. // Animations
  29795. appendAnimations(texture, serializationObject);
  29796. return serializationObject;
  29797. };
  29798. var serializeSkeleton = function (skeleton) {
  29799. var serializationObject = {};
  29800. serializationObject.name = skeleton.name;
  29801. serializationObject.id = skeleton.id;
  29802. serializationObject.bones = [];
  29803. for (var index = 0; index < skeleton.bones.length; index++) {
  29804. var bone = skeleton.bones[index];
  29805. var serializedBone = {
  29806. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29807. name: bone.name,
  29808. matrix: bone.getLocalMatrix().toArray()
  29809. };
  29810. serializationObject.bones.push(serializedBone);
  29811. if (bone.animations && bone.animations.length > 0) {
  29812. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29813. }
  29814. }
  29815. return serializationObject;
  29816. };
  29817. var serializeParticleSystem = function (particleSystem) {
  29818. var serializationObject = {};
  29819. serializationObject.emitterId = particleSystem.emitter.id;
  29820. serializationObject.capacity = particleSystem.getCapacity();
  29821. if (particleSystem.particleTexture) {
  29822. serializationObject.textureName = particleSystem.particleTexture.name;
  29823. }
  29824. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29825. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29826. serializationObject.minSize = particleSystem.minSize;
  29827. serializationObject.maxSize = particleSystem.maxSize;
  29828. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29829. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29830. serializationObject.emitRate = particleSystem.emitRate;
  29831. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29832. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29833. serializationObject.gravity = particleSystem.gravity.asArray();
  29834. serializationObject.direction1 = particleSystem.direction1.asArray();
  29835. serializationObject.direction2 = particleSystem.direction2.asArray();
  29836. serializationObject.color1 = particleSystem.color1.asArray();
  29837. serializationObject.color2 = particleSystem.color2.asArray();
  29838. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29839. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29840. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29841. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29842. serializationObject.blendMode = particleSystem.blendMode;
  29843. return serializationObject;
  29844. };
  29845. var serializeLensFlareSystem = function (lensFlareSystem) {
  29846. var serializationObject = {};
  29847. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29848. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29849. serializationObject.flares = [];
  29850. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29851. var flare = lensFlareSystem.lensFlares[index];
  29852. serializationObject.flares.push({
  29853. size: flare.size,
  29854. position: flare.position,
  29855. color: flare.color.asArray(),
  29856. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29857. });
  29858. }
  29859. return serializationObject;
  29860. };
  29861. var serializeShadowGenerator = function (light) {
  29862. var serializationObject = {};
  29863. var shadowGenerator = light.getShadowGenerator();
  29864. serializationObject.lightId = light.id;
  29865. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29866. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29867. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29868. serializationObject.renderList = [];
  29869. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29870. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29871. serializationObject.renderList.push(mesh.id);
  29872. }
  29873. return serializationObject;
  29874. };
  29875. var serializedGeometries = [];
  29876. var serializeVertexData;
  29877. var serializeTorusKnot;
  29878. var serializePlane;
  29879. var serializeGround;
  29880. var serializeTorus;
  29881. var serializeCylinder;
  29882. var serializeSphere;
  29883. var serializeBox;
  29884. var serializeGeometry = function (geometry, serializationGeometries) {
  29885. if (serializedGeometries[geometry.id]) {
  29886. return;
  29887. }
  29888. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29889. serializationGeometries.boxes.push(serializeBox(geometry));
  29890. }
  29891. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29892. serializationGeometries.spheres.push(serializeSphere(geometry));
  29893. }
  29894. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29895. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29896. }
  29897. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29898. serializationGeometries.toruses.push(serializeTorus(geometry));
  29899. }
  29900. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29901. serializationGeometries.grounds.push(serializeGround(geometry));
  29902. }
  29903. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29904. serializationGeometries.planes.push(serializePlane(geometry));
  29905. }
  29906. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29907. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29908. }
  29909. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29910. throw new Error("Unknown primitive type");
  29911. }
  29912. else {
  29913. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29914. }
  29915. serializedGeometries[geometry.id] = true;
  29916. };
  29917. var serializeGeometryBase = function (geometry) {
  29918. var serializationObject = {};
  29919. serializationObject.id = geometry.id;
  29920. if (BABYLON.Tags.HasTags(geometry)) {
  29921. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29922. }
  29923. return serializationObject;
  29924. };
  29925. serializeVertexData = function (vertexData) {
  29926. var serializationObject = serializeGeometryBase(vertexData);
  29927. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29928. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29929. }
  29930. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29931. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29932. }
  29933. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29934. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29935. }
  29936. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29937. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29938. }
  29939. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29940. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29941. }
  29942. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29943. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29944. }
  29945. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29946. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29947. }
  29948. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29949. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29950. }
  29951. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29952. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29953. }
  29954. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29955. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29956. serializationObject.matricesIndices._isExpanded = true;
  29957. }
  29958. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29959. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29960. }
  29961. serializationObject.indices = vertexData.getIndices();
  29962. return serializationObject;
  29963. };
  29964. var serializePrimitive = function (primitive) {
  29965. var serializationObject = serializeGeometryBase(primitive);
  29966. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29967. return serializationObject;
  29968. };
  29969. serializeBox = function (box) {
  29970. var serializationObject = serializePrimitive(box);
  29971. serializationObject.size = box.size;
  29972. return serializationObject;
  29973. };
  29974. serializeSphere = function (sphere) {
  29975. var serializationObject = serializePrimitive(sphere);
  29976. serializationObject.segments = sphere.segments;
  29977. serializationObject.diameter = sphere.diameter;
  29978. return serializationObject;
  29979. };
  29980. serializeCylinder = function (cylinder) {
  29981. var serializationObject = serializePrimitive(cylinder);
  29982. serializationObject.height = cylinder.height;
  29983. serializationObject.diameterTop = cylinder.diameterTop;
  29984. serializationObject.diameterBottom = cylinder.diameterBottom;
  29985. serializationObject.tessellation = cylinder.tessellation;
  29986. return serializationObject;
  29987. };
  29988. serializeTorus = function (torus) {
  29989. var serializationObject = serializePrimitive(torus);
  29990. serializationObject.diameter = torus.diameter;
  29991. serializationObject.thickness = torus.thickness;
  29992. serializationObject.tessellation = torus.tessellation;
  29993. return serializationObject;
  29994. };
  29995. serializeGround = function (ground) {
  29996. var serializationObject = serializePrimitive(ground);
  29997. serializationObject.width = ground.width;
  29998. serializationObject.height = ground.height;
  29999. serializationObject.subdivisions = ground.subdivisions;
  30000. return serializationObject;
  30001. };
  30002. serializePlane = function (plane) {
  30003. var serializationObject = serializePrimitive(plane);
  30004. serializationObject.size = plane.size;
  30005. return serializationObject;
  30006. };
  30007. serializeTorusKnot = function (torusKnot) {
  30008. var serializationObject = serializePrimitive(torusKnot);
  30009. serializationObject.radius = torusKnot.radius;
  30010. serializationObject.tube = torusKnot.tube;
  30011. serializationObject.radialSegments = torusKnot.radialSegments;
  30012. serializationObject.tubularSegments = torusKnot.tubularSegments;
  30013. serializationObject.p = torusKnot.p;
  30014. serializationObject.q = torusKnot.q;
  30015. return serializationObject;
  30016. };
  30017. var serializeMesh = function (mesh, serializationScene) {
  30018. var serializationObject = {};
  30019. serializationObject.name = mesh.name;
  30020. serializationObject.id = mesh.id;
  30021. if (BABYLON.Tags.HasTags(mesh)) {
  30022. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  30023. }
  30024. serializationObject.position = mesh.position.asArray();
  30025. if (mesh.rotationQuaternion) {
  30026. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  30027. }
  30028. else if (mesh.rotation) {
  30029. serializationObject.rotation = mesh.rotation.asArray();
  30030. }
  30031. serializationObject.scaling = mesh.scaling.asArray();
  30032. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  30033. serializationObject.isEnabled = mesh.isEnabled();
  30034. serializationObject.isVisible = mesh.isVisible;
  30035. serializationObject.infiniteDistance = mesh.infiniteDistance;
  30036. serializationObject.pickable = mesh.isPickable;
  30037. serializationObject.receiveShadows = mesh.receiveShadows;
  30038. serializationObject.billboardMode = mesh.billboardMode;
  30039. serializationObject.visibility = mesh.visibility;
  30040. serializationObject.checkCollisions = mesh.checkCollisions;
  30041. // Parent
  30042. if (mesh.parent) {
  30043. serializationObject.parentId = mesh.parent.id;
  30044. }
  30045. // Geometry
  30046. var geometry = mesh._geometry;
  30047. if (geometry) {
  30048. var geometryId = geometry.id;
  30049. serializationObject.geometryId = geometryId;
  30050. if (!mesh.getScene().getGeometryByID(geometryId)) {
  30051. // 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
  30052. serializeGeometry(geometry, serializationScene.geometries);
  30053. }
  30054. // SubMeshes
  30055. serializationObject.subMeshes = [];
  30056. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30057. var subMesh = mesh.subMeshes[subIndex];
  30058. serializationObject.subMeshes.push({
  30059. materialIndex: subMesh.materialIndex,
  30060. verticesStart: subMesh.verticesStart,
  30061. verticesCount: subMesh.verticesCount,
  30062. indexStart: subMesh.indexStart,
  30063. indexCount: subMesh.indexCount
  30064. });
  30065. }
  30066. }
  30067. // Material
  30068. if (mesh.material) {
  30069. serializationObject.materialId = mesh.material.id;
  30070. }
  30071. else {
  30072. mesh.material = null;
  30073. }
  30074. // Skeleton
  30075. if (mesh.skeleton) {
  30076. serializationObject.skeletonId = mesh.skeleton.id;
  30077. }
  30078. // Physics
  30079. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  30080. serializationObject.physicsMass = mesh.getPhysicsMass();
  30081. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  30082. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  30083. switch (mesh.getPhysicsImpostor()) {
  30084. case BABYLON.PhysicsEngine.BoxImpostor:
  30085. serializationObject.physicsImpostor = 1;
  30086. break;
  30087. case BABYLON.PhysicsEngine.SphereImpostor:
  30088. serializationObject.physicsImpostor = 2;
  30089. break;
  30090. }
  30091. }
  30092. // Instances
  30093. serializationObject.instances = [];
  30094. for (var index = 0; index < mesh.instances.length; index++) {
  30095. var instance = mesh.instances[index];
  30096. var serializationInstance = {
  30097. name: instance.name,
  30098. position: instance.position.asArray(),
  30099. rotation: instance.rotation.asArray(),
  30100. rotationQuaternion: instance.rotationQuaternion.asArray(),
  30101. scaling: instance.scaling.asArray()
  30102. };
  30103. serializationObject.instances.push(serializationInstance);
  30104. // Animations
  30105. appendAnimations(instance, serializationInstance);
  30106. }
  30107. // Animations
  30108. appendAnimations(mesh, serializationObject);
  30109. // Layer mask
  30110. serializationObject.layerMask = mesh.layerMask;
  30111. return serializationObject;
  30112. };
  30113. var finalizeSingleMesh = function (mesh, serializationObject) {
  30114. //only works if the mesh is already loaded
  30115. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30116. //serialize material
  30117. if (mesh.material) {
  30118. if (mesh.material instanceof BABYLON.StandardMaterial) {
  30119. serializationObject.materials = serializationObject.materials || [];
  30120. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30121. serializationObject.materials.push(serializeMaterial(mesh.material));
  30122. }
  30123. }
  30124. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  30125. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  30126. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  30127. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  30128. }
  30129. }
  30130. }
  30131. //serialize geometry
  30132. var geometry = mesh._geometry;
  30133. if (geometry) {
  30134. if (!serializationObject.geometries) {
  30135. serializationObject.geometries = {};
  30136. serializationObject.geometries.boxes = [];
  30137. serializationObject.geometries.spheres = [];
  30138. serializationObject.geometries.cylinders = [];
  30139. serializationObject.geometries.toruses = [];
  30140. serializationObject.geometries.grounds = [];
  30141. serializationObject.geometries.planes = [];
  30142. serializationObject.geometries.torusKnots = [];
  30143. serializationObject.geometries.vertexData = [];
  30144. }
  30145. serializeGeometry(geometry, serializationObject.geometries);
  30146. }
  30147. // Skeletons
  30148. if (mesh.skeleton) {
  30149. serializationObject.skeletons = serializationObject.skeletons || [];
  30150. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  30151. }
  30152. //serialize the actual mesh
  30153. serializationObject.meshes = serializationObject.meshes || [];
  30154. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30155. }
  30156. };
  30157. var SceneSerializer = (function () {
  30158. function SceneSerializer() {
  30159. }
  30160. SceneSerializer.Serialize = function (scene) {
  30161. var serializationObject = {};
  30162. // Scene
  30163. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  30164. serializationObject.autoClear = scene.autoClear;
  30165. serializationObject.clearColor = scene.clearColor.asArray();
  30166. serializationObject.ambientColor = scene.ambientColor.asArray();
  30167. serializationObject.gravity = scene.gravity.asArray();
  30168. // Fog
  30169. if (scene.fogMode && scene.fogMode !== 0) {
  30170. serializationObject.fogMode = scene.fogMode;
  30171. serializationObject.fogColor = scene.fogColor.asArray();
  30172. serializationObject.fogStart = scene.fogStart;
  30173. serializationObject.fogEnd = scene.fogEnd;
  30174. serializationObject.fogDensity = scene.fogDensity;
  30175. }
  30176. // Lights
  30177. serializationObject.lights = [];
  30178. var index;
  30179. var light;
  30180. for (index = 0; index < scene.lights.length; index++) {
  30181. light = scene.lights[index];
  30182. serializationObject.lights.push(serializeLight(light));
  30183. }
  30184. // Cameras
  30185. serializationObject.cameras = [];
  30186. for (index = 0; index < scene.cameras.length; index++) {
  30187. var camera = scene.cameras[index];
  30188. serializationObject.cameras.push(serializeCamera(camera));
  30189. }
  30190. if (scene.activeCamera) {
  30191. serializationObject.activeCameraID = scene.activeCamera.id;
  30192. }
  30193. // Materials
  30194. serializationObject.materials = [];
  30195. serializationObject.multiMaterials = [];
  30196. var material;
  30197. for (index = 0; index < scene.materials.length; index++) {
  30198. material = scene.materials[index];
  30199. serializationObject.materials.push(serializeMaterial(material));
  30200. }
  30201. // MultiMaterials
  30202. serializationObject.multiMaterials = [];
  30203. for (index = 0; index < scene.multiMaterials.length; index++) {
  30204. var multiMaterial = scene.multiMaterials[index];
  30205. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  30206. }
  30207. for (index = 0; index < scene.materials.length; index++) {
  30208. material = scene.materials[index];
  30209. if (material instanceof BABYLON.StandardMaterial) {
  30210. serializationObject.materials.push(serializeMaterial(material));
  30211. }
  30212. else if (material instanceof BABYLON.MultiMaterial) {
  30213. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  30214. }
  30215. }
  30216. // Skeletons
  30217. serializationObject.skeletons = [];
  30218. for (index = 0; index < scene.skeletons.length; index++) {
  30219. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  30220. }
  30221. // Geometries
  30222. serializationObject.geometries = {};
  30223. serializationObject.geometries.boxes = [];
  30224. serializationObject.geometries.spheres = [];
  30225. serializationObject.geometries.cylinders = [];
  30226. serializationObject.geometries.toruses = [];
  30227. serializationObject.geometries.grounds = [];
  30228. serializationObject.geometries.planes = [];
  30229. serializationObject.geometries.torusKnots = [];
  30230. serializationObject.geometries.vertexData = [];
  30231. serializedGeometries = [];
  30232. var geometries = scene.getGeometries();
  30233. for (index = 0; index < geometries.length; index++) {
  30234. var geometry = geometries[index];
  30235. if (geometry.isReady()) {
  30236. serializeGeometry(geometry, serializationObject.geometries);
  30237. }
  30238. }
  30239. // Meshes
  30240. serializationObject.meshes = [];
  30241. for (index = 0; index < scene.meshes.length; index++) {
  30242. var abstractMesh = scene.meshes[index];
  30243. if (abstractMesh instanceof BABYLON.Mesh) {
  30244. var mesh = abstractMesh;
  30245. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  30246. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  30247. }
  30248. }
  30249. }
  30250. // Particles Systems
  30251. serializationObject.particleSystems = [];
  30252. for (index = 0; index < scene.particleSystems.length; index++) {
  30253. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  30254. }
  30255. // Lens flares
  30256. serializationObject.lensFlareSystems = [];
  30257. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  30258. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  30259. }
  30260. // Shadows
  30261. serializationObject.shadowGenerators = [];
  30262. for (index = 0; index < scene.lights.length; index++) {
  30263. light = scene.lights[index];
  30264. if (light.getShadowGenerator()) {
  30265. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  30266. }
  30267. }
  30268. return serializationObject;
  30269. };
  30270. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  30271. if (withParents === void 0) { withParents = false; }
  30272. if (withChildren === void 0) { withChildren = false; }
  30273. var serializationObject = {};
  30274. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  30275. if (withParents || withChildren) {
  30276. //deliberate for loop! not for each, appended should be processed as well.
  30277. for (var i = 0; i < toSerialize.length; ++i) {
  30278. if (withChildren) {
  30279. toSerialize[i].getDescendants().forEach(function (node) {
  30280. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  30281. toSerialize.push(node);
  30282. }
  30283. });
  30284. }
  30285. //make sure the array doesn't contain the object already
  30286. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  30287. toSerialize.push(toSerialize[i].parent);
  30288. }
  30289. }
  30290. }
  30291. toSerialize.forEach(function (mesh) {
  30292. finalizeSingleMesh(mesh, serializationObject);
  30293. });
  30294. return serializationObject;
  30295. };
  30296. return SceneSerializer;
  30297. })();
  30298. BABYLON.SceneSerializer = SceneSerializer;
  30299. })(BABYLON || (BABYLON = {}));
  30300. var BABYLON;
  30301. (function (BABYLON) {
  30302. // Unique ID when we import meshes from Babylon to CSG
  30303. var currentCSGMeshId = 0;
  30304. // # class Vertex
  30305. // Represents a vertex of a polygon. Use your own vertex class instead of this
  30306. // one to provide additional features like texture coordinates and vertex
  30307. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  30308. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  30309. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  30310. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  30311. // is not used anywhere else.
  30312. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  30313. var Vertex = (function () {
  30314. function Vertex(pos, normal, uv) {
  30315. this.pos = pos;
  30316. this.normal = normal;
  30317. this.uv = uv;
  30318. }
  30319. Vertex.prototype.clone = function () {
  30320. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  30321. };
  30322. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  30323. // orientation of a polygon is flipped.
  30324. Vertex.prototype.flip = function () {
  30325. this.normal = this.normal.scale(-1);
  30326. };
  30327. // Create a new vertex between this vertex and `other` by linearly
  30328. // interpolating all properties using a parameter of `t`. Subclasses should
  30329. // override this to interpolate additional properties.
  30330. Vertex.prototype.interpolate = function (other, t) {
  30331. 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));
  30332. };
  30333. return Vertex;
  30334. })();
  30335. // # class Plane
  30336. // Represents a plane in 3D space.
  30337. var Plane = (function () {
  30338. function Plane(normal, w) {
  30339. this.normal = normal;
  30340. this.w = w;
  30341. }
  30342. Plane.FromPoints = function (a, b, c) {
  30343. var v0 = c.subtract(a);
  30344. var v1 = b.subtract(a);
  30345. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  30346. return null;
  30347. }
  30348. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  30349. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  30350. };
  30351. Plane.prototype.clone = function () {
  30352. return new Plane(this.normal.clone(), this.w);
  30353. };
  30354. Plane.prototype.flip = function () {
  30355. this.normal.scaleInPlace(-1);
  30356. this.w = -this.w;
  30357. };
  30358. // Split `polygon` by this plane if needed, then put the polygon or polygon
  30359. // fragments in the appropriate lists. Coplanar polygons go into either
  30360. // `coplanarFront` or `coplanarBack` depending on their orientation with
  30361. // respect to this plane. Polygons in front or in back of this plane go into
  30362. // either `front` or `back`.
  30363. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  30364. var COPLANAR = 0;
  30365. var FRONT = 1;
  30366. var BACK = 2;
  30367. var SPANNING = 3;
  30368. // Classify each point as well as the entire polygon into one of the above
  30369. // four classes.
  30370. var polygonType = 0;
  30371. var types = [];
  30372. var i;
  30373. var t;
  30374. for (i = 0; i < polygon.vertices.length; i++) {
  30375. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  30376. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  30377. polygonType |= type;
  30378. types.push(type);
  30379. }
  30380. // Put the polygon in the correct list, splitting it when necessary.
  30381. switch (polygonType) {
  30382. case COPLANAR:
  30383. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  30384. break;
  30385. case FRONT:
  30386. front.push(polygon);
  30387. break;
  30388. case BACK:
  30389. back.push(polygon);
  30390. break;
  30391. case SPANNING:
  30392. var f = [], b = [];
  30393. for (i = 0; i < polygon.vertices.length; i++) {
  30394. var j = (i + 1) % polygon.vertices.length;
  30395. var ti = types[i], tj = types[j];
  30396. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  30397. if (ti !== BACK)
  30398. f.push(vi);
  30399. if (ti !== FRONT)
  30400. b.push(ti !== BACK ? vi.clone() : vi);
  30401. if ((ti | tj) === SPANNING) {
  30402. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  30403. var v = vi.interpolate(vj, t);
  30404. f.push(v);
  30405. b.push(v.clone());
  30406. }
  30407. }
  30408. var poly;
  30409. if (f.length >= 3) {
  30410. poly = new Polygon(f, polygon.shared);
  30411. if (poly.plane)
  30412. front.push(poly);
  30413. }
  30414. if (b.length >= 3) {
  30415. poly = new Polygon(b, polygon.shared);
  30416. if (poly.plane)
  30417. back.push(poly);
  30418. }
  30419. break;
  30420. }
  30421. };
  30422. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  30423. // point is on the plane.
  30424. Plane.EPSILON = 1e-5;
  30425. return Plane;
  30426. })();
  30427. // # class Polygon
  30428. // Represents a convex polygon. The vertices used to initialize a polygon must
  30429. // be coplanar and form a convex loop.
  30430. //
  30431. // Each convex polygon has a `shared` property, which is shared between all
  30432. // polygons that are clones of each other or were split from the same polygon.
  30433. // This can be used to define per-polygon properties (such as surface color).
  30434. var Polygon = (function () {
  30435. function Polygon(vertices, shared) {
  30436. this.vertices = vertices;
  30437. this.shared = shared;
  30438. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  30439. }
  30440. Polygon.prototype.clone = function () {
  30441. var vertices = this.vertices.map(function (v) { return v.clone(); });
  30442. return new Polygon(vertices, this.shared);
  30443. };
  30444. Polygon.prototype.flip = function () {
  30445. this.vertices.reverse().map(function (v) { v.flip(); });
  30446. this.plane.flip();
  30447. };
  30448. return Polygon;
  30449. })();
  30450. // # class Node
  30451. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  30452. // by picking a polygon to split along. That polygon (and all other coplanar
  30453. // polygons) are added directly to that node and the other polygons are added to
  30454. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  30455. // no distinction between internal and leaf nodes.
  30456. var Node = (function () {
  30457. function Node(polygons) {
  30458. this.plane = null;
  30459. this.front = null;
  30460. this.back = null;
  30461. this.polygons = [];
  30462. if (polygons) {
  30463. this.build(polygons);
  30464. }
  30465. }
  30466. Node.prototype.clone = function () {
  30467. var node = new Node();
  30468. node.plane = this.plane && this.plane.clone();
  30469. node.front = this.front && this.front.clone();
  30470. node.back = this.back && this.back.clone();
  30471. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  30472. return node;
  30473. };
  30474. // Convert solid space to empty space and empty space to solid space.
  30475. Node.prototype.invert = function () {
  30476. for (var i = 0; i < this.polygons.length; i++) {
  30477. this.polygons[i].flip();
  30478. }
  30479. if (this.plane) {
  30480. this.plane.flip();
  30481. }
  30482. if (this.front) {
  30483. this.front.invert();
  30484. }
  30485. if (this.back) {
  30486. this.back.invert();
  30487. }
  30488. var temp = this.front;
  30489. this.front = this.back;
  30490. this.back = temp;
  30491. };
  30492. // Recursively remove all polygons in `polygons` that are inside this BSP
  30493. // tree.
  30494. Node.prototype.clipPolygons = function (polygons) {
  30495. if (!this.plane)
  30496. return polygons.slice();
  30497. var front = [], back = [];
  30498. for (var i = 0; i < polygons.length; i++) {
  30499. this.plane.splitPolygon(polygons[i], front, back, front, back);
  30500. }
  30501. if (this.front) {
  30502. front = this.front.clipPolygons(front);
  30503. }
  30504. if (this.back) {
  30505. back = this.back.clipPolygons(back);
  30506. }
  30507. else {
  30508. back = [];
  30509. }
  30510. return front.concat(back);
  30511. };
  30512. // Remove all polygons in this BSP tree that are inside the other BSP tree
  30513. // `bsp`.
  30514. Node.prototype.clipTo = function (bsp) {
  30515. this.polygons = bsp.clipPolygons(this.polygons);
  30516. if (this.front)
  30517. this.front.clipTo(bsp);
  30518. if (this.back)
  30519. this.back.clipTo(bsp);
  30520. };
  30521. // Return a list of all polygons in this BSP tree.
  30522. Node.prototype.allPolygons = function () {
  30523. var polygons = this.polygons.slice();
  30524. if (this.front)
  30525. polygons = polygons.concat(this.front.allPolygons());
  30526. if (this.back)
  30527. polygons = polygons.concat(this.back.allPolygons());
  30528. return polygons;
  30529. };
  30530. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  30531. // new polygons are filtered down to the bottom of the tree and become new
  30532. // nodes there. Each set of polygons is partitioned using the first polygon
  30533. // (no heuristic is used to pick a good split).
  30534. Node.prototype.build = function (polygons) {
  30535. if (!polygons.length)
  30536. return;
  30537. if (!this.plane)
  30538. this.plane = polygons[0].plane.clone();
  30539. var front = [], back = [];
  30540. for (var i = 0; i < polygons.length; i++) {
  30541. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  30542. }
  30543. if (front.length) {
  30544. if (!this.front)
  30545. this.front = new Node();
  30546. this.front.build(front);
  30547. }
  30548. if (back.length) {
  30549. if (!this.back)
  30550. this.back = new Node();
  30551. this.back.build(back);
  30552. }
  30553. };
  30554. return Node;
  30555. })();
  30556. var CSG = (function () {
  30557. function CSG() {
  30558. this.polygons = new Array();
  30559. }
  30560. // Convert BABYLON.Mesh to BABYLON.CSG
  30561. CSG.FromMesh = function (mesh) {
  30562. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  30563. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  30564. if (mesh instanceof BABYLON.Mesh) {
  30565. mesh.computeWorldMatrix(true);
  30566. matrix = mesh.getWorldMatrix();
  30567. meshPosition = mesh.position.clone();
  30568. meshRotation = mesh.rotation.clone();
  30569. if (mesh.rotationQuaternion) {
  30570. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  30571. }
  30572. meshScaling = mesh.scaling.clone();
  30573. }
  30574. else {
  30575. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  30576. }
  30577. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30578. var subMeshes = mesh.subMeshes;
  30579. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  30580. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  30581. vertices = [];
  30582. for (var j = 0; j < 3; j++) {
  30583. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  30584. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  30585. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  30586. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  30587. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  30588. vertex = new Vertex(position, normal, uv);
  30589. vertices.push(vertex);
  30590. }
  30591. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  30592. // To handle the case of degenerated triangle
  30593. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  30594. if (polygon.plane)
  30595. polygons.push(polygon);
  30596. }
  30597. }
  30598. var csg = CSG.FromPolygons(polygons);
  30599. csg.matrix = matrix;
  30600. csg.position = meshPosition;
  30601. csg.rotation = meshRotation;
  30602. csg.scaling = meshScaling;
  30603. csg.rotationQuaternion = meshRotationQuaternion;
  30604. currentCSGMeshId++;
  30605. return csg;
  30606. };
  30607. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  30608. CSG.FromPolygons = function (polygons) {
  30609. var csg = new CSG();
  30610. csg.polygons = polygons;
  30611. return csg;
  30612. };
  30613. CSG.prototype.clone = function () {
  30614. var csg = new CSG();
  30615. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  30616. csg.copyTransformAttributes(this);
  30617. return csg;
  30618. };
  30619. CSG.prototype.toPolygons = function () {
  30620. return this.polygons;
  30621. };
  30622. CSG.prototype.union = function (csg) {
  30623. var a = new Node(this.clone().polygons);
  30624. var b = new Node(csg.clone().polygons);
  30625. a.clipTo(b);
  30626. b.clipTo(a);
  30627. b.invert();
  30628. b.clipTo(a);
  30629. b.invert();
  30630. a.build(b.allPolygons());
  30631. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30632. };
  30633. CSG.prototype.unionInPlace = function (csg) {
  30634. var a = new Node(this.polygons);
  30635. var b = new Node(csg.polygons);
  30636. a.clipTo(b);
  30637. b.clipTo(a);
  30638. b.invert();
  30639. b.clipTo(a);
  30640. b.invert();
  30641. a.build(b.allPolygons());
  30642. this.polygons = a.allPolygons();
  30643. };
  30644. CSG.prototype.subtract = function (csg) {
  30645. var a = new Node(this.clone().polygons);
  30646. var b = new Node(csg.clone().polygons);
  30647. a.invert();
  30648. a.clipTo(b);
  30649. b.clipTo(a);
  30650. b.invert();
  30651. b.clipTo(a);
  30652. b.invert();
  30653. a.build(b.allPolygons());
  30654. a.invert();
  30655. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30656. };
  30657. CSG.prototype.subtractInPlace = function (csg) {
  30658. var a = new Node(this.polygons);
  30659. var b = new Node(csg.polygons);
  30660. a.invert();
  30661. a.clipTo(b);
  30662. b.clipTo(a);
  30663. b.invert();
  30664. b.clipTo(a);
  30665. b.invert();
  30666. a.build(b.allPolygons());
  30667. a.invert();
  30668. this.polygons = a.allPolygons();
  30669. };
  30670. CSG.prototype.intersect = function (csg) {
  30671. var a = new Node(this.clone().polygons);
  30672. var b = new Node(csg.clone().polygons);
  30673. a.invert();
  30674. b.clipTo(a);
  30675. b.invert();
  30676. a.clipTo(b);
  30677. b.clipTo(a);
  30678. a.build(b.allPolygons());
  30679. a.invert();
  30680. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  30681. };
  30682. CSG.prototype.intersectInPlace = function (csg) {
  30683. var a = new Node(this.polygons);
  30684. var b = new Node(csg.polygons);
  30685. a.invert();
  30686. b.clipTo(a);
  30687. b.invert();
  30688. a.clipTo(b);
  30689. b.clipTo(a);
  30690. a.build(b.allPolygons());
  30691. a.invert();
  30692. this.polygons = a.allPolygons();
  30693. };
  30694. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  30695. // not modified.
  30696. CSG.prototype.inverse = function () {
  30697. var csg = this.clone();
  30698. csg.inverseInPlace();
  30699. return csg;
  30700. };
  30701. CSG.prototype.inverseInPlace = function () {
  30702. this.polygons.map(function (p) { p.flip(); });
  30703. };
  30704. // This is used to keep meshes transformations so they can be restored
  30705. // when we build back a Babylon Mesh
  30706. // NB : All CSG operations are performed in world coordinates
  30707. CSG.prototype.copyTransformAttributes = function (csg) {
  30708. this.matrix = csg.matrix;
  30709. this.position = csg.position;
  30710. this.rotation = csg.rotation;
  30711. this.scaling = csg.scaling;
  30712. this.rotationQuaternion = csg.rotationQuaternion;
  30713. return this;
  30714. };
  30715. // Build Raw mesh from CSG
  30716. // Coordinates here are in world space
  30717. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30718. var matrix = this.matrix.clone();
  30719. matrix.invert();
  30720. 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;
  30721. if (keepSubMeshes) {
  30722. // Sort Polygons, since subMeshes are indices range
  30723. polygons.sort(function (a, b) {
  30724. if (a.shared.meshId === b.shared.meshId) {
  30725. return a.shared.subMeshId - b.shared.subMeshId;
  30726. }
  30727. else {
  30728. return a.shared.meshId - b.shared.meshId;
  30729. }
  30730. });
  30731. }
  30732. for (var i = 0, il = polygons.length; i < il; i++) {
  30733. polygon = polygons[i];
  30734. // Building SubMeshes
  30735. if (!subMesh_dict[polygon.shared.meshId]) {
  30736. subMesh_dict[polygon.shared.meshId] = {};
  30737. }
  30738. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30739. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30740. indexStart: +Infinity,
  30741. indexEnd: -Infinity,
  30742. materialIndex: polygon.shared.materialIndex
  30743. };
  30744. }
  30745. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30746. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30747. polygonIndices[0] = 0;
  30748. polygonIndices[1] = j - 1;
  30749. polygonIndices[2] = j;
  30750. for (var k = 0; k < 3; k++) {
  30751. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30752. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30753. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30754. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30755. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30756. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30757. // Check if 2 points can be merged
  30758. if (!(typeof vertex_idx !== 'undefined' &&
  30759. normals[vertex_idx * 3] === localNormal.x &&
  30760. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30761. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30762. uvs[vertex_idx * 2] === uv.x &&
  30763. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30764. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30765. uvs.push(uv.x, uv.y);
  30766. normals.push(normal.x, normal.y, normal.z);
  30767. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30768. }
  30769. indices.push(vertex_idx);
  30770. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30771. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30772. currentIndex++;
  30773. }
  30774. }
  30775. }
  30776. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30777. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30778. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30779. mesh.setIndices(indices);
  30780. if (keepSubMeshes) {
  30781. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30782. var materialIndexOffset = 0, materialMaxIndex;
  30783. mesh.subMeshes = new Array();
  30784. for (var m in subMesh_dict) {
  30785. materialMaxIndex = -1;
  30786. for (var sm in subMesh_dict[m]) {
  30787. subMesh_obj = subMesh_dict[m][sm];
  30788. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30789. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30790. }
  30791. materialIndexOffset += ++materialMaxIndex;
  30792. }
  30793. }
  30794. return mesh;
  30795. };
  30796. // Build Mesh from CSG taking material and transforms into account
  30797. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30798. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30799. mesh.material = material;
  30800. mesh.position.copyFrom(this.position);
  30801. mesh.rotation.copyFrom(this.rotation);
  30802. if (this.rotationQuaternion) {
  30803. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30804. }
  30805. mesh.scaling.copyFrom(this.scaling);
  30806. mesh.computeWorldMatrix(true);
  30807. return mesh;
  30808. };
  30809. return CSG;
  30810. })();
  30811. BABYLON.CSG = CSG;
  30812. })(BABYLON || (BABYLON = {}));
  30813. var BABYLON;
  30814. (function (BABYLON) {
  30815. var VRDistortionCorrectionPostProcess = (function (_super) {
  30816. __extends(VRDistortionCorrectionPostProcess, _super);
  30817. //ANY
  30818. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30819. var _this = this;
  30820. _super.call(this, name, "vrDistortionCorrection", [
  30821. 'LensCenter',
  30822. 'Scale',
  30823. 'ScaleIn',
  30824. 'HmdWarpParam'
  30825. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30826. this._isRightEye = isRightEye;
  30827. this._distortionFactors = vrMetrics.distortionK;
  30828. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30829. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30830. this.onSizeChanged = function () {
  30831. _this.aspectRatio = _this.width * .5 / _this.height;
  30832. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30833. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30834. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30835. };
  30836. this.onApply = function (effect) {
  30837. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30838. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30839. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30840. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30841. };
  30842. }
  30843. return VRDistortionCorrectionPostProcess;
  30844. })(BABYLON.PostProcess);
  30845. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30846. })(BABYLON || (BABYLON = {}));
  30847. // Mainly based on these 2 articles :
  30848. // 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
  30849. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30850. var BABYLON;
  30851. (function (BABYLON) {
  30852. (function (JoystickAxis) {
  30853. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30854. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30855. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30856. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30857. var JoystickAxis = BABYLON.JoystickAxis;
  30858. var VirtualJoystick = (function () {
  30859. function VirtualJoystick(leftJoystick) {
  30860. var _this = this;
  30861. if (leftJoystick) {
  30862. this._leftJoystick = true;
  30863. }
  30864. else {
  30865. this._leftJoystick = false;
  30866. }
  30867. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30868. VirtualJoystick._globalJoystickIndex++;
  30869. // By default left & right arrow keys are moving the X
  30870. // and up & down keys are moving the Y
  30871. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30872. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30873. this.reverseLeftRight = false;
  30874. this.reverseUpDown = false;
  30875. // collections of pointers
  30876. this._touches = new BABYLON.SmartCollection();
  30877. this.deltaPosition = BABYLON.Vector3.Zero();
  30878. this._joystickSensibility = 25;
  30879. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30880. this._rotationSpeed = 25;
  30881. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30882. this._rotateOnAxisRelativeToMesh = false;
  30883. this._onResize = function (evt) {
  30884. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30885. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30886. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30887. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30888. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30889. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30890. };
  30891. // injecting a canvas element on top of the canvas 3D game
  30892. if (!VirtualJoystick.vjCanvas) {
  30893. window.addEventListener("resize", this._onResize, false);
  30894. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30895. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30896. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30897. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30898. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30899. VirtualJoystick.vjCanvas.style.width = "100%";
  30900. VirtualJoystick.vjCanvas.style.height = "100%";
  30901. VirtualJoystick.vjCanvas.style.position = "absolute";
  30902. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30903. VirtualJoystick.vjCanvas.style.top = "0px";
  30904. VirtualJoystick.vjCanvas.style.left = "0px";
  30905. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30906. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30907. // Support for jQuery PEP polyfill
  30908. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30909. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30910. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30911. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30912. document.body.appendChild(VirtualJoystick.vjCanvas);
  30913. }
  30914. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30915. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30916. this.pressed = false;
  30917. // default joystick color
  30918. this._joystickColor = "cyan";
  30919. this._joystickPointerID = -1;
  30920. // current joystick position
  30921. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30922. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30923. // origin joystick position
  30924. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30925. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30926. this._onPointerDownHandlerRef = function (evt) {
  30927. _this._onPointerDown(evt);
  30928. };
  30929. this._onPointerMoveHandlerRef = function (evt) {
  30930. _this._onPointerMove(evt);
  30931. };
  30932. this._onPointerOutHandlerRef = function (evt) {
  30933. _this._onPointerUp(evt);
  30934. };
  30935. this._onPointerUpHandlerRef = function (evt) {
  30936. _this._onPointerUp(evt);
  30937. };
  30938. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30939. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30940. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30941. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30942. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30943. evt.preventDefault(); // Disables system menu
  30944. }, false);
  30945. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30946. }
  30947. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30948. this._joystickSensibility = newJoystickSensibility;
  30949. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30950. };
  30951. VirtualJoystick.prototype._onPointerDown = function (e) {
  30952. var positionOnScreenCondition;
  30953. e.preventDefault();
  30954. if (this._leftJoystick === true) {
  30955. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30956. }
  30957. else {
  30958. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30959. }
  30960. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30961. // First contact will be dedicated to the virtual joystick
  30962. this._joystickPointerID = e.pointerId;
  30963. this._joystickPointerStartPos.x = e.clientX;
  30964. this._joystickPointerStartPos.y = e.clientY;
  30965. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30966. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30967. this._deltaJoystickVector.x = 0;
  30968. this._deltaJoystickVector.y = 0;
  30969. this.pressed = true;
  30970. this._touches.add(e.pointerId.toString(), e);
  30971. }
  30972. else {
  30973. // You can only trigger the action buttons with a joystick declared
  30974. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30975. this._action();
  30976. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30977. }
  30978. }
  30979. };
  30980. VirtualJoystick.prototype._onPointerMove = function (e) {
  30981. // If the current pointer is the one associated to the joystick (first touch contact)
  30982. if (this._joystickPointerID == e.pointerId) {
  30983. this._joystickPointerPos.x = e.clientX;
  30984. this._joystickPointerPos.y = e.clientY;
  30985. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30986. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30987. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30988. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30989. switch (this._axisTargetedByLeftAndRight) {
  30990. case JoystickAxis.X:
  30991. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30992. break;
  30993. case JoystickAxis.Y:
  30994. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30995. break;
  30996. case JoystickAxis.Z:
  30997. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30998. break;
  30999. }
  31000. var directionUpDown = this.reverseUpDown ? 1 : -1;
  31001. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  31002. switch (this._axisTargetedByUpAndDown) {
  31003. case JoystickAxis.X:
  31004. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  31005. break;
  31006. case JoystickAxis.Y:
  31007. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  31008. break;
  31009. case JoystickAxis.Z:
  31010. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  31011. break;
  31012. }
  31013. }
  31014. else {
  31015. if (this._touches.item(e.pointerId.toString())) {
  31016. this._touches.item(e.pointerId.toString()).x = e.clientX;
  31017. this._touches.item(e.pointerId.toString()).y = e.clientY;
  31018. }
  31019. }
  31020. };
  31021. VirtualJoystick.prototype._onPointerUp = function (e) {
  31022. if (this._joystickPointerID == e.pointerId) {
  31023. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  31024. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  31025. this._joystickPointerID = -1;
  31026. this.pressed = false;
  31027. }
  31028. else {
  31029. var touch = this._touches.item(e.pointerId.toString());
  31030. if (touch) {
  31031. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31032. }
  31033. }
  31034. this._deltaJoystickVector.x = 0;
  31035. this._deltaJoystickVector.y = 0;
  31036. this._touches.remove(e.pointerId.toString());
  31037. };
  31038. /**
  31039. * Change the color of the virtual joystick
  31040. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  31041. */
  31042. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  31043. this._joystickColor = newColor;
  31044. };
  31045. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  31046. this._action = action;
  31047. };
  31048. // Define which axis you'd like to control for left & right
  31049. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  31050. switch (axis) {
  31051. case JoystickAxis.X:
  31052. case JoystickAxis.Y:
  31053. case JoystickAxis.Z:
  31054. this._axisTargetedByLeftAndRight = axis;
  31055. break;
  31056. default:
  31057. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  31058. break;
  31059. }
  31060. };
  31061. // Define which axis you'd like to control for up & down
  31062. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  31063. switch (axis) {
  31064. case JoystickAxis.X:
  31065. case JoystickAxis.Y:
  31066. case JoystickAxis.Z:
  31067. this._axisTargetedByUpAndDown = axis;
  31068. break;
  31069. default:
  31070. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  31071. break;
  31072. }
  31073. };
  31074. VirtualJoystick.prototype._clearCanvas = function () {
  31075. if (this._leftJoystick) {
  31076. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  31077. }
  31078. else {
  31079. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  31080. }
  31081. };
  31082. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  31083. var _this = this;
  31084. if (this.pressed) {
  31085. this._touches.forEach(function (touch) {
  31086. if (touch.pointerId === _this._joystickPointerID) {
  31087. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  31088. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  31089. VirtualJoystick.vjCanvasContext.beginPath();
  31090. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31091. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31092. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  31093. VirtualJoystick.vjCanvasContext.stroke();
  31094. VirtualJoystick.vjCanvasContext.closePath();
  31095. VirtualJoystick.vjCanvasContext.beginPath();
  31096. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31097. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  31098. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  31099. VirtualJoystick.vjCanvasContext.stroke();
  31100. VirtualJoystick.vjCanvasContext.closePath();
  31101. VirtualJoystick.vjCanvasContext.beginPath();
  31102. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  31103. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  31104. VirtualJoystick.vjCanvasContext.stroke();
  31105. VirtualJoystick.vjCanvasContext.closePath();
  31106. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  31107. }
  31108. else {
  31109. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  31110. VirtualJoystick.vjCanvasContext.beginPath();
  31111. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  31112. VirtualJoystick.vjCanvasContext.beginPath();
  31113. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  31114. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  31115. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  31116. VirtualJoystick.vjCanvasContext.stroke();
  31117. VirtualJoystick.vjCanvasContext.closePath();
  31118. touch.prevX = touch.x;
  31119. touch.prevY = touch.y;
  31120. }
  31121. ;
  31122. });
  31123. }
  31124. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  31125. };
  31126. VirtualJoystick.prototype.releaseCanvas = function () {
  31127. if (VirtualJoystick.vjCanvas) {
  31128. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  31129. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  31130. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  31131. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  31132. window.removeEventListener("resize", this._onResize);
  31133. document.body.removeChild(VirtualJoystick.vjCanvas);
  31134. VirtualJoystick.vjCanvas = null;
  31135. }
  31136. };
  31137. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  31138. VirtualJoystick._globalJoystickIndex = 0;
  31139. return VirtualJoystick;
  31140. })();
  31141. BABYLON.VirtualJoystick = VirtualJoystick;
  31142. })(BABYLON || (BABYLON = {}));
  31143. var BABYLON;
  31144. (function (BABYLON) {
  31145. // We're mainly based on the logic defined into the FreeCamera code
  31146. var VirtualJoysticksCamera = (function (_super) {
  31147. __extends(VirtualJoysticksCamera, _super);
  31148. function VirtualJoysticksCamera(name, position, scene) {
  31149. _super.call(this, name, position, scene);
  31150. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  31151. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  31152. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  31153. this._leftjoystick.setJoystickSensibility(0.15);
  31154. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  31155. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  31156. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  31157. this._rightjoystick.reverseUpDown = true;
  31158. this._rightjoystick.setJoystickSensibility(0.05);
  31159. this._rightjoystick.setJoystickColor("yellow");
  31160. }
  31161. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  31162. return this._leftjoystick;
  31163. };
  31164. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  31165. return this._rightjoystick;
  31166. };
  31167. VirtualJoysticksCamera.prototype._checkInputs = function () {
  31168. var speed = this._computeLocalCameraSpeed() * 50;
  31169. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  31170. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  31171. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  31172. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  31173. if (!this._leftjoystick.pressed) {
  31174. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  31175. }
  31176. if (!this._rightjoystick.pressed) {
  31177. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  31178. }
  31179. _super.prototype._checkInputs.call(this);
  31180. };
  31181. VirtualJoysticksCamera.prototype.dispose = function () {
  31182. this._leftjoystick.releaseCanvas();
  31183. _super.prototype.dispose.call(this);
  31184. };
  31185. return VirtualJoysticksCamera;
  31186. })(BABYLON.FreeCamera);
  31187. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  31188. })(BABYLON || (BABYLON = {}));
  31189. var BABYLON;
  31190. (function (BABYLON) {
  31191. var AnaglyphPostProcess = (function (_super) {
  31192. __extends(AnaglyphPostProcess, _super);
  31193. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31194. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  31195. }
  31196. return AnaglyphPostProcess;
  31197. })(BABYLON.PostProcess);
  31198. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  31199. })(BABYLON || (BABYLON = {}));
  31200. var BABYLON;
  31201. (function (BABYLON) {
  31202. var OutlineRenderer = (function () {
  31203. function OutlineRenderer(scene) {
  31204. this._scene = scene;
  31205. }
  31206. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  31207. var _this = this;
  31208. if (useOverlay === void 0) { useOverlay = false; }
  31209. var scene = this._scene;
  31210. var engine = this._scene.getEngine();
  31211. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31212. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  31213. return;
  31214. }
  31215. var mesh = subMesh.getRenderingMesh();
  31216. var material = subMesh.getMaterial();
  31217. engine.enableEffect(this._effect);
  31218. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  31219. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  31220. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31221. // Bones
  31222. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31223. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31224. }
  31225. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  31226. // Alpha test
  31227. if (material && material.needAlphaTesting()) {
  31228. var alphaTexture = material.getAlphaTestTexture();
  31229. this._effect.setTexture("diffuseSampler", alphaTexture);
  31230. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31231. }
  31232. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  31233. };
  31234. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  31235. var defines = [];
  31236. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  31237. var mesh = subMesh.getMesh();
  31238. var material = subMesh.getMaterial();
  31239. // Alpha test
  31240. if (material && material.needAlphaTesting()) {
  31241. defines.push("#define ALPHATEST");
  31242. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31243. attribs.push(BABYLON.VertexBuffer.UVKind);
  31244. defines.push("#define UV1");
  31245. }
  31246. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31247. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31248. defines.push("#define UV2");
  31249. }
  31250. }
  31251. // Bones
  31252. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31253. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31254. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31255. if (mesh.numBoneInfluencers > 4) {
  31256. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31257. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  31258. }
  31259. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  31260. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31261. }
  31262. else {
  31263. defines.push("#define NUM_BONE_INFLUENCERS 0");
  31264. }
  31265. // Instances
  31266. if (useInstances) {
  31267. defines.push("#define INSTANCES");
  31268. attribs.push("world0");
  31269. attribs.push("world1");
  31270. attribs.push("world2");
  31271. attribs.push("world3");
  31272. }
  31273. // Get correct effect
  31274. var join = defines.join("\n");
  31275. if (this._cachedDefines !== join) {
  31276. this._cachedDefines = join;
  31277. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  31278. }
  31279. return this._effect.isReady();
  31280. };
  31281. return OutlineRenderer;
  31282. })();
  31283. BABYLON.OutlineRenderer = OutlineRenderer;
  31284. })(BABYLON || (BABYLON = {}));
  31285. var BABYLON;
  31286. (function (BABYLON) {
  31287. var MeshAssetTask = (function () {
  31288. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  31289. this.name = name;
  31290. this.meshesNames = meshesNames;
  31291. this.rootUrl = rootUrl;
  31292. this.sceneFilename = sceneFilename;
  31293. this.isCompleted = false;
  31294. }
  31295. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31296. var _this = this;
  31297. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  31298. _this.loadedMeshes = meshes;
  31299. _this.loadedParticleSystems = particleSystems;
  31300. _this.loadedSkeletons = skeletons;
  31301. _this.isCompleted = true;
  31302. if (_this.onSuccess) {
  31303. _this.onSuccess(_this);
  31304. }
  31305. onSuccess();
  31306. }, null, function () {
  31307. if (_this.onError) {
  31308. _this.onError(_this);
  31309. }
  31310. onError();
  31311. });
  31312. };
  31313. return MeshAssetTask;
  31314. })();
  31315. BABYLON.MeshAssetTask = MeshAssetTask;
  31316. var TextFileAssetTask = (function () {
  31317. function TextFileAssetTask(name, url) {
  31318. this.name = name;
  31319. this.url = url;
  31320. this.isCompleted = false;
  31321. }
  31322. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31323. var _this = this;
  31324. BABYLON.Tools.LoadFile(this.url, function (data) {
  31325. _this.text = data;
  31326. _this.isCompleted = true;
  31327. if (_this.onSuccess) {
  31328. _this.onSuccess(_this);
  31329. }
  31330. onSuccess();
  31331. }, null, scene.database, false, function () {
  31332. if (_this.onError) {
  31333. _this.onError(_this);
  31334. }
  31335. onError();
  31336. });
  31337. };
  31338. return TextFileAssetTask;
  31339. })();
  31340. BABYLON.TextFileAssetTask = TextFileAssetTask;
  31341. var BinaryFileAssetTask = (function () {
  31342. function BinaryFileAssetTask(name, url) {
  31343. this.name = name;
  31344. this.url = url;
  31345. this.isCompleted = false;
  31346. }
  31347. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31348. var _this = this;
  31349. BABYLON.Tools.LoadFile(this.url, function (data) {
  31350. _this.data = data;
  31351. _this.isCompleted = true;
  31352. if (_this.onSuccess) {
  31353. _this.onSuccess(_this);
  31354. }
  31355. onSuccess();
  31356. }, null, scene.database, true, function () {
  31357. if (_this.onError) {
  31358. _this.onError(_this);
  31359. }
  31360. onError();
  31361. });
  31362. };
  31363. return BinaryFileAssetTask;
  31364. })();
  31365. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  31366. var ImageAssetTask = (function () {
  31367. function ImageAssetTask(name, url) {
  31368. this.name = name;
  31369. this.url = url;
  31370. this.isCompleted = false;
  31371. }
  31372. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31373. var _this = this;
  31374. var img = new Image();
  31375. img.onload = function () {
  31376. _this.image = img;
  31377. _this.isCompleted = true;
  31378. if (_this.onSuccess) {
  31379. _this.onSuccess(_this);
  31380. }
  31381. onSuccess();
  31382. };
  31383. img.onerror = function () {
  31384. if (_this.onError) {
  31385. _this.onError(_this);
  31386. }
  31387. onError();
  31388. };
  31389. img.src = this.url;
  31390. };
  31391. return ImageAssetTask;
  31392. })();
  31393. BABYLON.ImageAssetTask = ImageAssetTask;
  31394. var TextureAssetTask = (function () {
  31395. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  31396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31397. this.name = name;
  31398. this.url = url;
  31399. this.noMipmap = noMipmap;
  31400. this.invertY = invertY;
  31401. this.samplingMode = samplingMode;
  31402. this.isCompleted = false;
  31403. }
  31404. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  31405. var _this = this;
  31406. var onload = function () {
  31407. _this.isCompleted = true;
  31408. if (_this.onSuccess) {
  31409. _this.onSuccess(_this);
  31410. }
  31411. onSuccess();
  31412. };
  31413. var onerror = function () {
  31414. if (_this.onError) {
  31415. _this.onError(_this);
  31416. }
  31417. onError();
  31418. };
  31419. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  31420. };
  31421. return TextureAssetTask;
  31422. })();
  31423. BABYLON.TextureAssetTask = TextureAssetTask;
  31424. var AssetsManager = (function () {
  31425. function AssetsManager(scene) {
  31426. this._tasks = new Array();
  31427. this._waitingTasksCount = 0;
  31428. this.useDefaultLoadingScreen = true;
  31429. this._scene = scene;
  31430. }
  31431. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  31432. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  31433. this._tasks.push(task);
  31434. return task;
  31435. };
  31436. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  31437. var task = new TextFileAssetTask(taskName, url);
  31438. this._tasks.push(task);
  31439. return task;
  31440. };
  31441. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  31442. var task = new BinaryFileAssetTask(taskName, url);
  31443. this._tasks.push(task);
  31444. return task;
  31445. };
  31446. AssetsManager.prototype.addImageTask = function (taskName, url) {
  31447. var task = new ImageAssetTask(taskName, url);
  31448. this._tasks.push(task);
  31449. return task;
  31450. };
  31451. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  31452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31453. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  31454. this._tasks.push(task);
  31455. return task;
  31456. };
  31457. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  31458. this._waitingTasksCount--;
  31459. if (this._waitingTasksCount === 0) {
  31460. if (this.onFinish) {
  31461. this.onFinish(this._tasks);
  31462. }
  31463. this._scene.getEngine().hideLoadingUI();
  31464. }
  31465. };
  31466. AssetsManager.prototype._runTask = function (task) {
  31467. var _this = this;
  31468. task.run(this._scene, function () {
  31469. if (_this.onTaskSuccess) {
  31470. _this.onTaskSuccess(task);
  31471. }
  31472. _this._decreaseWaitingTasksCount();
  31473. }, function () {
  31474. if (_this.onTaskError) {
  31475. _this.onTaskError(task);
  31476. }
  31477. _this._decreaseWaitingTasksCount();
  31478. });
  31479. };
  31480. AssetsManager.prototype.reset = function () {
  31481. this._tasks = new Array();
  31482. return this;
  31483. };
  31484. AssetsManager.prototype.load = function () {
  31485. this._waitingTasksCount = this._tasks.length;
  31486. if (this._waitingTasksCount === 0) {
  31487. if (this.onFinish) {
  31488. this.onFinish(this._tasks);
  31489. }
  31490. return this;
  31491. }
  31492. if (this.useDefaultLoadingScreen) {
  31493. this._scene.getEngine().displayLoadingUI();
  31494. }
  31495. for (var index = 0; index < this._tasks.length; index++) {
  31496. var task = this._tasks[index];
  31497. this._runTask(task);
  31498. }
  31499. return this;
  31500. };
  31501. return AssetsManager;
  31502. })();
  31503. BABYLON.AssetsManager = AssetsManager;
  31504. })(BABYLON || (BABYLON = {}));
  31505. var BABYLON;
  31506. (function (BABYLON) {
  31507. var VRDeviceOrientationFreeCamera = (function (_super) {
  31508. __extends(VRDeviceOrientationFreeCamera, _super);
  31509. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  31510. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31511. _super.call(this, name, position, scene);
  31512. this._alpha = 0;
  31513. this._beta = 0;
  31514. this._gamma = 0;
  31515. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31516. metrics.compensateDistortion = compensateDistortion;
  31517. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31518. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  31519. }
  31520. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  31521. this._alpha = +evt.alpha | 0;
  31522. this._beta = +evt.beta | 0;
  31523. this._gamma = +evt.gamma | 0;
  31524. if (this._gamma < 0) {
  31525. this._gamma = 90 + this._gamma;
  31526. }
  31527. else {
  31528. // Incline it in the correct angle.
  31529. this._gamma = 270 - this._gamma;
  31530. }
  31531. this.rotation.x = this._gamma / 180.0 * Math.PI;
  31532. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  31533. this.rotation.z = this._beta / 180.0 * Math.PI;
  31534. };
  31535. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31536. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31537. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  31538. };
  31539. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  31540. _super.prototype.detachControl.call(this, element);
  31541. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  31542. };
  31543. return VRDeviceOrientationFreeCamera;
  31544. })(BABYLON.FreeCamera);
  31545. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  31546. })(BABYLON || (BABYLON = {}));
  31547. var BABYLON;
  31548. (function (BABYLON) {
  31549. var WebVRFreeCamera = (function (_super) {
  31550. __extends(WebVRFreeCamera, _super);
  31551. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  31552. if (compensateDistortion === void 0) { compensateDistortion = true; }
  31553. _super.call(this, name, position, scene);
  31554. this._hmdDevice = null;
  31555. this._sensorDevice = null;
  31556. this._cacheState = null;
  31557. this._cacheQuaternion = new BABYLON.Quaternion();
  31558. this._cacheRotation = BABYLON.Vector3.Zero();
  31559. this._vrEnabled = false;
  31560. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  31561. metrics.compensateDistortion = compensateDistortion;
  31562. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  31563. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  31564. }
  31565. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  31566. var size = devices.length;
  31567. var i = 0;
  31568. // Reset devices.
  31569. this._sensorDevice = null;
  31570. this._hmdDevice = null;
  31571. // Search for a HmdDevice.
  31572. while (i < size && this._hmdDevice === null) {
  31573. if (devices[i] instanceof HMDVRDevice) {
  31574. this._hmdDevice = devices[i];
  31575. }
  31576. i++;
  31577. }
  31578. i = 0;
  31579. while (i < size && this._sensorDevice === null) {
  31580. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  31581. this._sensorDevice = devices[i];
  31582. }
  31583. i++;
  31584. }
  31585. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  31586. };
  31587. WebVRFreeCamera.prototype._checkInputs = function () {
  31588. if (this._vrEnabled) {
  31589. this._cacheState = this._sensorDevice.getState();
  31590. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  31591. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  31592. this.rotation.x = -this._cacheRotation.z;
  31593. this.rotation.y = -this._cacheRotation.y;
  31594. this.rotation.z = this._cacheRotation.x;
  31595. }
  31596. _super.prototype._checkInputs.call(this);
  31597. };
  31598. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  31599. _super.prototype.attachControl.call(this, element, noPreventDefault);
  31600. if (navigator.getVRDevices) {
  31601. navigator.getVRDevices().then(this._getWebVRDevices);
  31602. }
  31603. else if (navigator.mozGetVRDevices) {
  31604. navigator.mozGetVRDevices(this._getWebVRDevices);
  31605. }
  31606. };
  31607. WebVRFreeCamera.prototype.detachControl = function (element) {
  31608. _super.prototype.detachControl.call(this, element);
  31609. this._vrEnabled = false;
  31610. };
  31611. return WebVRFreeCamera;
  31612. })(BABYLON.FreeCamera);
  31613. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  31614. })(BABYLON || (BABYLON = {}));
  31615. var BABYLON;
  31616. (function (BABYLON) {
  31617. // Standard optimizations
  31618. var SceneOptimization = (function () {
  31619. function SceneOptimization(priority) {
  31620. if (priority === void 0) { priority = 0; }
  31621. this.priority = priority;
  31622. this.apply = function (scene) {
  31623. return true; // Return true if everything that can be done was applied
  31624. };
  31625. }
  31626. return SceneOptimization;
  31627. })();
  31628. BABYLON.SceneOptimization = SceneOptimization;
  31629. var TextureOptimization = (function (_super) {
  31630. __extends(TextureOptimization, _super);
  31631. function TextureOptimization(priority, maximumSize) {
  31632. var _this = this;
  31633. if (priority === void 0) { priority = 0; }
  31634. if (maximumSize === void 0) { maximumSize = 1024; }
  31635. _super.call(this, priority);
  31636. this.priority = priority;
  31637. this.maximumSize = maximumSize;
  31638. this.apply = function (scene) {
  31639. var allDone = true;
  31640. for (var index = 0; index < scene.textures.length; index++) {
  31641. var texture = scene.textures[index];
  31642. if (!texture.canRescale) {
  31643. continue;
  31644. }
  31645. var currentSize = texture.getSize();
  31646. var maxDimension = Math.max(currentSize.width, currentSize.height);
  31647. if (maxDimension > _this.maximumSize) {
  31648. texture.scale(0.5);
  31649. allDone = false;
  31650. }
  31651. }
  31652. return allDone;
  31653. };
  31654. }
  31655. return TextureOptimization;
  31656. })(SceneOptimization);
  31657. BABYLON.TextureOptimization = TextureOptimization;
  31658. var HardwareScalingOptimization = (function (_super) {
  31659. __extends(HardwareScalingOptimization, _super);
  31660. function HardwareScalingOptimization(priority, maximumScale) {
  31661. var _this = this;
  31662. if (priority === void 0) { priority = 0; }
  31663. if (maximumScale === void 0) { maximumScale = 2; }
  31664. _super.call(this, priority);
  31665. this.priority = priority;
  31666. this.maximumScale = maximumScale;
  31667. this._currentScale = 1;
  31668. this.apply = function (scene) {
  31669. _this._currentScale++;
  31670. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  31671. return _this._currentScale >= _this.maximumScale;
  31672. };
  31673. }
  31674. return HardwareScalingOptimization;
  31675. })(SceneOptimization);
  31676. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  31677. var ShadowsOptimization = (function (_super) {
  31678. __extends(ShadowsOptimization, _super);
  31679. function ShadowsOptimization() {
  31680. _super.apply(this, arguments);
  31681. this.apply = function (scene) {
  31682. scene.shadowsEnabled = false;
  31683. return true;
  31684. };
  31685. }
  31686. return ShadowsOptimization;
  31687. })(SceneOptimization);
  31688. BABYLON.ShadowsOptimization = ShadowsOptimization;
  31689. var PostProcessesOptimization = (function (_super) {
  31690. __extends(PostProcessesOptimization, _super);
  31691. function PostProcessesOptimization() {
  31692. _super.apply(this, arguments);
  31693. this.apply = function (scene) {
  31694. scene.postProcessesEnabled = false;
  31695. return true;
  31696. };
  31697. }
  31698. return PostProcessesOptimization;
  31699. })(SceneOptimization);
  31700. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  31701. var LensFlaresOptimization = (function (_super) {
  31702. __extends(LensFlaresOptimization, _super);
  31703. function LensFlaresOptimization() {
  31704. _super.apply(this, arguments);
  31705. this.apply = function (scene) {
  31706. scene.lensFlaresEnabled = false;
  31707. return true;
  31708. };
  31709. }
  31710. return LensFlaresOptimization;
  31711. })(SceneOptimization);
  31712. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  31713. var ParticlesOptimization = (function (_super) {
  31714. __extends(ParticlesOptimization, _super);
  31715. function ParticlesOptimization() {
  31716. _super.apply(this, arguments);
  31717. this.apply = function (scene) {
  31718. scene.particlesEnabled = false;
  31719. return true;
  31720. };
  31721. }
  31722. return ParticlesOptimization;
  31723. })(SceneOptimization);
  31724. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31725. var RenderTargetsOptimization = (function (_super) {
  31726. __extends(RenderTargetsOptimization, _super);
  31727. function RenderTargetsOptimization() {
  31728. _super.apply(this, arguments);
  31729. this.apply = function (scene) {
  31730. scene.renderTargetsEnabled = false;
  31731. return true;
  31732. };
  31733. }
  31734. return RenderTargetsOptimization;
  31735. })(SceneOptimization);
  31736. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31737. var MergeMeshesOptimization = (function (_super) {
  31738. __extends(MergeMeshesOptimization, _super);
  31739. function MergeMeshesOptimization() {
  31740. var _this = this;
  31741. _super.apply(this, arguments);
  31742. this._canBeMerged = function (abstractMesh) {
  31743. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31744. return false;
  31745. }
  31746. var mesh = abstractMesh;
  31747. if (!mesh.isVisible || !mesh.isEnabled()) {
  31748. return false;
  31749. }
  31750. if (mesh.instances.length > 0) {
  31751. return false;
  31752. }
  31753. if (mesh.skeleton || mesh.hasLODLevels) {
  31754. return false;
  31755. }
  31756. if (mesh.parent) {
  31757. return false;
  31758. }
  31759. return true;
  31760. };
  31761. this.apply = function (scene, updateSelectionTree) {
  31762. var globalPool = scene.meshes.slice(0);
  31763. var globalLength = globalPool.length;
  31764. for (var index = 0; index < globalLength; index++) {
  31765. var currentPool = new Array();
  31766. var current = globalPool[index];
  31767. // Checks
  31768. if (!_this._canBeMerged(current)) {
  31769. continue;
  31770. }
  31771. currentPool.push(current);
  31772. // Find compatible meshes
  31773. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31774. var otherMesh = globalPool[subIndex];
  31775. if (!_this._canBeMerged(otherMesh)) {
  31776. continue;
  31777. }
  31778. if (otherMesh.material !== current.material) {
  31779. continue;
  31780. }
  31781. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31782. continue;
  31783. }
  31784. currentPool.push(otherMesh);
  31785. globalLength--;
  31786. globalPool.splice(subIndex, 1);
  31787. subIndex--;
  31788. }
  31789. if (currentPool.length < 2) {
  31790. continue;
  31791. }
  31792. // Merge meshes
  31793. BABYLON.Mesh.MergeMeshes(currentPool);
  31794. }
  31795. if (updateSelectionTree != undefined) {
  31796. if (updateSelectionTree) {
  31797. scene.createOrUpdateSelectionOctree();
  31798. }
  31799. }
  31800. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31801. scene.createOrUpdateSelectionOctree();
  31802. }
  31803. return true;
  31804. };
  31805. }
  31806. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31807. get: function () {
  31808. return MergeMeshesOptimization._UpdateSelectionTree;
  31809. },
  31810. set: function (value) {
  31811. MergeMeshesOptimization._UpdateSelectionTree = value;
  31812. },
  31813. enumerable: true,
  31814. configurable: true
  31815. });
  31816. MergeMeshesOptimization._UpdateSelectionTree = false;
  31817. return MergeMeshesOptimization;
  31818. })(SceneOptimization);
  31819. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31820. // Options
  31821. var SceneOptimizerOptions = (function () {
  31822. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31823. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31824. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31825. this.targetFrameRate = targetFrameRate;
  31826. this.trackerDuration = trackerDuration;
  31827. this.optimizations = new Array();
  31828. }
  31829. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31830. var result = new SceneOptimizerOptions(targetFrameRate);
  31831. var priority = 0;
  31832. result.optimizations.push(new MergeMeshesOptimization(priority));
  31833. result.optimizations.push(new ShadowsOptimization(priority));
  31834. result.optimizations.push(new LensFlaresOptimization(priority));
  31835. // Next priority
  31836. priority++;
  31837. result.optimizations.push(new PostProcessesOptimization(priority));
  31838. result.optimizations.push(new ParticlesOptimization(priority));
  31839. // Next priority
  31840. priority++;
  31841. result.optimizations.push(new TextureOptimization(priority, 1024));
  31842. return result;
  31843. };
  31844. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31845. var result = new SceneOptimizerOptions(targetFrameRate);
  31846. var priority = 0;
  31847. result.optimizations.push(new MergeMeshesOptimization(priority));
  31848. result.optimizations.push(new ShadowsOptimization(priority));
  31849. result.optimizations.push(new LensFlaresOptimization(priority));
  31850. // Next priority
  31851. priority++;
  31852. result.optimizations.push(new PostProcessesOptimization(priority));
  31853. result.optimizations.push(new ParticlesOptimization(priority));
  31854. // Next priority
  31855. priority++;
  31856. result.optimizations.push(new TextureOptimization(priority, 512));
  31857. // Next priority
  31858. priority++;
  31859. result.optimizations.push(new RenderTargetsOptimization(priority));
  31860. // Next priority
  31861. priority++;
  31862. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31863. return result;
  31864. };
  31865. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31866. var result = new SceneOptimizerOptions(targetFrameRate);
  31867. var priority = 0;
  31868. result.optimizations.push(new MergeMeshesOptimization(priority));
  31869. result.optimizations.push(new ShadowsOptimization(priority));
  31870. result.optimizations.push(new LensFlaresOptimization(priority));
  31871. // Next priority
  31872. priority++;
  31873. result.optimizations.push(new PostProcessesOptimization(priority));
  31874. result.optimizations.push(new ParticlesOptimization(priority));
  31875. // Next priority
  31876. priority++;
  31877. result.optimizations.push(new TextureOptimization(priority, 256));
  31878. // Next priority
  31879. priority++;
  31880. result.optimizations.push(new RenderTargetsOptimization(priority));
  31881. // Next priority
  31882. priority++;
  31883. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31884. return result;
  31885. };
  31886. return SceneOptimizerOptions;
  31887. })();
  31888. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31889. // Scene optimizer tool
  31890. var SceneOptimizer = (function () {
  31891. function SceneOptimizer() {
  31892. }
  31893. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31894. // TODO: add an epsilon
  31895. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31896. if (onSuccess) {
  31897. onSuccess();
  31898. }
  31899. return;
  31900. }
  31901. // Apply current level of optimizations
  31902. var allDone = true;
  31903. var noOptimizationApplied = true;
  31904. for (var index = 0; index < options.optimizations.length; index++) {
  31905. var optimization = options.optimizations[index];
  31906. if (optimization.priority === currentPriorityLevel) {
  31907. noOptimizationApplied = false;
  31908. allDone = allDone && optimization.apply(scene);
  31909. }
  31910. }
  31911. // If no optimization was applied, this is a failure :(
  31912. if (noOptimizationApplied) {
  31913. if (onFailure) {
  31914. onFailure();
  31915. }
  31916. return;
  31917. }
  31918. // If all optimizations were done, move to next level
  31919. if (allDone) {
  31920. currentPriorityLevel++;
  31921. }
  31922. // Let's the system running for a specific amount of time before checking FPS
  31923. scene.executeWhenReady(function () {
  31924. setTimeout(function () {
  31925. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31926. }, options.trackerDuration);
  31927. });
  31928. };
  31929. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31930. if (!options) {
  31931. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31932. }
  31933. // Let's the system running for a specific amount of time before checking FPS
  31934. scene.executeWhenReady(function () {
  31935. setTimeout(function () {
  31936. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31937. }, options.trackerDuration);
  31938. });
  31939. };
  31940. return SceneOptimizer;
  31941. })();
  31942. BABYLON.SceneOptimizer = SceneOptimizer;
  31943. })(BABYLON || (BABYLON = {}));
  31944. var BABYLON;
  31945. (function (BABYLON) {
  31946. var Internals;
  31947. (function (Internals) {
  31948. var MeshLODLevel = (function () {
  31949. function MeshLODLevel(distance, mesh) {
  31950. this.distance = distance;
  31951. this.mesh = mesh;
  31952. }
  31953. return MeshLODLevel;
  31954. })();
  31955. Internals.MeshLODLevel = MeshLODLevel;
  31956. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31957. })(BABYLON || (BABYLON = {}));
  31958. var BABYLON;
  31959. (function (BABYLON) {
  31960. var RawTexture = (function (_super) {
  31961. __extends(RawTexture, _super);
  31962. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31963. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31964. if (invertY === void 0) { invertY = false; }
  31965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31966. _super.call(this, null, scene, !generateMipMaps, invertY);
  31967. this.format = format;
  31968. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31969. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31970. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31971. }
  31972. RawTexture.prototype.update = function (data) {
  31973. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31974. };
  31975. // Statics
  31976. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31977. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31978. if (invertY === void 0) { invertY = false; }
  31979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31980. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31981. };
  31982. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31983. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31984. if (invertY === void 0) { invertY = false; }
  31985. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31986. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31987. };
  31988. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31989. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31990. if (invertY === void 0) { invertY = false; }
  31991. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31992. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31993. };
  31994. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31995. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31996. if (invertY === void 0) { invertY = false; }
  31997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31998. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31999. };
  32000. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32001. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32002. if (invertY === void 0) { invertY = false; }
  32003. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32004. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32005. };
  32006. return RawTexture;
  32007. })(BABYLON.Texture);
  32008. BABYLON.RawTexture = RawTexture;
  32009. })(BABYLON || (BABYLON = {}));
  32010. var BABYLON;
  32011. (function (BABYLON) {
  32012. var IndexedVector2 = (function (_super) {
  32013. __extends(IndexedVector2, _super);
  32014. function IndexedVector2(original, index) {
  32015. _super.call(this, original.x, original.y);
  32016. this.index = index;
  32017. }
  32018. return IndexedVector2;
  32019. })(BABYLON.Vector2);
  32020. var PolygonPoints = (function () {
  32021. function PolygonPoints() {
  32022. this.elements = new Array();
  32023. }
  32024. PolygonPoints.prototype.add = function (originalPoints) {
  32025. var _this = this;
  32026. var result = new Array();
  32027. originalPoints.forEach(function (point) {
  32028. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  32029. var newPoint = new IndexedVector2(point, _this.elements.length);
  32030. result.push(newPoint);
  32031. _this.elements.push(newPoint);
  32032. }
  32033. });
  32034. return result;
  32035. };
  32036. PolygonPoints.prototype.computeBounds = function () {
  32037. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32038. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  32039. this.elements.forEach(function (point) {
  32040. // x
  32041. if (point.x < lmin.x) {
  32042. lmin.x = point.x;
  32043. }
  32044. else if (point.x > lmax.x) {
  32045. lmax.x = point.x;
  32046. }
  32047. // y
  32048. if (point.y < lmin.y) {
  32049. lmin.y = point.y;
  32050. }
  32051. else if (point.y > lmax.y) {
  32052. lmax.y = point.y;
  32053. }
  32054. });
  32055. return {
  32056. min: lmin,
  32057. max: lmax,
  32058. width: lmax.x - lmin.x,
  32059. height: lmax.y - lmin.y
  32060. };
  32061. };
  32062. return PolygonPoints;
  32063. })();
  32064. var Polygon = (function () {
  32065. function Polygon() {
  32066. }
  32067. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  32068. return [
  32069. new BABYLON.Vector2(xmin, ymin),
  32070. new BABYLON.Vector2(xmax, ymin),
  32071. new BABYLON.Vector2(xmax, ymax),
  32072. new BABYLON.Vector2(xmin, ymax)
  32073. ];
  32074. };
  32075. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  32076. if (cx === void 0) { cx = 0; }
  32077. if (cy === void 0) { cy = 0; }
  32078. if (numberOfSides === void 0) { numberOfSides = 32; }
  32079. var result = new Array();
  32080. var angle = 0;
  32081. var increment = (Math.PI * 2) / numberOfSides;
  32082. for (var i = 0; i < numberOfSides; i++) {
  32083. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  32084. angle -= increment;
  32085. }
  32086. return result;
  32087. };
  32088. Polygon.Parse = function (input) {
  32089. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  32090. var i, result = [];
  32091. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  32092. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  32093. }
  32094. return result;
  32095. };
  32096. Polygon.StartingAt = function (x, y) {
  32097. return BABYLON.Path2.StartingAt(x, y);
  32098. };
  32099. return Polygon;
  32100. })();
  32101. BABYLON.Polygon = Polygon;
  32102. var PolygonMeshBuilder = (function () {
  32103. function PolygonMeshBuilder(name, contours, scene) {
  32104. this._points = new PolygonPoints();
  32105. this._outlinepoints = new PolygonPoints();
  32106. this._holes = [];
  32107. if (!("poly2tri" in window)) {
  32108. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  32109. }
  32110. this._name = name;
  32111. this._scene = scene;
  32112. var points;
  32113. if (contours instanceof BABYLON.Path2) {
  32114. points = contours.getPoints();
  32115. }
  32116. else {
  32117. points = contours;
  32118. }
  32119. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  32120. this._outlinepoints.add(points);
  32121. }
  32122. PolygonMeshBuilder.prototype.addHole = function (hole) {
  32123. this._swctx.addHole(this._points.add(hole));
  32124. var holepoints = new PolygonPoints();
  32125. holepoints.add(hole);
  32126. this._holes.push(holepoints);
  32127. return this;
  32128. };
  32129. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  32130. var _this = this;
  32131. if (updatable === void 0) { updatable = false; }
  32132. var result = new BABYLON.Mesh(this._name, this._scene);
  32133. var normals = [];
  32134. var positions = [];
  32135. var uvs = [];
  32136. var bounds = this._points.computeBounds();
  32137. this._points.elements.forEach(function (p) {
  32138. normals.push(0, 1.0, 0);
  32139. positions.push(p.x, 0, p.y);
  32140. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  32141. });
  32142. var indices = [];
  32143. this._swctx.triangulate();
  32144. this._swctx.getTriangles().forEach(function (triangle) {
  32145. triangle.getPoints().forEach(function (point) {
  32146. indices.push(point.index);
  32147. });
  32148. });
  32149. if (depth > 0) {
  32150. var positionscount = (positions.length / 3); //get the current pointcount
  32151. this._points.elements.forEach(function (p) {
  32152. normals.push(0, -1.0, 0);
  32153. positions.push(p.x, -depth, p.y);
  32154. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  32155. });
  32156. var p1; //we need to change order of point so the triangles are made in the rigth way.
  32157. var p2;
  32158. var poscounter = 0;
  32159. this._swctx.getTriangles().forEach(function (triangle) {
  32160. triangle.getPoints().forEach(function (point) {
  32161. switch (poscounter) {
  32162. case 0:
  32163. p1 = point;
  32164. break;
  32165. case 1:
  32166. p2 = point;
  32167. break;
  32168. case 2:
  32169. indices.push(point.index + positionscount);
  32170. indices.push(p2.index + positionscount);
  32171. indices.push(p1.index + positionscount);
  32172. poscounter = -1;
  32173. break;
  32174. }
  32175. poscounter++;
  32176. //indices.push((<IndexedVector2>point).index + positionscount);
  32177. });
  32178. });
  32179. //Add the sides
  32180. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  32181. this._holes.forEach(function (hole) {
  32182. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  32183. });
  32184. }
  32185. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  32186. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  32187. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  32188. result.setIndices(indices);
  32189. return result;
  32190. };
  32191. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  32192. var StartIndex = positions.length / 3;
  32193. var ulength = 0;
  32194. for (var i = 0; i < points.elements.length; i++) {
  32195. var p = points.elements[i];
  32196. var p1;
  32197. if ((i + 1) > points.elements.length - 1) {
  32198. p1 = points.elements[0];
  32199. }
  32200. else {
  32201. p1 = points.elements[i + 1];
  32202. }
  32203. positions.push(p.x, 0, p.y);
  32204. positions.push(p.x, -depth, p.y);
  32205. positions.push(p1.x, 0, p1.y);
  32206. positions.push(p1.x, -depth, p1.y);
  32207. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  32208. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  32209. var v3 = v2.subtract(v1);
  32210. var v4 = new BABYLON.Vector3(0, 1, 0);
  32211. var vn = BABYLON.Vector3.Cross(v3, v4);
  32212. vn = vn.normalize();
  32213. uvs.push(ulength / bounds.width, 0);
  32214. uvs.push(ulength / bounds.width, 1);
  32215. ulength += v3.length();
  32216. uvs.push((ulength / bounds.width), 0);
  32217. uvs.push((ulength / bounds.width), 1);
  32218. if (!flip) {
  32219. normals.push(-vn.x, -vn.y, -vn.z);
  32220. normals.push(-vn.x, -vn.y, -vn.z);
  32221. normals.push(-vn.x, -vn.y, -vn.z);
  32222. normals.push(-vn.x, -vn.y, -vn.z);
  32223. indices.push(StartIndex);
  32224. indices.push(StartIndex + 1);
  32225. indices.push(StartIndex + 2);
  32226. indices.push(StartIndex + 1);
  32227. indices.push(StartIndex + 3);
  32228. indices.push(StartIndex + 2);
  32229. }
  32230. else {
  32231. normals.push(vn.x, vn.y, vn.z);
  32232. normals.push(vn.x, vn.y, vn.z);
  32233. normals.push(vn.x, vn.y, vn.z);
  32234. normals.push(vn.x, vn.y, vn.z);
  32235. indices.push(StartIndex);
  32236. indices.push(StartIndex + 2);
  32237. indices.push(StartIndex + 1);
  32238. indices.push(StartIndex + 1);
  32239. indices.push(StartIndex + 2);
  32240. indices.push(StartIndex + 3);
  32241. }
  32242. StartIndex += 4;
  32243. }
  32244. ;
  32245. };
  32246. return PolygonMeshBuilder;
  32247. })();
  32248. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  32249. })(BABYLON || (BABYLON = {}));
  32250. var BABYLON;
  32251. (function (BABYLON) {
  32252. var Octree = (function () {
  32253. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  32254. if (maxDepth === void 0) { maxDepth = 2; }
  32255. this.maxDepth = maxDepth;
  32256. this.dynamicContent = new Array();
  32257. this._maxBlockCapacity = maxBlockCapacity || 64;
  32258. this._selectionContent = new BABYLON.SmartArray(1024);
  32259. this._creationFunc = creationFunc;
  32260. }
  32261. // Methods
  32262. Octree.prototype.update = function (worldMin, worldMax, entries) {
  32263. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  32264. };
  32265. Octree.prototype.addMesh = function (entry) {
  32266. for (var index = 0; index < this.blocks.length; index++) {
  32267. var block = this.blocks[index];
  32268. block.addEntry(entry);
  32269. }
  32270. };
  32271. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  32272. this._selectionContent.reset();
  32273. for (var index = 0; index < this.blocks.length; index++) {
  32274. var block = this.blocks[index];
  32275. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  32276. }
  32277. if (allowDuplicate) {
  32278. this._selectionContent.concat(this.dynamicContent);
  32279. }
  32280. else {
  32281. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32282. }
  32283. return this._selectionContent;
  32284. };
  32285. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  32286. this._selectionContent.reset();
  32287. for (var index = 0; index < this.blocks.length; index++) {
  32288. var block = this.blocks[index];
  32289. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  32290. }
  32291. if (allowDuplicate) {
  32292. this._selectionContent.concat(this.dynamicContent);
  32293. }
  32294. else {
  32295. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32296. }
  32297. return this._selectionContent;
  32298. };
  32299. Octree.prototype.intersectsRay = function (ray) {
  32300. this._selectionContent.reset();
  32301. for (var index = 0; index < this.blocks.length; index++) {
  32302. var block = this.blocks[index];
  32303. block.intersectsRay(ray, this._selectionContent);
  32304. }
  32305. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  32306. return this._selectionContent;
  32307. };
  32308. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  32309. target.blocks = new Array();
  32310. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  32311. // Segmenting space
  32312. for (var x = 0; x < 2; x++) {
  32313. for (var y = 0; y < 2; y++) {
  32314. for (var z = 0; z < 2; z++) {
  32315. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  32316. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  32317. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  32318. block.addEntries(entries);
  32319. target.blocks.push(block);
  32320. }
  32321. }
  32322. }
  32323. };
  32324. Octree.CreationFuncForMeshes = function (entry, block) {
  32325. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32326. block.entries.push(entry);
  32327. }
  32328. };
  32329. Octree.CreationFuncForSubMeshes = function (entry, block) {
  32330. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  32331. block.entries.push(entry);
  32332. }
  32333. };
  32334. return Octree;
  32335. })();
  32336. BABYLON.Octree = Octree;
  32337. })(BABYLON || (BABYLON = {}));
  32338. var BABYLON;
  32339. (function (BABYLON) {
  32340. var OctreeBlock = (function () {
  32341. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  32342. this.entries = new Array();
  32343. this._boundingVectors = new Array();
  32344. this._capacity = capacity;
  32345. this._depth = depth;
  32346. this._maxDepth = maxDepth;
  32347. this._creationFunc = creationFunc;
  32348. this._minPoint = minPoint;
  32349. this._maxPoint = maxPoint;
  32350. this._boundingVectors.push(minPoint.clone());
  32351. this._boundingVectors.push(maxPoint.clone());
  32352. this._boundingVectors.push(minPoint.clone());
  32353. this._boundingVectors[2].x = maxPoint.x;
  32354. this._boundingVectors.push(minPoint.clone());
  32355. this._boundingVectors[3].y = maxPoint.y;
  32356. this._boundingVectors.push(minPoint.clone());
  32357. this._boundingVectors[4].z = maxPoint.z;
  32358. this._boundingVectors.push(maxPoint.clone());
  32359. this._boundingVectors[5].z = minPoint.z;
  32360. this._boundingVectors.push(maxPoint.clone());
  32361. this._boundingVectors[6].x = minPoint.x;
  32362. this._boundingVectors.push(maxPoint.clone());
  32363. this._boundingVectors[7].y = minPoint.y;
  32364. }
  32365. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  32366. // Property
  32367. get: function () {
  32368. return this._capacity;
  32369. },
  32370. enumerable: true,
  32371. configurable: true
  32372. });
  32373. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  32374. get: function () {
  32375. return this._minPoint;
  32376. },
  32377. enumerable: true,
  32378. configurable: true
  32379. });
  32380. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  32381. get: function () {
  32382. return this._maxPoint;
  32383. },
  32384. enumerable: true,
  32385. configurable: true
  32386. });
  32387. // Methods
  32388. OctreeBlock.prototype.addEntry = function (entry) {
  32389. if (this.blocks) {
  32390. for (var index = 0; index < this.blocks.length; index++) {
  32391. var block = this.blocks[index];
  32392. block.addEntry(entry);
  32393. }
  32394. return;
  32395. }
  32396. this._creationFunc(entry, this);
  32397. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  32398. this.createInnerBlocks();
  32399. }
  32400. };
  32401. OctreeBlock.prototype.addEntries = function (entries) {
  32402. for (var index = 0; index < entries.length; index++) {
  32403. var mesh = entries[index];
  32404. this.addEntry(mesh);
  32405. }
  32406. };
  32407. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  32408. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  32409. if (this.blocks) {
  32410. for (var index = 0; index < this.blocks.length; index++) {
  32411. var block = this.blocks[index];
  32412. block.select(frustumPlanes, selection, allowDuplicate);
  32413. }
  32414. return;
  32415. }
  32416. if (allowDuplicate) {
  32417. selection.concat(this.entries);
  32418. }
  32419. else {
  32420. selection.concatWithNoDuplicate(this.entries);
  32421. }
  32422. }
  32423. };
  32424. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  32425. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  32426. if (this.blocks) {
  32427. for (var index = 0; index < this.blocks.length; index++) {
  32428. var block = this.blocks[index];
  32429. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  32430. }
  32431. return;
  32432. }
  32433. if (allowDuplicate) {
  32434. selection.concat(this.entries);
  32435. }
  32436. else {
  32437. selection.concatWithNoDuplicate(this.entries);
  32438. }
  32439. }
  32440. };
  32441. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  32442. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  32443. if (this.blocks) {
  32444. for (var index = 0; index < this.blocks.length; index++) {
  32445. var block = this.blocks[index];
  32446. block.intersectsRay(ray, selection);
  32447. }
  32448. return;
  32449. }
  32450. selection.concatWithNoDuplicate(this.entries);
  32451. }
  32452. };
  32453. OctreeBlock.prototype.createInnerBlocks = function () {
  32454. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  32455. };
  32456. return OctreeBlock;
  32457. })();
  32458. BABYLON.OctreeBlock = OctreeBlock;
  32459. })(BABYLON || (BABYLON = {}));
  32460. var BABYLON;
  32461. (function (BABYLON) {
  32462. var BlurPostProcess = (function (_super) {
  32463. __extends(BlurPostProcess, _super);
  32464. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  32465. var _this = this;
  32466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32467. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  32468. this.direction = direction;
  32469. this.blurWidth = blurWidth;
  32470. this.onApply = function (effect) {
  32471. effect.setFloat2("screenSize", _this.width, _this.height);
  32472. effect.setVector2("direction", _this.direction);
  32473. effect.setFloat("blurWidth", _this.blurWidth);
  32474. };
  32475. }
  32476. return BlurPostProcess;
  32477. })(BABYLON.PostProcess);
  32478. BABYLON.BlurPostProcess = BlurPostProcess;
  32479. })(BABYLON || (BABYLON = {}));
  32480. var BABYLON;
  32481. (function (BABYLON) {
  32482. var RefractionPostProcess = (function (_super) {
  32483. __extends(RefractionPostProcess, _super);
  32484. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  32485. var _this = this;
  32486. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  32487. this.color = color;
  32488. this.depth = depth;
  32489. this.colorLevel = colorLevel;
  32490. this.onActivate = function (cam) {
  32491. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  32492. };
  32493. this.onApply = function (effect) {
  32494. effect.setColor3("baseColor", _this.color);
  32495. effect.setFloat("depth", _this.depth);
  32496. effect.setFloat("colorLevel", _this.colorLevel);
  32497. effect.setTexture("refractionSampler", _this._refRexture);
  32498. };
  32499. }
  32500. // Methods
  32501. RefractionPostProcess.prototype.dispose = function (camera) {
  32502. if (this._refRexture) {
  32503. this._refRexture.dispose();
  32504. }
  32505. _super.prototype.dispose.call(this, camera);
  32506. };
  32507. return RefractionPostProcess;
  32508. })(BABYLON.PostProcess);
  32509. BABYLON.RefractionPostProcess = RefractionPostProcess;
  32510. })(BABYLON || (BABYLON = {}));
  32511. var BABYLON;
  32512. (function (BABYLON) {
  32513. var BlackAndWhitePostProcess = (function (_super) {
  32514. __extends(BlackAndWhitePostProcess, _super);
  32515. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32516. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  32517. }
  32518. return BlackAndWhitePostProcess;
  32519. })(BABYLON.PostProcess);
  32520. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  32521. })(BABYLON || (BABYLON = {}));
  32522. var BABYLON;
  32523. (function (BABYLON) {
  32524. var ConvolutionPostProcess = (function (_super) {
  32525. __extends(ConvolutionPostProcess, _super);
  32526. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  32527. var _this = this;
  32528. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  32529. this.kernel = kernel;
  32530. this.onApply = function (effect) {
  32531. effect.setFloat2("screenSize", _this.width, _this.height);
  32532. effect.setArray("kernel", _this.kernel);
  32533. };
  32534. }
  32535. // Statics
  32536. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  32537. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  32538. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  32539. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  32540. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  32541. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  32542. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  32543. return ConvolutionPostProcess;
  32544. })(BABYLON.PostProcess);
  32545. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  32546. })(BABYLON || (BABYLON = {}));
  32547. var BABYLON;
  32548. (function (BABYLON) {
  32549. var FilterPostProcess = (function (_super) {
  32550. __extends(FilterPostProcess, _super);
  32551. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  32552. var _this = this;
  32553. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  32554. this.kernelMatrix = kernelMatrix;
  32555. this.onApply = function (effect) {
  32556. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  32557. };
  32558. }
  32559. return FilterPostProcess;
  32560. })(BABYLON.PostProcess);
  32561. BABYLON.FilterPostProcess = FilterPostProcess;
  32562. })(BABYLON || (BABYLON = {}));
  32563. var BABYLON;
  32564. (function (BABYLON) {
  32565. var FxaaPostProcess = (function (_super) {
  32566. __extends(FxaaPostProcess, _super);
  32567. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32568. var _this = this;
  32569. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  32570. this.onSizeChanged = function () {
  32571. _this.texelWidth = 1.0 / _this.width;
  32572. _this.texelHeight = 1.0 / _this.height;
  32573. };
  32574. this.onApply = function (effect) {
  32575. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  32576. };
  32577. }
  32578. return FxaaPostProcess;
  32579. })(BABYLON.PostProcess);
  32580. BABYLON.FxaaPostProcess = FxaaPostProcess;
  32581. })(BABYLON || (BABYLON = {}));
  32582. var BABYLON;
  32583. (function (BABYLON) {
  32584. var StereoscopicInterlacePostProcess = (function (_super) {
  32585. __extends(StereoscopicInterlacePostProcess, _super);
  32586. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  32587. var _this = this;
  32588. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  32589. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  32590. this.onSizeChanged = function () {
  32591. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  32592. };
  32593. this.onApply = function (effect) {
  32594. effect.setTextureFromPostProcess("camASampler", postProcessA);
  32595. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  32596. };
  32597. }
  32598. return StereoscopicInterlacePostProcess;
  32599. })(BABYLON.PostProcess);
  32600. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  32601. })(BABYLON || (BABYLON = {}));
  32602. var BABYLON;
  32603. (function (BABYLON) {
  32604. var LensFlare = (function () {
  32605. function LensFlare(size, position, color, imgUrl, system) {
  32606. this.size = size;
  32607. this.position = position;
  32608. this.dispose = function () {
  32609. if (this.texture) {
  32610. this.texture.dispose();
  32611. }
  32612. // Remove from scene
  32613. var index = this._system.lensFlares.indexOf(this);
  32614. this._system.lensFlares.splice(index, 1);
  32615. };
  32616. this.color = color || new BABYLON.Color3(1, 1, 1);
  32617. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  32618. this._system = system;
  32619. system.lensFlares.push(this);
  32620. }
  32621. return LensFlare;
  32622. })();
  32623. BABYLON.LensFlare = LensFlare;
  32624. })(BABYLON || (BABYLON = {}));
  32625. var BABYLON;
  32626. (function (BABYLON) {
  32627. var LensFlareSystem = (function () {
  32628. function LensFlareSystem(name, emitter, scene) {
  32629. this.name = name;
  32630. this.lensFlares = new Array();
  32631. this.borderLimit = 300;
  32632. this.layerMask = 0x0FFFFFFF;
  32633. this._vertexDeclaration = [2];
  32634. this._vertexStrideSize = 2 * 4;
  32635. this._isEnabled = true;
  32636. this._scene = scene;
  32637. this._emitter = emitter;
  32638. scene.lensFlareSystems.push(this);
  32639. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  32640. // VBO
  32641. var vertices = [];
  32642. vertices.push(1, 1);
  32643. vertices.push(-1, 1);
  32644. vertices.push(-1, -1);
  32645. vertices.push(1, -1);
  32646. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  32647. // Indices
  32648. var indices = [];
  32649. indices.push(0);
  32650. indices.push(1);
  32651. indices.push(2);
  32652. indices.push(0);
  32653. indices.push(2);
  32654. indices.push(3);
  32655. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32656. // Effects
  32657. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  32658. }
  32659. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  32660. get: function () {
  32661. return this._isEnabled;
  32662. },
  32663. set: function (value) {
  32664. this._isEnabled = value;
  32665. },
  32666. enumerable: true,
  32667. configurable: true
  32668. });
  32669. LensFlareSystem.prototype.getScene = function () {
  32670. return this._scene;
  32671. };
  32672. LensFlareSystem.prototype.getEmitter = function () {
  32673. return this._emitter;
  32674. };
  32675. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  32676. this._emitter = newEmitter;
  32677. };
  32678. LensFlareSystem.prototype.getEmitterPosition = function () {
  32679. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  32680. };
  32681. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  32682. var position = this.getEmitterPosition();
  32683. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  32684. this._positionX = position.x;
  32685. this._positionY = position.y;
  32686. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  32687. if (position.z > 0) {
  32688. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  32689. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  32690. return true;
  32691. }
  32692. }
  32693. return false;
  32694. };
  32695. LensFlareSystem.prototype._isVisible = function () {
  32696. if (!this._isEnabled) {
  32697. return false;
  32698. }
  32699. var emitterPosition = this.getEmitterPosition();
  32700. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  32701. var distance = direction.length();
  32702. direction.normalize();
  32703. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  32704. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  32705. return !pickInfo.hit || pickInfo.distance > distance;
  32706. };
  32707. LensFlareSystem.prototype.render = function () {
  32708. if (!this._effect.isReady())
  32709. return false;
  32710. var engine = this._scene.getEngine();
  32711. var viewport = this._scene.activeCamera.viewport;
  32712. var globalViewport = viewport.toGlobal(engine);
  32713. // Position
  32714. if (!this.computeEffectivePosition(globalViewport)) {
  32715. return false;
  32716. }
  32717. // Visibility
  32718. if (!this._isVisible()) {
  32719. return false;
  32720. }
  32721. // Intensity
  32722. var awayX;
  32723. var awayY;
  32724. if (this._positionX < this.borderLimit + globalViewport.x) {
  32725. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32726. }
  32727. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32728. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32729. }
  32730. else {
  32731. awayX = 0;
  32732. }
  32733. if (this._positionY < this.borderLimit + globalViewport.y) {
  32734. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32735. }
  32736. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32737. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32738. }
  32739. else {
  32740. awayY = 0;
  32741. }
  32742. var away = (awayX > awayY) ? awayX : awayY;
  32743. if (away > this.borderLimit) {
  32744. away = this.borderLimit;
  32745. }
  32746. var intensity = 1.0 - (away / this.borderLimit);
  32747. if (intensity < 0) {
  32748. return false;
  32749. }
  32750. if (intensity > 1.0) {
  32751. intensity = 1.0;
  32752. }
  32753. // Position
  32754. var centerX = globalViewport.x + globalViewport.width / 2;
  32755. var centerY = globalViewport.y + globalViewport.height / 2;
  32756. var distX = centerX - this._positionX;
  32757. var distY = centerY - this._positionY;
  32758. // Effects
  32759. engine.enableEffect(this._effect);
  32760. engine.setState(false);
  32761. engine.setDepthBuffer(false);
  32762. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32763. // VBOs
  32764. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32765. // Flares
  32766. for (var index = 0; index < this.lensFlares.length; index++) {
  32767. var flare = this.lensFlares[index];
  32768. var x = centerX - (distX * flare.position);
  32769. var y = centerY - (distY * flare.position);
  32770. var cw = flare.size;
  32771. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32772. var cx = 2 * (x / globalViewport.width) - 1.0;
  32773. var cy = 1.0 - 2 * (y / globalViewport.height);
  32774. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32775. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32776. // Texture
  32777. this._effect.setTexture("textureSampler", flare.texture);
  32778. // Color
  32779. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32780. // Draw order
  32781. engine.draw(true, 0, 6);
  32782. }
  32783. engine.setDepthBuffer(true);
  32784. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32785. return true;
  32786. };
  32787. LensFlareSystem.prototype.dispose = function () {
  32788. if (this._vertexBuffer) {
  32789. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32790. this._vertexBuffer = null;
  32791. }
  32792. if (this._indexBuffer) {
  32793. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32794. this._indexBuffer = null;
  32795. }
  32796. while (this.lensFlares.length) {
  32797. this.lensFlares[0].dispose();
  32798. }
  32799. // Remove from scene
  32800. var index = this._scene.lensFlareSystems.indexOf(this);
  32801. this._scene.lensFlareSystems.splice(index, 1);
  32802. };
  32803. return LensFlareSystem;
  32804. })();
  32805. BABYLON.LensFlareSystem = LensFlareSystem;
  32806. })(BABYLON || (BABYLON = {}));
  32807. var BABYLON;
  32808. (function (BABYLON) {
  32809. // We're mainly based on the logic defined into the FreeCamera code
  32810. var DeviceOrientationCamera = (function (_super) {
  32811. __extends(DeviceOrientationCamera, _super);
  32812. function DeviceOrientationCamera(name, position, scene) {
  32813. var _this = this;
  32814. _super.call(this, name, position, scene);
  32815. this._offsetX = null;
  32816. this._offsetY = null;
  32817. this._orientationGamma = 0;
  32818. this._orientationBeta = 0;
  32819. this._initialOrientationGamma = 0;
  32820. this._initialOrientationBeta = 0;
  32821. this.angularSensibility = 10000.0;
  32822. this.moveSensibility = 50.0;
  32823. window.addEventListener("resize", function () {
  32824. _this._initialOrientationGamma = null;
  32825. }, false);
  32826. }
  32827. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32828. var _this = this;
  32829. if (this._attachedCanvas) {
  32830. return;
  32831. }
  32832. this._attachedCanvas = canvas;
  32833. if (!this._orientationChanged) {
  32834. this._orientationChanged = function (evt) {
  32835. if (!_this._initialOrientationGamma) {
  32836. _this._initialOrientationGamma = evt.gamma;
  32837. _this._initialOrientationBeta = evt.beta;
  32838. }
  32839. _this._orientationGamma = evt.gamma;
  32840. _this._orientationBeta = evt.beta;
  32841. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32842. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32843. };
  32844. }
  32845. window.addEventListener("deviceorientation", this._orientationChanged);
  32846. };
  32847. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32848. if (this._attachedCanvas != canvas) {
  32849. return;
  32850. }
  32851. window.removeEventListener("deviceorientation", this._orientationChanged);
  32852. this._attachedCanvas = null;
  32853. this._orientationGamma = 0;
  32854. this._orientationBeta = 0;
  32855. this._initialOrientationGamma = 0;
  32856. this._initialOrientationBeta = 0;
  32857. };
  32858. DeviceOrientationCamera.prototype._checkInputs = function () {
  32859. if (!this._offsetX) {
  32860. return;
  32861. }
  32862. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32863. var speed = this._computeLocalCameraSpeed();
  32864. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32865. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32866. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32867. _super.prototype._checkInputs.call(this);
  32868. };
  32869. return DeviceOrientationCamera;
  32870. })(BABYLON.FreeCamera);
  32871. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32872. })(BABYLON || (BABYLON = {}));
  32873. var BABYLON;
  32874. (function (BABYLON) {
  32875. var Gamepads = (function () {
  32876. function Gamepads(ongamedpadconnected) {
  32877. var _this = this;
  32878. this.babylonGamepads = [];
  32879. this.oneGamepadConnected = false;
  32880. this.isMonitoring = false;
  32881. this.gamepadEventSupported = 'GamepadEvent' in window;
  32882. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32883. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32884. 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=";
  32885. this._callbackGamepadConnected = ongamedpadconnected;
  32886. if (this.gamepadSupportAvailable) {
  32887. // Checking if the gamepad connected event is supported (like in Firefox)
  32888. if (this.gamepadEventSupported) {
  32889. window.addEventListener('gamepadconnected', function (evt) {
  32890. _this._onGamepadConnected(evt);
  32891. }, false);
  32892. window.addEventListener('gamepaddisconnected', function (evt) {
  32893. _this._onGamepadDisconnected(evt);
  32894. }, false);
  32895. }
  32896. else {
  32897. this._startMonitoringGamepads();
  32898. }
  32899. if (!this.oneGamepadConnected) {
  32900. this._insertGamepadDOMInstructions();
  32901. }
  32902. }
  32903. else {
  32904. this._insertGamepadDOMNotSupported();
  32905. }
  32906. }
  32907. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32908. Gamepads.gamepadDOMInfo = document.createElement("div");
  32909. var buttonAImage = document.createElement("img");
  32910. buttonAImage.src = this.buttonADataURL;
  32911. var spanMessage = document.createElement("span");
  32912. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32913. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32914. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32915. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32916. Gamepads.gamepadDOMInfo.style.width = "100%";
  32917. Gamepads.gamepadDOMInfo.style.height = "48px";
  32918. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32919. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32920. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32921. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32922. buttonAImage.style.position = "relative";
  32923. buttonAImage.style.bottom = "8px";
  32924. spanMessage.style.position = "relative";
  32925. spanMessage.style.fontSize = "32px";
  32926. spanMessage.style.bottom = "32px";
  32927. spanMessage.style.color = "green";
  32928. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32929. };
  32930. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32931. Gamepads.gamepadDOMInfo = document.createElement("div");
  32932. var spanMessage = document.createElement("span");
  32933. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32934. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32935. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32936. Gamepads.gamepadDOMInfo.style.width = "100%";
  32937. Gamepads.gamepadDOMInfo.style.height = "40px";
  32938. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32939. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32940. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32941. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32942. spanMessage.style.position = "relative";
  32943. spanMessage.style.fontSize = "32px";
  32944. spanMessage.style.color = "red";
  32945. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32946. };
  32947. Gamepads.prototype.dispose = function () {
  32948. if (Gamepads.gamepadDOMInfo) {
  32949. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32950. }
  32951. };
  32952. Gamepads.prototype._onGamepadConnected = function (evt) {
  32953. var newGamepad = this._addNewGamepad(evt.gamepad);
  32954. if (this._callbackGamepadConnected)
  32955. this._callbackGamepadConnected(newGamepad);
  32956. this._startMonitoringGamepads();
  32957. };
  32958. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32959. if (!this.oneGamepadConnected) {
  32960. this.oneGamepadConnected = true;
  32961. if (Gamepads.gamepadDOMInfo) {
  32962. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32963. Gamepads.gamepadDOMInfo = null;
  32964. }
  32965. }
  32966. var newGamepad;
  32967. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32968. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32969. }
  32970. else {
  32971. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32972. }
  32973. this.babylonGamepads.push(newGamepad);
  32974. return newGamepad;
  32975. };
  32976. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32977. // Remove the gamepad from the list of gamepads to monitor.
  32978. for (var i in this.babylonGamepads) {
  32979. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32980. this.babylonGamepads.splice(i, 1);
  32981. break;
  32982. }
  32983. }
  32984. // If no gamepads are left, stop the polling loop.
  32985. if (this.babylonGamepads.length == 0) {
  32986. this._stopMonitoringGamepads();
  32987. }
  32988. };
  32989. Gamepads.prototype._startMonitoringGamepads = function () {
  32990. if (!this.isMonitoring) {
  32991. this.isMonitoring = true;
  32992. this._checkGamepadsStatus();
  32993. }
  32994. };
  32995. Gamepads.prototype._stopMonitoringGamepads = function () {
  32996. this.isMonitoring = false;
  32997. };
  32998. Gamepads.prototype._checkGamepadsStatus = function () {
  32999. var _this = this;
  33000. // updating gamepad objects
  33001. this._updateGamepadObjects();
  33002. for (var i in this.babylonGamepads) {
  33003. this.babylonGamepads[i].update();
  33004. }
  33005. if (this.isMonitoring) {
  33006. if (window.requestAnimationFrame) {
  33007. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33008. }
  33009. else if (window.mozRequestAnimationFrame) {
  33010. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33011. }
  33012. else if (window.webkitRequestAnimationFrame) {
  33013. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  33014. }
  33015. }
  33016. };
  33017. // This function is called only on Chrome, which does not yet support
  33018. // connection/disconnection events, but requires you to monitor
  33019. // an array for changes.
  33020. Gamepads.prototype._updateGamepadObjects = function () {
  33021. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  33022. for (var i = 0; i < gamepads.length; i++) {
  33023. if (gamepads[i]) {
  33024. if (!(gamepads[i].index in this.babylonGamepads)) {
  33025. var newGamepad = this._addNewGamepad(gamepads[i]);
  33026. if (this._callbackGamepadConnected) {
  33027. this._callbackGamepadConnected(newGamepad);
  33028. }
  33029. }
  33030. else {
  33031. this.babylonGamepads[i].browserGamepad = gamepads[i];
  33032. }
  33033. }
  33034. }
  33035. };
  33036. return Gamepads;
  33037. })();
  33038. BABYLON.Gamepads = Gamepads;
  33039. var StickValues = (function () {
  33040. function StickValues(x, y) {
  33041. this.x = x;
  33042. this.y = y;
  33043. }
  33044. return StickValues;
  33045. })();
  33046. BABYLON.StickValues = StickValues;
  33047. var Gamepad = (function () {
  33048. function Gamepad(id, index, browserGamepad) {
  33049. this.id = id;
  33050. this.index = index;
  33051. this.browserGamepad = browserGamepad;
  33052. if (this.browserGamepad.axes.length >= 2) {
  33053. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33054. }
  33055. if (this.browserGamepad.axes.length >= 4) {
  33056. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33057. }
  33058. }
  33059. Gamepad.prototype.onleftstickchanged = function (callback) {
  33060. this._onleftstickchanged = callback;
  33061. };
  33062. Gamepad.prototype.onrightstickchanged = function (callback) {
  33063. this._onrightstickchanged = callback;
  33064. };
  33065. Object.defineProperty(Gamepad.prototype, "leftStick", {
  33066. get: function () {
  33067. return this._leftStick;
  33068. },
  33069. set: function (newValues) {
  33070. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  33071. this._onleftstickchanged(newValues);
  33072. }
  33073. this._leftStick = newValues;
  33074. },
  33075. enumerable: true,
  33076. configurable: true
  33077. });
  33078. Object.defineProperty(Gamepad.prototype, "rightStick", {
  33079. get: function () {
  33080. return this._rightStick;
  33081. },
  33082. set: function (newValues) {
  33083. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  33084. this._onrightstickchanged(newValues);
  33085. }
  33086. this._rightStick = newValues;
  33087. },
  33088. enumerable: true,
  33089. configurable: true
  33090. });
  33091. Gamepad.prototype.update = function () {
  33092. if (this._leftStick) {
  33093. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  33094. }
  33095. if (this._rightStick) {
  33096. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  33097. }
  33098. };
  33099. return Gamepad;
  33100. })();
  33101. BABYLON.Gamepad = Gamepad;
  33102. var GenericPad = (function (_super) {
  33103. __extends(GenericPad, _super);
  33104. function GenericPad(id, index, gamepad) {
  33105. _super.call(this, id, index, gamepad);
  33106. this.id = id;
  33107. this.index = index;
  33108. this.gamepad = gamepad;
  33109. this._buttons = new Array(gamepad.buttons.length);
  33110. }
  33111. GenericPad.prototype.onbuttondown = function (callback) {
  33112. this._onbuttondown = callback;
  33113. };
  33114. GenericPad.prototype.onbuttonup = function (callback) {
  33115. this._onbuttonup = callback;
  33116. };
  33117. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  33118. if (newValue !== currentValue) {
  33119. if (this._onbuttondown && newValue === 1) {
  33120. this._onbuttondown(buttonIndex);
  33121. }
  33122. if (this._onbuttonup && newValue === 0) {
  33123. this._onbuttonup(buttonIndex);
  33124. }
  33125. }
  33126. return newValue;
  33127. };
  33128. GenericPad.prototype.update = function () {
  33129. _super.prototype.update.call(this);
  33130. for (var index = 0; index < this._buttons.length; index++) {
  33131. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  33132. }
  33133. };
  33134. return GenericPad;
  33135. })(Gamepad);
  33136. BABYLON.GenericPad = GenericPad;
  33137. (function (Xbox360Button) {
  33138. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  33139. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  33140. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  33141. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  33142. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  33143. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  33144. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  33145. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  33146. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  33147. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  33148. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  33149. var Xbox360Button = BABYLON.Xbox360Button;
  33150. (function (Xbox360Dpad) {
  33151. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  33152. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  33153. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  33154. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  33155. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  33156. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  33157. var Xbox360Pad = (function (_super) {
  33158. __extends(Xbox360Pad, _super);
  33159. function Xbox360Pad() {
  33160. _super.apply(this, arguments);
  33161. this._leftTrigger = 0;
  33162. this._rightTrigger = 0;
  33163. this._buttonA = 0;
  33164. this._buttonB = 0;
  33165. this._buttonX = 0;
  33166. this._buttonY = 0;
  33167. this._buttonBack = 0;
  33168. this._buttonStart = 0;
  33169. this._buttonLB = 0;
  33170. this._buttonRB = 0;
  33171. this._buttonLeftStick = 0;
  33172. this._buttonRightStick = 0;
  33173. this._dPadUp = 0;
  33174. this._dPadDown = 0;
  33175. this._dPadLeft = 0;
  33176. this._dPadRight = 0;
  33177. }
  33178. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  33179. this._onlefttriggerchanged = callback;
  33180. };
  33181. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  33182. this._onrighttriggerchanged = callback;
  33183. };
  33184. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  33185. get: function () {
  33186. return this._leftTrigger;
  33187. },
  33188. set: function (newValue) {
  33189. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  33190. this._onlefttriggerchanged(newValue);
  33191. }
  33192. this._leftTrigger = newValue;
  33193. },
  33194. enumerable: true,
  33195. configurable: true
  33196. });
  33197. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  33198. get: function () {
  33199. return this._rightTrigger;
  33200. },
  33201. set: function (newValue) {
  33202. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  33203. this._onrighttriggerchanged(newValue);
  33204. }
  33205. this._rightTrigger = newValue;
  33206. },
  33207. enumerable: true,
  33208. configurable: true
  33209. });
  33210. Xbox360Pad.prototype.onbuttondown = function (callback) {
  33211. this._onbuttondown = callback;
  33212. };
  33213. Xbox360Pad.prototype.onbuttonup = function (callback) {
  33214. this._onbuttonup = callback;
  33215. };
  33216. Xbox360Pad.prototype.ondpaddown = function (callback) {
  33217. this._ondpaddown = callback;
  33218. };
  33219. Xbox360Pad.prototype.ondpadup = function (callback) {
  33220. this._ondpadup = callback;
  33221. };
  33222. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  33223. if (newValue !== currentValue) {
  33224. if (this._onbuttondown && newValue === 1) {
  33225. this._onbuttondown(buttonType);
  33226. }
  33227. if (this._onbuttonup && newValue === 0) {
  33228. this._onbuttonup(buttonType);
  33229. }
  33230. }
  33231. return newValue;
  33232. };
  33233. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  33234. if (newValue !== currentValue) {
  33235. if (this._ondpaddown && newValue === 1) {
  33236. this._ondpaddown(buttonType);
  33237. }
  33238. if (this._ondpadup && newValue === 0) {
  33239. this._ondpadup(buttonType);
  33240. }
  33241. }
  33242. return newValue;
  33243. };
  33244. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  33245. get: function () {
  33246. return this._buttonA;
  33247. },
  33248. set: function (value) {
  33249. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  33250. },
  33251. enumerable: true,
  33252. configurable: true
  33253. });
  33254. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  33255. get: function () {
  33256. return this._buttonB;
  33257. },
  33258. set: function (value) {
  33259. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  33260. },
  33261. enumerable: true,
  33262. configurable: true
  33263. });
  33264. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  33265. get: function () {
  33266. return this._buttonX;
  33267. },
  33268. set: function (value) {
  33269. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  33270. },
  33271. enumerable: true,
  33272. configurable: true
  33273. });
  33274. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  33275. get: function () {
  33276. return this._buttonY;
  33277. },
  33278. set: function (value) {
  33279. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  33285. get: function () {
  33286. return this._buttonStart;
  33287. },
  33288. set: function (value) {
  33289. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  33290. },
  33291. enumerable: true,
  33292. configurable: true
  33293. });
  33294. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  33295. get: function () {
  33296. return this._buttonBack;
  33297. },
  33298. set: function (value) {
  33299. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  33300. },
  33301. enumerable: true,
  33302. configurable: true
  33303. });
  33304. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  33305. get: function () {
  33306. return this._buttonLB;
  33307. },
  33308. set: function (value) {
  33309. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  33310. },
  33311. enumerable: true,
  33312. configurable: true
  33313. });
  33314. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  33315. get: function () {
  33316. return this._buttonRB;
  33317. },
  33318. set: function (value) {
  33319. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  33320. },
  33321. enumerable: true,
  33322. configurable: true
  33323. });
  33324. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  33325. get: function () {
  33326. return this._buttonLeftStick;
  33327. },
  33328. set: function (value) {
  33329. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  33330. },
  33331. enumerable: true,
  33332. configurable: true
  33333. });
  33334. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  33335. get: function () {
  33336. return this._buttonRightStick;
  33337. },
  33338. set: function (value) {
  33339. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  33340. },
  33341. enumerable: true,
  33342. configurable: true
  33343. });
  33344. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  33345. get: function () {
  33346. return this._dPadUp;
  33347. },
  33348. set: function (value) {
  33349. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  33350. },
  33351. enumerable: true,
  33352. configurable: true
  33353. });
  33354. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  33355. get: function () {
  33356. return this._dPadDown;
  33357. },
  33358. set: function (value) {
  33359. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  33360. },
  33361. enumerable: true,
  33362. configurable: true
  33363. });
  33364. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  33365. get: function () {
  33366. return this._dPadLeft;
  33367. },
  33368. set: function (value) {
  33369. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  33370. },
  33371. enumerable: true,
  33372. configurable: true
  33373. });
  33374. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  33375. get: function () {
  33376. return this._dPadRight;
  33377. },
  33378. set: function (value) {
  33379. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  33380. },
  33381. enumerable: true,
  33382. configurable: true
  33383. });
  33384. Xbox360Pad.prototype.update = function () {
  33385. _super.prototype.update.call(this);
  33386. this.buttonA = this.browserGamepad.buttons[0].value;
  33387. this.buttonB = this.browserGamepad.buttons[1].value;
  33388. this.buttonX = this.browserGamepad.buttons[2].value;
  33389. this.buttonY = this.browserGamepad.buttons[3].value;
  33390. this.buttonLB = this.browserGamepad.buttons[4].value;
  33391. this.buttonRB = this.browserGamepad.buttons[5].value;
  33392. this.leftTrigger = this.browserGamepad.buttons[6].value;
  33393. this.rightTrigger = this.browserGamepad.buttons[7].value;
  33394. this.buttonBack = this.browserGamepad.buttons[8].value;
  33395. this.buttonStart = this.browserGamepad.buttons[9].value;
  33396. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  33397. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  33398. this.dPadUp = this.browserGamepad.buttons[12].value;
  33399. this.dPadDown = this.browserGamepad.buttons[13].value;
  33400. this.dPadLeft = this.browserGamepad.buttons[14].value;
  33401. this.dPadRight = this.browserGamepad.buttons[15].value;
  33402. };
  33403. return Xbox360Pad;
  33404. })(Gamepad);
  33405. BABYLON.Xbox360Pad = Xbox360Pad;
  33406. })(BABYLON || (BABYLON = {}));
  33407. var BABYLON;
  33408. (function (BABYLON) {
  33409. // We're mainly based on the logic defined into the FreeCamera code
  33410. var GamepadCamera = (function (_super) {
  33411. __extends(GamepadCamera, _super);
  33412. function GamepadCamera(name, position, scene) {
  33413. var _this = this;
  33414. _super.call(this, name, position, scene);
  33415. this.angularSensibility = 200;
  33416. this.moveSensibility = 75;
  33417. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  33418. }
  33419. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  33420. // Only the first gamepad can control the camera
  33421. if (gamepad.index === 0) {
  33422. this._gamepad = gamepad;
  33423. }
  33424. };
  33425. GamepadCamera.prototype._checkInputs = function () {
  33426. if (this._gamepad) {
  33427. var LSValues = this._gamepad.leftStick;
  33428. var normalizedLX = LSValues.x / this.moveSensibility;
  33429. var normalizedLY = LSValues.y / this.moveSensibility;
  33430. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  33431. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  33432. var RSValues = this._gamepad.rightStick;
  33433. var normalizedRX = RSValues.x / this.angularSensibility;
  33434. var normalizedRY = RSValues.y / this.angularSensibility;
  33435. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  33436. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  33437. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33438. var speed = this._computeLocalCameraSpeed() * 50.0;
  33439. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  33440. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33441. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  33442. }
  33443. _super.prototype._checkInputs.call(this);
  33444. };
  33445. GamepadCamera.prototype.dispose = function () {
  33446. this._gamepads.dispose();
  33447. _super.prototype.dispose.call(this);
  33448. };
  33449. return GamepadCamera;
  33450. })(BABYLON.FreeCamera);
  33451. BABYLON.GamepadCamera = GamepadCamera;
  33452. })(BABYLON || (BABYLON = {}));
  33453. var BABYLON;
  33454. (function (BABYLON) {
  33455. var Analyser = (function () {
  33456. function Analyser(scene) {
  33457. this.SMOOTHING = 0.75;
  33458. this.FFT_SIZE = 512;
  33459. this.BARGRAPHAMPLITUDE = 256;
  33460. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  33461. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  33462. this._scene = scene;
  33463. this._audioEngine = BABYLON.Engine.audioEngine;
  33464. if (this._audioEngine.canUseWebAudio) {
  33465. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  33466. this._webAudioAnalyser.minDecibels = -140;
  33467. this._webAudioAnalyser.maxDecibels = 0;
  33468. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33469. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  33470. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  33471. }
  33472. }
  33473. Analyser.prototype.getFrequencyBinCount = function () {
  33474. if (this._audioEngine.canUseWebAudio) {
  33475. return this._webAudioAnalyser.frequencyBinCount;
  33476. }
  33477. else {
  33478. return 0;
  33479. }
  33480. };
  33481. Analyser.prototype.getByteFrequencyData = function () {
  33482. if (this._audioEngine.canUseWebAudio) {
  33483. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33484. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33485. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  33486. }
  33487. return this._byteFreqs;
  33488. };
  33489. Analyser.prototype.getByteTimeDomainData = function () {
  33490. if (this._audioEngine.canUseWebAudio) {
  33491. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33492. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33493. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  33494. }
  33495. return this._byteTime;
  33496. };
  33497. Analyser.prototype.getFloatFrequencyData = function () {
  33498. if (this._audioEngine.canUseWebAudio) {
  33499. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  33500. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  33501. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  33502. }
  33503. return this._floatFreqs;
  33504. };
  33505. Analyser.prototype.drawDebugCanvas = function () {
  33506. var _this = this;
  33507. if (this._audioEngine.canUseWebAudio) {
  33508. if (!this._debugCanvas) {
  33509. this._debugCanvas = document.createElement("canvas");
  33510. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  33511. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  33512. this._debugCanvas.style.position = "absolute";
  33513. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  33514. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  33515. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  33516. document.body.appendChild(this._debugCanvas);
  33517. this._registerFunc = function () {
  33518. _this.drawDebugCanvas();
  33519. };
  33520. this._scene.registerBeforeRender(this._registerFunc);
  33521. }
  33522. if (this._registerFunc) {
  33523. var workingArray = this.getByteFrequencyData();
  33524. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  33525. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  33526. // Draw the frequency domain chart.
  33527. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  33528. var value = workingArray[i];
  33529. var percent = value / this.BARGRAPHAMPLITUDE;
  33530. var height = this.DEBUGCANVASSIZE.height * percent;
  33531. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  33532. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  33533. var hue = i / this.getFrequencyBinCount() * 360;
  33534. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  33535. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  33536. }
  33537. }
  33538. }
  33539. };
  33540. Analyser.prototype.stopDebugCanvas = function () {
  33541. if (this._debugCanvas) {
  33542. this._scene.unregisterBeforeRender(this._registerFunc);
  33543. this._registerFunc = null;
  33544. document.body.removeChild(this._debugCanvas);
  33545. this._debugCanvas = null;
  33546. this._debugCanvasContext = null;
  33547. }
  33548. };
  33549. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  33550. if (this._audioEngine.canUseWebAudio) {
  33551. inputAudioNode.connect(this._webAudioAnalyser);
  33552. this._webAudioAnalyser.connect(outputAudioNode);
  33553. }
  33554. };
  33555. Analyser.prototype.dispose = function () {
  33556. if (this._audioEngine.canUseWebAudio) {
  33557. this._webAudioAnalyser.disconnect();
  33558. }
  33559. };
  33560. return Analyser;
  33561. })();
  33562. BABYLON.Analyser = Analyser;
  33563. })(BABYLON || (BABYLON = {}));
  33564. var BABYLON;
  33565. (function (BABYLON) {
  33566. var AudioEngine = (function () {
  33567. function AudioEngine() {
  33568. this._audioContext = null;
  33569. this._audioContextInitialized = false;
  33570. this.canUseWebAudio = false;
  33571. this.WarnedWebAudioUnsupported = false;
  33572. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33573. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33574. this.canUseWebAudio = true;
  33575. }
  33576. }
  33577. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33578. get: function () {
  33579. if (!this._audioContextInitialized) {
  33580. this._initializeAudioContext();
  33581. }
  33582. return this._audioContext;
  33583. },
  33584. enumerable: true,
  33585. configurable: true
  33586. });
  33587. AudioEngine.prototype._initializeAudioContext = function () {
  33588. try {
  33589. if (this.canUseWebAudio) {
  33590. this._audioContext = new AudioContext();
  33591. // create a global volume gain node
  33592. this.masterGain = this._audioContext.createGain();
  33593. this.masterGain.gain.value = 1;
  33594. this.masterGain.connect(this._audioContext.destination);
  33595. this._audioContextInitialized = true;
  33596. }
  33597. }
  33598. catch (e) {
  33599. this.canUseWebAudio = false;
  33600. BABYLON.Tools.Error("Web Audio: " + e.message);
  33601. }
  33602. };
  33603. AudioEngine.prototype.dispose = function () {
  33604. if (this.canUseWebAudio && this._audioContextInitialized) {
  33605. if (this._connectedAnalyser) {
  33606. this._connectedAnalyser.stopDebugCanvas();
  33607. this._connectedAnalyser.dispose();
  33608. this.masterGain.disconnect();
  33609. this.masterGain.connect(this._audioContext.destination);
  33610. this._connectedAnalyser = null;
  33611. }
  33612. this.masterGain.gain.value = 1;
  33613. }
  33614. this.WarnedWebAudioUnsupported = false;
  33615. };
  33616. AudioEngine.prototype.getGlobalVolume = function () {
  33617. if (this.canUseWebAudio && this._audioContextInitialized) {
  33618. return this.masterGain.gain.value;
  33619. }
  33620. else {
  33621. return -1;
  33622. }
  33623. };
  33624. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33625. if (this.canUseWebAudio && this._audioContextInitialized) {
  33626. this.masterGain.gain.value = newVolume;
  33627. }
  33628. };
  33629. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33630. if (this._connectedAnalyser) {
  33631. this._connectedAnalyser.stopDebugCanvas();
  33632. }
  33633. if (this.canUseWebAudio && this._audioContextInitialized) {
  33634. this._connectedAnalyser = analyser;
  33635. this.masterGain.disconnect();
  33636. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33637. }
  33638. };
  33639. return AudioEngine;
  33640. })();
  33641. BABYLON.AudioEngine = AudioEngine;
  33642. })(BABYLON || (BABYLON = {}));
  33643. var BABYLON;
  33644. (function (BABYLON) {
  33645. var Sound = (function () {
  33646. /**
  33647. * Create a sound and attach it to a scene
  33648. * @param name Name of your sound
  33649. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33650. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33651. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  33652. */
  33653. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33654. var _this = this;
  33655. this.autoplay = false;
  33656. this.loop = false;
  33657. this.useCustomAttenuation = false;
  33658. this.spatialSound = false;
  33659. this.refDistance = 1;
  33660. this.rolloffFactor = 1;
  33661. this.maxDistance = 100;
  33662. this.distanceModel = "linear";
  33663. this._panningModel = "equalpower";
  33664. this._playbackRate = 1;
  33665. this._streaming = false;
  33666. this._startTime = 0;
  33667. this._startOffset = 0;
  33668. this._position = BABYLON.Vector3.Zero();
  33669. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33670. this._volume = 1;
  33671. this._isLoaded = false;
  33672. this._isReadyToPlay = false;
  33673. this.isPlaying = false;
  33674. this.isPaused = false;
  33675. this._isDirectional = false;
  33676. // Used if you'd like to create a directional sound.
  33677. // If not set, the sound will be omnidirectional
  33678. this._coneInnerAngle = 360;
  33679. this._coneOuterAngle = 360;
  33680. this._coneOuterGain = 0;
  33681. this._isOutputConnected = false;
  33682. this.name = name;
  33683. this._scene = scene;
  33684. this._readyToPlayCallback = readyToPlayCallback;
  33685. // Default custom attenuation function is a linear attenuation
  33686. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33687. if (currentDistance < maxDistance) {
  33688. return currentVolume * (1 - currentDistance / maxDistance);
  33689. }
  33690. else {
  33691. return 0;
  33692. }
  33693. };
  33694. if (options) {
  33695. this.autoplay = options.autoplay || false;
  33696. this.loop = options.loop || false;
  33697. // if volume === 0, we need another way to check this option
  33698. if (options.volume !== undefined) {
  33699. this._volume = options.volume;
  33700. }
  33701. this.spatialSound = options.spatialSound || false;
  33702. this.maxDistance = options.maxDistance || 100;
  33703. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33704. this.rolloffFactor = options.rolloffFactor || 1;
  33705. this.refDistance = options.refDistance || 1;
  33706. this.distanceModel = options.distanceModel || "linear";
  33707. this._playbackRate = options.playbackRate || 1;
  33708. this._streaming = options.streaming || false;
  33709. }
  33710. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33711. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33712. this._soundGain.gain.value = this._volume;
  33713. this._inputAudioNode = this._soundGain;
  33714. this._ouputAudioNode = this._soundGain;
  33715. if (this.spatialSound) {
  33716. this._createSpatialParameters();
  33717. }
  33718. this._scene.mainSoundTrack.AddSound(this);
  33719. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33720. if (urlOrArrayBuffer) {
  33721. // If it's an URL
  33722. if (typeof (urlOrArrayBuffer) === "string") {
  33723. // Loading sound using XHR2
  33724. if (!this._streaming) {
  33725. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33726. }
  33727. else {
  33728. this._htmlAudioElement = new Audio();
  33729. this._htmlAudioElement.src = urlOrArrayBuffer;
  33730. this._htmlAudioElement.controls = false;
  33731. this._htmlAudioElement.loop = this.loop;
  33732. this._htmlAudioElement.crossOrigin = "anonymous";
  33733. this._isReadyToPlay = true;
  33734. document.body.appendChild(this._htmlAudioElement);
  33735. // Simulating a ready to play event for consistent behavior with non streamed audio source
  33736. if (this._readyToPlayCallback) {
  33737. window.setTimeout(function () {
  33738. _this._readyToPlayCallback();
  33739. }, 1000);
  33740. }
  33741. if (this.autoplay) {
  33742. this.play();
  33743. }
  33744. }
  33745. }
  33746. else {
  33747. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33748. this._soundLoaded(urlOrArrayBuffer);
  33749. }
  33750. else {
  33751. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33752. }
  33753. }
  33754. }
  33755. }
  33756. else {
  33757. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33758. this._scene.mainSoundTrack.AddSound(this);
  33759. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33760. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33761. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33762. }
  33763. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33764. if (this._readyToPlayCallback) {
  33765. window.setTimeout(function () {
  33766. _this._readyToPlayCallback();
  33767. }, 1000);
  33768. }
  33769. }
  33770. }
  33771. Sound.prototype.dispose = function () {
  33772. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33773. if (this.isPlaying) {
  33774. this.stop();
  33775. }
  33776. this._isReadyToPlay = false;
  33777. if (this.soundTrackId === -1) {
  33778. this._scene.mainSoundTrack.RemoveSound(this);
  33779. }
  33780. else {
  33781. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33782. }
  33783. if (this._soundGain) {
  33784. this._soundGain.disconnect();
  33785. this._soundGain = null;
  33786. }
  33787. if (this._soundPanner) {
  33788. this._soundPanner.disconnect();
  33789. this._soundPanner = null;
  33790. }
  33791. if (this._soundSource) {
  33792. this._soundSource.disconnect();
  33793. this._soundSource = null;
  33794. }
  33795. this._audioBuffer = null;
  33796. if (this._htmlAudioElement) {
  33797. this._htmlAudioElement.pause();
  33798. this._htmlAudioElement.src = "";
  33799. document.body.removeChild(this._htmlAudioElement);
  33800. }
  33801. if (this._connectedMesh) {
  33802. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33803. this._connectedMesh = null;
  33804. }
  33805. }
  33806. };
  33807. Sound.prototype._soundLoaded = function (audioData) {
  33808. var _this = this;
  33809. this._isLoaded = true;
  33810. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33811. _this._audioBuffer = buffer;
  33812. _this._isReadyToPlay = true;
  33813. if (_this.autoplay) {
  33814. _this.play();
  33815. }
  33816. if (_this._readyToPlayCallback) {
  33817. _this._readyToPlayCallback();
  33818. }
  33819. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33820. };
  33821. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33822. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33823. this._audioBuffer = audioBuffer;
  33824. this._isReadyToPlay = true;
  33825. }
  33826. };
  33827. Sound.prototype.updateOptions = function (options) {
  33828. if (options) {
  33829. this.loop = options.loop || this.loop;
  33830. this.maxDistance = options.maxDistance || this.maxDistance;
  33831. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33832. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33833. this.refDistance = options.refDistance || this.refDistance;
  33834. this.distanceModel = options.distanceModel || this.distanceModel;
  33835. this._playbackRate = options.playbackRate || this._playbackRate;
  33836. this._updateSpatialParameters();
  33837. if (this.isPlaying) {
  33838. if (this._streaming) {
  33839. this._htmlAudioElement.playbackRate = this._playbackRate;
  33840. }
  33841. else {
  33842. this._soundSource.playbackRate.value = this._playbackRate;
  33843. }
  33844. }
  33845. }
  33846. };
  33847. Sound.prototype._createSpatialParameters = function () {
  33848. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33849. if (this._scene.headphone) {
  33850. this._panningModel = "HRTF";
  33851. }
  33852. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33853. this._updateSpatialParameters();
  33854. this._soundPanner.connect(this._ouputAudioNode);
  33855. this._inputAudioNode = this._soundPanner;
  33856. }
  33857. };
  33858. Sound.prototype._updateSpatialParameters = function () {
  33859. if (this.spatialSound) {
  33860. if (this.useCustomAttenuation) {
  33861. // Tricks to disable in a way embedded Web Audio attenuation
  33862. this._soundPanner.distanceModel = "linear";
  33863. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33864. this._soundPanner.refDistance = 1;
  33865. this._soundPanner.rolloffFactor = 1;
  33866. this._soundPanner.panningModel = this._panningModel;
  33867. }
  33868. else {
  33869. this._soundPanner.distanceModel = this.distanceModel;
  33870. this._soundPanner.maxDistance = this.maxDistance;
  33871. this._soundPanner.refDistance = this.refDistance;
  33872. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33873. this._soundPanner.panningModel = this._panningModel;
  33874. }
  33875. }
  33876. };
  33877. Sound.prototype.switchPanningModelToHRTF = function () {
  33878. this._panningModel = "HRTF";
  33879. this._switchPanningModel();
  33880. };
  33881. Sound.prototype.switchPanningModelToEqualPower = function () {
  33882. this._panningModel = "equalpower";
  33883. this._switchPanningModel();
  33884. };
  33885. Sound.prototype._switchPanningModel = function () {
  33886. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33887. this._soundPanner.panningModel = this._panningModel;
  33888. }
  33889. };
  33890. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33891. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33892. if (this._isOutputConnected) {
  33893. this._ouputAudioNode.disconnect();
  33894. }
  33895. this._ouputAudioNode.connect(soundTrackAudioNode);
  33896. this._isOutputConnected = true;
  33897. }
  33898. };
  33899. /**
  33900. * Transform this sound into a directional source
  33901. * @param coneInnerAngle Size of the inner cone in degree
  33902. * @param coneOuterAngle Size of the outer cone in degree
  33903. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33904. */
  33905. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33906. if (coneOuterAngle < coneInnerAngle) {
  33907. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33908. return;
  33909. }
  33910. this._coneInnerAngle = coneInnerAngle;
  33911. this._coneOuterAngle = coneOuterAngle;
  33912. this._coneOuterGain = coneOuterGain;
  33913. this._isDirectional = true;
  33914. if (this.isPlaying && this.loop) {
  33915. this.stop();
  33916. this.play();
  33917. }
  33918. };
  33919. Sound.prototype.setPosition = function (newPosition) {
  33920. this._position = newPosition;
  33921. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33922. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33923. }
  33924. };
  33925. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33926. this._localDirection = newLocalDirection;
  33927. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33928. this._updateDirection();
  33929. }
  33930. };
  33931. Sound.prototype._updateDirection = function () {
  33932. var mat = this._connectedMesh.getWorldMatrix();
  33933. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33934. direction.normalize();
  33935. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33936. };
  33937. Sound.prototype.updateDistanceFromListener = function () {
  33938. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33939. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33940. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33941. }
  33942. };
  33943. Sound.prototype.setAttenuationFunction = function (callback) {
  33944. this._customAttenuationFunction = callback;
  33945. };
  33946. /**
  33947. * Play the sound
  33948. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33949. */
  33950. Sound.prototype.play = function (time) {
  33951. var _this = this;
  33952. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33953. try {
  33954. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33955. if (!this._soundSource || !this._streamingSource) {
  33956. if (this.spatialSound) {
  33957. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33958. if (this._isDirectional) {
  33959. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33960. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33961. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33962. if (this._connectedMesh) {
  33963. this._updateDirection();
  33964. }
  33965. else {
  33966. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33967. }
  33968. }
  33969. }
  33970. }
  33971. if (this._streaming) {
  33972. if (!this._streamingSource) {
  33973. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33974. this._htmlAudioElement.onended = function () { _this._onended(); };
  33975. this._htmlAudioElement.playbackRate = this._playbackRate;
  33976. }
  33977. this._streamingSource.disconnect();
  33978. this._streamingSource.connect(this._inputAudioNode);
  33979. this._htmlAudioElement.play();
  33980. }
  33981. else {
  33982. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33983. this._soundSource.buffer = this._audioBuffer;
  33984. this._soundSource.connect(this._inputAudioNode);
  33985. this._soundSource.loop = this.loop;
  33986. this._soundSource.playbackRate.value = this._playbackRate;
  33987. this._soundSource.onended = function () { _this._onended(); };
  33988. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33989. }
  33990. this._startTime = startTime;
  33991. this.isPlaying = true;
  33992. this.isPaused = false;
  33993. }
  33994. catch (ex) {
  33995. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33996. }
  33997. }
  33998. };
  33999. Sound.prototype._onended = function () {
  34000. this.isPlaying = false;
  34001. if (this.onended) {
  34002. this.onended();
  34003. }
  34004. };
  34005. /**
  34006. * Stop the sound
  34007. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34008. */
  34009. Sound.prototype.stop = function (time) {
  34010. if (this.isPlaying) {
  34011. if (this._streaming) {
  34012. this._htmlAudioElement.pause();
  34013. // Test needed for Firefox or it will generate an Invalid State Error
  34014. if (this._htmlAudioElement.currentTime > 0) {
  34015. this._htmlAudioElement.currentTime = 0;
  34016. }
  34017. }
  34018. else {
  34019. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34020. this._soundSource.stop(stopTime);
  34021. }
  34022. this.isPlaying = false;
  34023. }
  34024. };
  34025. Sound.prototype.pause = function () {
  34026. if (this.isPlaying) {
  34027. if (this._streaming) {
  34028. this._htmlAudioElement.pause();
  34029. }
  34030. else {
  34031. this.stop(0);
  34032. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34033. }
  34034. this.isPaused = true;
  34035. }
  34036. };
  34037. Sound.prototype.setVolume = function (newVolume, time) {
  34038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34039. if (time) {
  34040. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34041. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  34042. }
  34043. else {
  34044. this._soundGain.gain.value = newVolume;
  34045. }
  34046. }
  34047. this._volume = newVolume;
  34048. };
  34049. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34050. this._playbackRate = newPlaybackRate;
  34051. if (this.isPlaying) {
  34052. if (this._streaming) {
  34053. this._htmlAudioElement.playbackRate = this._playbackRate;
  34054. }
  34055. else {
  34056. this._soundSource.playbackRate.value = this._playbackRate;
  34057. }
  34058. }
  34059. };
  34060. Sound.prototype.getVolume = function () {
  34061. return this._volume;
  34062. };
  34063. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34064. var _this = this;
  34065. this._connectedMesh = meshToConnectTo;
  34066. if (!this.spatialSound) {
  34067. this.spatialSound = true;
  34068. this._createSpatialParameters();
  34069. if (this.isPlaying && this.loop) {
  34070. this.stop();
  34071. this.play();
  34072. }
  34073. }
  34074. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34075. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34076. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34077. };
  34078. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34079. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34080. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34081. this._updateDirection();
  34082. }
  34083. };
  34084. return Sound;
  34085. })();
  34086. BABYLON.Sound = Sound;
  34087. })(BABYLON || (BABYLON = {}));
  34088. var BABYLON;
  34089. (function (BABYLON) {
  34090. var SoundTrack = (function () {
  34091. function SoundTrack(scene, options) {
  34092. this.id = -1;
  34093. this._isMainTrack = false;
  34094. this._isInitialized = false;
  34095. this._scene = scene;
  34096. this.soundCollection = new Array();
  34097. this._options = options;
  34098. if (!this._isMainTrack) {
  34099. this._scene.soundTracks.push(this);
  34100. this.id = this._scene.soundTracks.length - 1;
  34101. }
  34102. }
  34103. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34104. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34105. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34106. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34107. if (this._options) {
  34108. if (this._options.volume) {
  34109. this._outputAudioNode.gain.value = this._options.volume;
  34110. }
  34111. if (this._options.mainTrack) {
  34112. this._isMainTrack = this._options.mainTrack;
  34113. }
  34114. }
  34115. this._isInitialized = true;
  34116. }
  34117. };
  34118. SoundTrack.prototype.dispose = function () {
  34119. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34120. if (this._connectedAnalyser) {
  34121. this._connectedAnalyser.stopDebugCanvas();
  34122. }
  34123. while (this.soundCollection.length) {
  34124. this.soundCollection[0].dispose();
  34125. }
  34126. if (this._outputAudioNode) {
  34127. this._outputAudioNode.disconnect();
  34128. }
  34129. this._outputAudioNode = null;
  34130. }
  34131. };
  34132. SoundTrack.prototype.AddSound = function (sound) {
  34133. if (!this._isInitialized) {
  34134. this._initializeSoundTrackAudioGraph();
  34135. }
  34136. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34137. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34138. }
  34139. if (sound.soundTrackId) {
  34140. if (sound.soundTrackId === -1) {
  34141. this._scene.mainSoundTrack.RemoveSound(sound);
  34142. }
  34143. else {
  34144. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34145. }
  34146. }
  34147. this.soundCollection.push(sound);
  34148. sound.soundTrackId = this.id;
  34149. };
  34150. SoundTrack.prototype.RemoveSound = function (sound) {
  34151. var index = this.soundCollection.indexOf(sound);
  34152. if (index !== -1) {
  34153. this.soundCollection.splice(index, 1);
  34154. }
  34155. };
  34156. SoundTrack.prototype.setVolume = function (newVolume) {
  34157. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34158. this._outputAudioNode.gain.value = newVolume;
  34159. }
  34160. };
  34161. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34162. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34163. for (var i = 0; i < this.soundCollection.length; i++) {
  34164. this.soundCollection[i].switchPanningModelToHRTF();
  34165. }
  34166. }
  34167. };
  34168. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34169. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34170. for (var i = 0; i < this.soundCollection.length; i++) {
  34171. this.soundCollection[i].switchPanningModelToEqualPower();
  34172. }
  34173. }
  34174. };
  34175. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34176. if (this._connectedAnalyser) {
  34177. this._connectedAnalyser.stopDebugCanvas();
  34178. }
  34179. this._connectedAnalyser = analyser;
  34180. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34181. this._outputAudioNode.disconnect();
  34182. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34183. }
  34184. };
  34185. return SoundTrack;
  34186. })();
  34187. BABYLON.SoundTrack = SoundTrack;
  34188. })(BABYLON || (BABYLON = {}));
  34189. var BABYLON;
  34190. (function (BABYLON) {
  34191. var DepthRenderer = (function () {
  34192. function DepthRenderer(scene, type) {
  34193. var _this = this;
  34194. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  34195. this._viewMatrix = BABYLON.Matrix.Zero();
  34196. this._projectionMatrix = BABYLON.Matrix.Zero();
  34197. this._transformMatrix = BABYLON.Matrix.Zero();
  34198. this._worldViewProjection = BABYLON.Matrix.Zero();
  34199. this._scene = scene;
  34200. var engine = scene.getEngine();
  34201. // Render target
  34202. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  34203. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34204. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34205. this._depthMap.refreshRate = 1;
  34206. this._depthMap.renderParticles = false;
  34207. this._depthMap.renderList = null;
  34208. // set default depth value to 1.0 (far away)
  34209. this._depthMap.onClear = function (engine) {
  34210. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  34211. };
  34212. // Custom render function
  34213. var renderSubMesh = function (subMesh) {
  34214. var mesh = subMesh.getRenderingMesh();
  34215. var scene = _this._scene;
  34216. var engine = scene.getEngine();
  34217. // Culling
  34218. engine.setState(subMesh.getMaterial().backFaceCulling);
  34219. // Managing instances
  34220. var batch = mesh._getInstancesRenderList(subMesh._id);
  34221. if (batch.mustReturn) {
  34222. return;
  34223. }
  34224. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34225. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34226. engine.enableEffect(_this._effect);
  34227. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  34228. var material = subMesh.getMaterial();
  34229. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  34230. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  34231. // Alpha test
  34232. if (material && material.needAlphaTesting()) {
  34233. var alphaTexture = material.getAlphaTestTexture();
  34234. _this._effect.setTexture("diffuseSampler", alphaTexture);
  34235. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34236. }
  34237. // Bones
  34238. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34239. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34240. }
  34241. // Draw
  34242. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34243. }
  34244. };
  34245. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  34246. var index;
  34247. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34248. renderSubMesh(opaqueSubMeshes.data[index]);
  34249. }
  34250. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34251. renderSubMesh(alphaTestSubMeshes.data[index]);
  34252. }
  34253. };
  34254. }
  34255. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  34256. var defines = [];
  34257. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34258. var mesh = subMesh.getMesh();
  34259. var scene = mesh.getScene();
  34260. var material = subMesh.getMaterial();
  34261. // Alpha test
  34262. if (material && material.needAlphaTesting()) {
  34263. defines.push("#define ALPHATEST");
  34264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34265. attribs.push(BABYLON.VertexBuffer.UVKind);
  34266. defines.push("#define UV1");
  34267. }
  34268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34269. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34270. defines.push("#define UV2");
  34271. }
  34272. }
  34273. // Bones
  34274. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34275. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34276. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34277. if (mesh.numBoneInfluencers > 4) {
  34278. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34279. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34280. }
  34281. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34282. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34283. }
  34284. else {
  34285. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34286. }
  34287. // Instances
  34288. if (useInstances) {
  34289. defines.push("#define INSTANCES");
  34290. attribs.push("world0");
  34291. attribs.push("world1");
  34292. attribs.push("world2");
  34293. attribs.push("world3");
  34294. }
  34295. // Get correct effect
  34296. var join = defines.join("\n");
  34297. if (this._cachedDefines !== join) {
  34298. this._cachedDefines = join;
  34299. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  34300. }
  34301. return this._effect.isReady();
  34302. };
  34303. DepthRenderer.prototype.getDepthMap = function () {
  34304. return this._depthMap;
  34305. };
  34306. // Methods
  34307. DepthRenderer.prototype.dispose = function () {
  34308. this._depthMap.dispose();
  34309. };
  34310. return DepthRenderer;
  34311. })();
  34312. BABYLON.DepthRenderer = DepthRenderer;
  34313. })(BABYLON || (BABYLON = {}));
  34314. var BABYLON;
  34315. (function (BABYLON) {
  34316. var SSAORenderingPipeline = (function (_super) {
  34317. __extends(SSAORenderingPipeline, _super);
  34318. /**
  34319. * @constructor
  34320. * @param {string} name - The rendering pipeline name
  34321. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34322. * @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 }
  34323. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34324. */
  34325. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  34326. var _this = this;
  34327. _super.call(this, scene.getEngine(), name);
  34328. // Members
  34329. /**
  34330. * The PassPostProcess id in the pipeline that contains the original scene color
  34331. * @type {string}
  34332. */
  34333. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  34334. /**
  34335. * The SSAO PostProcess id in the pipeline
  34336. * @type {string}
  34337. */
  34338. this.SSAORenderEffect = "SSAORenderEffect";
  34339. /**
  34340. * The horizontal blur PostProcess id in the pipeline
  34341. * @type {string}
  34342. */
  34343. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  34344. /**
  34345. * The vertical blur PostProcess id in the pipeline
  34346. * @type {string}
  34347. */
  34348. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  34349. /**
  34350. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  34351. * @type {string}
  34352. */
  34353. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  34354. /**
  34355. * The output strength of the SSAO post-process. Default value is 1.0.
  34356. * @type {number}
  34357. */
  34358. this.totalStrength = 1.0;
  34359. /**
  34360. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  34361. * @type {number}
  34362. */
  34363. this.radius = 0.0001;
  34364. /**
  34365. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  34366. * Must not be equal to fallOff and superior to fallOff.
  34367. * Default value is 0.975
  34368. * @type {number}
  34369. */
  34370. this.area = 0.0075;
  34371. /**
  34372. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  34373. * Must not be equal to area and inferior to area.
  34374. * Default value is 0.0
  34375. * @type {number}
  34376. */
  34377. this.fallOff = 0.000001;
  34378. /**
  34379. * The base color of the SSAO post-process
  34380. * The final result is "base + ssao" between [0, 1]
  34381. * @type {number}
  34382. */
  34383. this.base = 0.5;
  34384. this._firstUpdate = true;
  34385. this._scene = scene;
  34386. // Set up assets
  34387. this._createRandomTexture();
  34388. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34389. var ssaoRatio = ratio.ssaoRatio || ratio;
  34390. var combineRatio = ratio.combineRatio || ratio;
  34391. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34392. this._createSSAOPostProcess(ssaoRatio);
  34393. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34394. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34395. this._createSSAOCombinePostProcess(combineRatio);
  34396. // Set up pipeline
  34397. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  34398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  34399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  34400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  34401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  34402. // Finish
  34403. scene.postProcessRenderPipelineManager.addPipeline(this);
  34404. if (cameras)
  34405. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34406. }
  34407. // Public Methods
  34408. /**
  34409. * Returns the horizontal blur PostProcess
  34410. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  34411. */
  34412. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  34413. return this._blurHPostProcess;
  34414. };
  34415. /**
  34416. * Returns the vertical blur PostProcess
  34417. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  34418. */
  34419. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  34420. return this._blurVPostProcess;
  34421. };
  34422. /**
  34423. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  34424. */
  34425. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34426. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34427. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34428. this._originalColorPostProcess = undefined;
  34429. this._ssaoPostProcess = undefined;
  34430. this._blurHPostProcess = undefined;
  34431. this._blurVPostProcess = undefined;
  34432. this._ssaoCombinePostProcess = undefined;
  34433. this._randomTexture.dispose();
  34434. if (disableDepthRender)
  34435. this._scene.disableDepthRenderer();
  34436. };
  34437. // Private Methods
  34438. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  34439. var _this = this;
  34440. var numSamples = 16;
  34441. var sampleSphere = [
  34442. 0.5381, 0.1856, -0.4319,
  34443. 0.1379, 0.2486, 0.4430,
  34444. 0.3371, 0.5679, -0.0057,
  34445. -0.6999, -0.0451, -0.0019,
  34446. 0.0689, -0.1598, -0.8547,
  34447. 0.0560, 0.0069, -0.1843,
  34448. -0.0146, 0.1402, 0.0762,
  34449. 0.0100, -0.1924, -0.0344,
  34450. -0.3577, -0.5301, -0.4358,
  34451. -0.3169, 0.1063, 0.0158,
  34452. 0.0103, -0.5869, 0.0046,
  34453. -0.0897, -0.4940, 0.3287,
  34454. 0.7119, -0.0154, -0.0918,
  34455. -0.0533, 0.0596, -0.5411,
  34456. 0.0352, -0.0631, 0.5460,
  34457. -0.4776, 0.2847, -0.0271
  34458. ];
  34459. var samplesFactor = 1.0 / numSamples;
  34460. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  34461. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  34462. "area", "fallOff", "base"
  34463. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  34464. this._ssaoPostProcess.onApply = function (effect) {
  34465. if (_this._firstUpdate) {
  34466. effect.setArray3("sampleSphere", sampleSphere);
  34467. effect.setFloat("samplesFactor", samplesFactor);
  34468. effect.setFloat("randTextureTiles", 4.0);
  34469. _this._firstUpdate = false;
  34470. }
  34471. effect.setFloat("totalStrength", _this.totalStrength);
  34472. effect.setFloat("radius", _this.radius);
  34473. effect.setFloat("area", _this.area);
  34474. effect.setFloat("fallOff", _this.fallOff);
  34475. effect.setFloat("base", _this.base);
  34476. effect.setTexture("textureSampler", _this._depthTexture);
  34477. effect.setTexture("randomSampler", _this._randomTexture);
  34478. };
  34479. };
  34480. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  34481. var _this = this;
  34482. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34483. this._ssaoCombinePostProcess.onApply = function (effect) {
  34484. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  34485. };
  34486. };
  34487. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  34488. var size = 512;
  34489. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34490. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34491. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34492. var context = this._randomTexture.getContext();
  34493. var rand = function (min, max) {
  34494. return Math.random() * (max - min) + min;
  34495. };
  34496. var randVector = BABYLON.Vector3.Zero();
  34497. for (var x = 0; x < size; x++) {
  34498. for (var y = 0; y < size; y++) {
  34499. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  34500. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  34501. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  34502. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  34503. context.fillRect(x, y, 1, 1);
  34504. }
  34505. }
  34506. this._randomTexture.update(false);
  34507. };
  34508. return SSAORenderingPipeline;
  34509. })(BABYLON.PostProcessRenderPipeline);
  34510. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  34511. })(BABYLON || (BABYLON = {}));
  34512. var BABYLON;
  34513. (function (BABYLON) {
  34514. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  34515. var VolumetricLightScatteringPostProcess = (function (_super) {
  34516. __extends(VolumetricLightScatteringPostProcess, _super);
  34517. /**
  34518. * @constructor
  34519. * @param {string} name - The post-process name
  34520. * @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)
  34521. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  34522. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  34523. * @param {number} samples - The post-process quality, default 100
  34524. * @param {number} samplingMode - The post-process filtering mode
  34525. * @param {BABYLON.Engine} engine - The babylon engine
  34526. * @param {boolean} reusable - If the post-process is reusable
  34527. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  34528. */
  34529. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  34530. var _this = this;
  34531. if (samples === void 0) { samples = 100; }
  34532. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34533. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  34534. this._screenCoordinates = BABYLON.Vector2.Zero();
  34535. /**
  34536. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  34537. * @type {boolean}
  34538. */
  34539. this.useCustomMeshPosition = false;
  34540. /**
  34541. * If the post-process should inverse the light scattering direction
  34542. * @type {boolean}
  34543. */
  34544. this.invert = true;
  34545. /**
  34546. * Set to true to use the diffuseColor instead of the diffuseTexture
  34547. * @type {boolean}
  34548. */
  34549. this.useDiffuseColor = false;
  34550. /**
  34551. * Array containing the excluded meshes not rendered in the internal pass
  34552. */
  34553. this.excludedMeshes = new Array();
  34554. /**
  34555. * Controls the overall intensity of the post-process
  34556. * @type {number}
  34557. */
  34558. this.exposure = 0.3;
  34559. /**
  34560. * Dissipates each sample's contribution in range [0, 1]
  34561. * @type {number}
  34562. */
  34563. this.decay = 0.96815;
  34564. /**
  34565. * Controls the overall intensity of each sample
  34566. * @type {number}
  34567. */
  34568. this.weight = 0.58767;
  34569. /**
  34570. * Controls the density of each sample
  34571. * @type {number}
  34572. */
  34573. this.density = 0.926;
  34574. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  34575. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  34576. // Configure mesh
  34577. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  34578. // Configure
  34579. this._createPass(scene, ratio.passRatio || ratio);
  34580. this.onActivate = function (camera) {
  34581. if (!_this.isSupported) {
  34582. _this.dispose(camera);
  34583. }
  34584. _this.onActivate = null;
  34585. };
  34586. this.onApply = function (effect) {
  34587. _this._updateMeshScreenCoordinates(scene);
  34588. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  34589. effect.setFloat("exposure", _this.exposure);
  34590. effect.setFloat("decay", _this.decay);
  34591. effect.setFloat("weight", _this.weight);
  34592. effect.setFloat("density", _this.density);
  34593. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  34594. };
  34595. }
  34596. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  34597. var mesh = subMesh.getMesh();
  34598. var defines = [];
  34599. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34600. var material = subMesh.getMaterial();
  34601. var needUV = false;
  34602. // Render this.mesh as default
  34603. if (mesh === this.mesh) {
  34604. if (this.useDiffuseColor) {
  34605. defines.push("#define DIFFUSE_COLOR_RENDER");
  34606. }
  34607. else if (material) {
  34608. if (material.diffuseTexture !== undefined) {
  34609. defines.push("#define BASIC_RENDER");
  34610. }
  34611. else {
  34612. defines.push("#define DIFFUSE_COLOR_RENDER");
  34613. }
  34614. }
  34615. defines.push("#define NEED_UV");
  34616. needUV = true;
  34617. }
  34618. // Alpha test
  34619. if (material) {
  34620. if (material.needAlphaTesting()) {
  34621. defines.push("#define ALPHATEST");
  34622. }
  34623. if (material.opacityTexture !== undefined) {
  34624. defines.push("#define OPACITY");
  34625. if (material.opacityTexture.getAlphaFromRGB) {
  34626. defines.push("#define OPACITYRGB");
  34627. }
  34628. if (!needUV) {
  34629. defines.push("#define NEED_UV");
  34630. }
  34631. }
  34632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34633. attribs.push(BABYLON.VertexBuffer.UVKind);
  34634. defines.push("#define UV1");
  34635. }
  34636. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34637. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34638. defines.push("#define UV2");
  34639. }
  34640. }
  34641. // Bones
  34642. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34643. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34644. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34645. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34646. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34647. }
  34648. else {
  34649. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34650. }
  34651. // Instances
  34652. if (useInstances) {
  34653. defines.push("#define INSTANCES");
  34654. attribs.push("world0");
  34655. attribs.push("world1");
  34656. attribs.push("world2");
  34657. attribs.push("world3");
  34658. }
  34659. // Get correct effect
  34660. var join = defines.join("\n");
  34661. if (this._cachedDefines !== join) {
  34662. this._cachedDefines = join;
  34663. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  34664. }
  34665. return this._volumetricLightScatteringPass.isReady();
  34666. };
  34667. /**
  34668. * Sets the new light position for light scattering effect
  34669. * @param {BABYLON.Vector3} The new custom light position
  34670. */
  34671. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  34672. this._customMeshPosition = position;
  34673. };
  34674. /**
  34675. * Returns the light position for light scattering effect
  34676. * @return {BABYLON.Vector3} The custom light position
  34677. */
  34678. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  34679. return this._customMeshPosition;
  34680. };
  34681. /**
  34682. * Disposes the internal assets and detaches the post-process from the camera
  34683. */
  34684. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  34685. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  34686. if (rttIndex !== -1) {
  34687. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  34688. }
  34689. this._volumetricLightScatteringRTT.dispose();
  34690. _super.prototype.dispose.call(this, camera);
  34691. };
  34692. /**
  34693. * Returns the render target texture used by the post-process
  34694. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  34695. */
  34696. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  34697. return this._volumetricLightScatteringRTT;
  34698. };
  34699. // Private methods
  34700. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  34701. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  34702. return true;
  34703. }
  34704. return false;
  34705. };
  34706. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  34707. var _this = this;
  34708. var engine = scene.getEngine();
  34709. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  34710. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34711. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34712. this._volumetricLightScatteringRTT.renderList = null;
  34713. this._volumetricLightScatteringRTT.renderParticles = false;
  34714. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  34715. // Custom render function for submeshes
  34716. var renderSubMesh = function (subMesh) {
  34717. var mesh = subMesh.getRenderingMesh();
  34718. if (_this._meshExcluded(mesh)) {
  34719. return;
  34720. }
  34721. var scene = mesh.getScene();
  34722. var engine = scene.getEngine();
  34723. // Culling
  34724. engine.setState(subMesh.getMaterial().backFaceCulling);
  34725. // Managing instances
  34726. var batch = mesh._getInstancesRenderList(subMesh._id);
  34727. if (batch.mustReturn) {
  34728. return;
  34729. }
  34730. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  34731. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  34732. engine.enableEffect(_this._volumetricLightScatteringPass);
  34733. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  34734. var material = subMesh.getMaterial();
  34735. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  34736. // Alpha test
  34737. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  34738. var alphaTexture = material.getAlphaTestTexture();
  34739. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  34740. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  34741. }
  34742. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  34743. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  34744. if (alphaTexture) {
  34745. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  34746. }
  34747. }
  34748. if (material.opacityTexture !== undefined) {
  34749. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  34750. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  34751. }
  34752. }
  34753. // Bones
  34754. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34755. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  34756. }
  34757. // Draw
  34758. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  34759. }
  34760. };
  34761. // Render target texture callbacks
  34762. var savedSceneClearColor;
  34763. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  34764. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  34765. savedSceneClearColor = scene.clearColor;
  34766. scene.clearColor = sceneClearColor;
  34767. };
  34768. this._volumetricLightScatteringRTT.onAfterRender = function () {
  34769. scene.clearColor = savedSceneClearColor;
  34770. };
  34771. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  34772. var engine = scene.getEngine();
  34773. var index;
  34774. for (index = 0; index < opaqueSubMeshes.length; index++) {
  34775. renderSubMesh(opaqueSubMeshes.data[index]);
  34776. }
  34777. engine.setAlphaTesting(true);
  34778. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  34779. renderSubMesh(alphaTestSubMeshes.data[index]);
  34780. }
  34781. engine.setAlphaTesting(false);
  34782. if (transparentSubMeshes.length) {
  34783. // Sort sub meshes
  34784. for (index = 0; index < transparentSubMeshes.length; index++) {
  34785. var submesh = transparentSubMeshes.data[index];
  34786. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  34787. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  34788. }
  34789. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  34790. sortedArray.sort(function (a, b) {
  34791. // Alpha index first
  34792. if (a._alphaIndex > b._alphaIndex) {
  34793. return 1;
  34794. }
  34795. if (a._alphaIndex < b._alphaIndex) {
  34796. return -1;
  34797. }
  34798. // Then distance to camera
  34799. if (a._distanceToCamera < b._distanceToCamera) {
  34800. return 1;
  34801. }
  34802. if (a._distanceToCamera > b._distanceToCamera) {
  34803. return -1;
  34804. }
  34805. return 0;
  34806. });
  34807. // Render sub meshes
  34808. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34809. for (index = 0; index < sortedArray.length; index++) {
  34810. renderSubMesh(sortedArray[index]);
  34811. }
  34812. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34813. }
  34814. };
  34815. };
  34816. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34817. var transform = scene.getTransformMatrix();
  34818. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  34819. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34820. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34821. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34822. if (this.invert)
  34823. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34824. };
  34825. // Static methods
  34826. /**
  34827. * Creates a default mesh for the Volumeric Light Scattering post-process
  34828. * @param {string} The mesh name
  34829. * @param {BABYLON.Scene} The scene where to create the mesh
  34830. * @return {BABYLON.Mesh} the default mesh
  34831. */
  34832. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34833. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34834. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34835. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34836. return mesh;
  34837. };
  34838. return VolumetricLightScatteringPostProcess;
  34839. })(BABYLON.PostProcess);
  34840. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34841. })(BABYLON || (BABYLON = {}));
  34842. var BABYLON;
  34843. (function (BABYLON) {
  34844. var LensRenderingPipeline = (function (_super) {
  34845. __extends(LensRenderingPipeline, _super);
  34846. /**
  34847. * @constructor
  34848. *
  34849. * Effect parameters are as follow:
  34850. * {
  34851. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34852. * edge_blur: number; // from 0 to x (1 for realism)
  34853. * distortion: number; // from 0 to x (1 for realism)
  34854. * grain_amount: number; // from 0 to 1
  34855. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34856. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34857. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34858. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34859. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34860. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34861. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34862. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34863. * }
  34864. * Note: if an effect parameter is unset, effect is disabled
  34865. *
  34866. * @param {string} name - The rendering pipeline name
  34867. * @param {object} parameters - An object containing all parameters (see above)
  34868. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34869. * @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)
  34870. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34871. */
  34872. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34873. var _this = this;
  34874. if (ratio === void 0) { ratio = 1.0; }
  34875. _super.call(this, scene.getEngine(), name);
  34876. // Lens effects can be of the following:
  34877. // - chromatic aberration (slight shift of RGB colors)
  34878. // - blur on the edge of the lens
  34879. // - lens distortion
  34880. // - depth-of-field blur & highlights enhancing
  34881. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34882. // - grain effect (noise or custom texture)
  34883. // Two additional texture samplers are needed:
  34884. // - depth map (for depth-of-field)
  34885. // - grain texture
  34886. /**
  34887. * The chromatic aberration PostProcess id in the pipeline
  34888. * @type {string}
  34889. */
  34890. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34891. /**
  34892. * The highlights enhancing PostProcess id in the pipeline
  34893. * @type {string}
  34894. */
  34895. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34896. /**
  34897. * The depth-of-field PostProcess id in the pipeline
  34898. * @type {string}
  34899. */
  34900. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34901. this._scene = scene;
  34902. // Fetch texture samplers
  34903. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34904. if (parameters.grain_texture) {
  34905. this._grainTexture = parameters.grain_texture;
  34906. }
  34907. else {
  34908. this._createGrainTexture();
  34909. }
  34910. // save parameters
  34911. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34912. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34913. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34914. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34915. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34916. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34917. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34918. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34919. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34920. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34921. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34922. // Create effects
  34923. this._createChromaticAberrationPostProcess(ratio);
  34924. this._createHighlightsPostProcess(ratio);
  34925. this._createDepthOfFieldPostProcess(ratio / 4);
  34926. // Set up pipeline
  34927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34928. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34930. if (this._highlightsGain === -1) {
  34931. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34932. }
  34933. // Finish
  34934. scene.postProcessRenderPipelineManager.addPipeline(this);
  34935. if (cameras) {
  34936. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34937. }
  34938. }
  34939. // public methods (self explanatory)
  34940. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34941. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34942. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34943. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34944. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34945. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34946. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34947. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34948. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34949. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34950. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34951. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34952. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  34953. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  34954. };
  34955. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  34956. this._highlightsPostProcess.updateEffect();
  34957. };
  34958. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34959. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34960. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34961. this._highlightsGain = amount;
  34962. };
  34963. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34964. if (this._highlightsGain === -1) {
  34965. this._highlightsGain = 1.0;
  34966. }
  34967. this._highlightsThreshold = amount;
  34968. };
  34969. LensRenderingPipeline.prototype.disableHighlights = function () {
  34970. this._highlightsGain = -1;
  34971. };
  34972. /**
  34973. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34974. */
  34975. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34976. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34977. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34978. this._chromaticAberrationPostProcess = undefined;
  34979. this._highlightsPostProcess = undefined;
  34980. this._depthOfFieldPostProcess = undefined;
  34981. this._grainTexture.dispose();
  34982. if (disableDepthRender)
  34983. this._scene.disableDepthRenderer();
  34984. };
  34985. // colors shifting and distortion
  34986. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34987. var _this = this;
  34988. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34989. [], // samplers
  34990. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34991. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34992. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34993. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34994. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34995. };
  34996. };
  34997. // highlights enhancing
  34998. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34999. var _this = this;
  35000. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35001. [], // samplers
  35002. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35003. this._highlightsPostProcess.onApply = function (effect) {
  35004. effect.setFloat('gain', _this._highlightsGain);
  35005. effect.setFloat('threshold', _this._highlightsThreshold);
  35006. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35007. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35008. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35009. };
  35010. };
  35011. // colors shifting and distortion
  35012. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35013. var _this = this;
  35014. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35015. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35016. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35017. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35018. this._depthOfFieldPostProcess.onApply = function (effect) {
  35019. effect.setTexture("depthSampler", _this._depthTexture);
  35020. effect.setTexture("grainSampler", _this._grainTexture);
  35021. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35022. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35023. effect.setFloat('grain_amount', _this._grainAmount);
  35024. effect.setBool('blur_noise', _this._blurNoise);
  35025. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35026. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35027. effect.setFloat('distortion', _this._distortion);
  35028. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35029. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35030. effect.setFloat('aperture', _this._dofAperture);
  35031. effect.setFloat('darken', _this._dofDarken);
  35032. effect.setFloat('edge_blur', _this._edgeBlur);
  35033. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35034. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35035. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35036. };
  35037. };
  35038. // creates a black and white random noise texture, 512x512
  35039. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35040. var size = 512;
  35041. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35042. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35043. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35044. var context = this._grainTexture.getContext();
  35045. var rand = function (min, max) {
  35046. return Math.random() * (max - min) + min;
  35047. };
  35048. var value;
  35049. for (var x = 0; x < size; x++) {
  35050. for (var y = 0; y < size; y++) {
  35051. value = Math.floor(rand(0.42, 0.58) * 255);
  35052. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35053. context.fillRect(x, y, 1, 1);
  35054. }
  35055. }
  35056. this._grainTexture.update(false);
  35057. };
  35058. return LensRenderingPipeline;
  35059. })(BABYLON.PostProcessRenderPipeline);
  35060. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35061. })(BABYLON || (BABYLON = {}));
  35062. //
  35063. // This post-process allows the modification of rendered colors by using
  35064. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35065. //
  35066. // The object needs to be provided an url to a texture containing the color
  35067. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35068. // Use an image editing software to tweak the LUT to match your needs.
  35069. //
  35070. // For an example of a color LUT, see here:
  35071. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35072. // For explanations on color grading, see here:
  35073. // http://udn.epicgames.com/Three/ColorGrading.html
  35074. //
  35075. var BABYLON;
  35076. (function (BABYLON) {
  35077. var ColorCorrectionPostProcess = (function (_super) {
  35078. __extends(ColorCorrectionPostProcess, _super);
  35079. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35080. var _this = this;
  35081. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35082. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35083. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35084. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35085. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35086. this.onApply = function (effect) {
  35087. effect.setTexture("colorTable", _this._colorTableTexture);
  35088. };
  35089. }
  35090. return ColorCorrectionPostProcess;
  35091. })(BABYLON.PostProcess);
  35092. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35093. })(BABYLON || (BABYLON = {}));
  35094. var BABYLON;
  35095. (function (BABYLON) {
  35096. var AnaglyphFreeCamera = (function (_super) {
  35097. __extends(AnaglyphFreeCamera, _super);
  35098. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  35099. _super.call(this, name, position, scene);
  35100. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35101. }
  35102. return AnaglyphFreeCamera;
  35103. })(BABYLON.FreeCamera);
  35104. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  35105. var AnaglyphArcRotateCamera = (function (_super) {
  35106. __extends(AnaglyphArcRotateCamera, _super);
  35107. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  35108. _super.call(this, name, alpha, beta, radius, target, scene);
  35109. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35110. }
  35111. return AnaglyphArcRotateCamera;
  35112. })(BABYLON.ArcRotateCamera);
  35113. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  35114. var AnaglyphGamepadCamera = (function (_super) {
  35115. __extends(AnaglyphGamepadCamera, _super);
  35116. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  35117. _super.call(this, name, position, scene);
  35118. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  35119. }
  35120. return AnaglyphGamepadCamera;
  35121. })(BABYLON.GamepadCamera);
  35122. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  35123. var StereoscopicFreeCamera = (function (_super) {
  35124. __extends(StereoscopicFreeCamera, _super);
  35125. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35126. _super.call(this, name, position, scene);
  35127. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35128. }
  35129. return StereoscopicFreeCamera;
  35130. })(BABYLON.FreeCamera);
  35131. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  35132. var StereoscopicArcRotateCamera = (function (_super) {
  35133. __extends(StereoscopicArcRotateCamera, _super);
  35134. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  35135. _super.call(this, name, alpha, beta, radius, target, scene);
  35136. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35137. }
  35138. return StereoscopicArcRotateCamera;
  35139. })(BABYLON.ArcRotateCamera);
  35140. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  35141. var StereoscopicGamepadCamera = (function (_super) {
  35142. __extends(StereoscopicGamepadCamera, _super);
  35143. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  35144. _super.call(this, name, position, scene);
  35145. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  35146. }
  35147. return StereoscopicGamepadCamera;
  35148. })(BABYLON.GamepadCamera);
  35149. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  35150. })(BABYLON || (BABYLON = {}));
  35151. var BABYLON;
  35152. (function (BABYLON) {
  35153. var HDRRenderingPipeline = (function (_super) {
  35154. __extends(HDRRenderingPipeline, _super);
  35155. /**
  35156. * @constructor
  35157. * @param {string} name - The rendering pipeline name
  35158. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35159. * @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)
  35160. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35161. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35162. */
  35163. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35164. var _this = this;
  35165. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35166. _super.call(this, scene.getEngine(), name);
  35167. /**
  35168. * Public members
  35169. */
  35170. // Gaussian Blur
  35171. /**
  35172. * Gaussian blur coefficient
  35173. * @type {number}
  35174. */
  35175. this.gaussCoeff = 0.3;
  35176. /**
  35177. * Gaussian blur mean
  35178. * @type {number}
  35179. */
  35180. this.gaussMean = 1.0;
  35181. /**
  35182. * Gaussian blur standard deviation
  35183. * @type {number}
  35184. */
  35185. this.gaussStandDev = 0.8;
  35186. /**
  35187. * Gaussian blur multiplier. Multiplies the blur effect
  35188. * @type {number}
  35189. */
  35190. this.gaussMultiplier = 4.0;
  35191. // HDR
  35192. /**
  35193. * Exposure, controls the overall intensity of the pipeline
  35194. * @type {number}
  35195. */
  35196. this.exposure = 1.0;
  35197. /**
  35198. * Minimum luminance that the post-process can output. Luminance is >= 0
  35199. * @type {number}
  35200. */
  35201. this.minimumLuminance = 1.0;
  35202. /**
  35203. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35204. * @type {number}
  35205. */
  35206. this.maximumLuminance = 1e20;
  35207. /**
  35208. * Increase rate for luminance: eye adaptation speed to dark
  35209. * @type {number}
  35210. */
  35211. this.luminanceIncreaserate = 0.5;
  35212. /**
  35213. * Decrease rate for luminance: eye adaptation speed to bright
  35214. * @type {number}
  35215. */
  35216. this.luminanceDecreaseRate = 0.5;
  35217. // Bright pass
  35218. /**
  35219. * Minimum luminance needed to compute HDR
  35220. * @type {number}
  35221. */
  35222. this.brightThreshold = 0.8;
  35223. this._needUpdate = true;
  35224. this._scene = scene;
  35225. // Bright pass
  35226. this._createBrightPassPostProcess(scene, ratio);
  35227. // Down sample X4
  35228. this._createDownSampleX4PostProcess(scene, ratio);
  35229. // Create gaussian blur post-processes
  35230. this._createGaussianBlurPostProcess(scene, ratio);
  35231. // Texture adder
  35232. this._createTextureAdderPostProcess(scene, ratio);
  35233. // Luminance generator
  35234. this._createLuminanceGeneratorPostProcess(scene);
  35235. // HDR
  35236. this._createHDRPostProcess(scene, ratio);
  35237. // Pass postprocess
  35238. if (originalPostProcess === null) {
  35239. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35240. }
  35241. else {
  35242. this._originalPostProcess = originalPostProcess;
  35243. }
  35244. // Configure pipeline
  35245. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  35246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  35247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  35248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  35249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  35250. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  35251. var addDownSamplerPostProcess = function (id) {
  35252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  35253. };
  35254. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35255. addDownSamplerPostProcess(i);
  35256. }
  35257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  35258. // Finish
  35259. scene.postProcessRenderPipelineManager.addPipeline(this);
  35260. if (cameras !== null) {
  35261. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35262. }
  35263. this.update();
  35264. }
  35265. /**
  35266. * Tells the pipeline to update its post-processes
  35267. */
  35268. HDRRenderingPipeline.prototype.update = function () {
  35269. this._needUpdate = true;
  35270. };
  35271. /**
  35272. * Returns the current calculated luminance
  35273. */
  35274. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  35275. return this._hdrCurrentLuminance;
  35276. };
  35277. /**
  35278. * Returns the currently drawn luminance
  35279. */
  35280. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  35281. return this._hdrOutputLuminance;
  35282. };
  35283. /**
  35284. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  35285. */
  35286. HDRRenderingPipeline.prototype.dispose = function () {
  35287. this._originalPostProcess = undefined;
  35288. this._brightPassPostProcess = undefined;
  35289. this._downSampleX4PostProcess = undefined;
  35290. this._guassianBlurHPostProcess = undefined;
  35291. this._guassianBlurVPostProcess = undefined;
  35292. this._textureAdderPostProcess = undefined;
  35293. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  35294. this._downSamplePostProcesses[i] = undefined;
  35295. }
  35296. this._hdrPostProcess = undefined;
  35297. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35298. };
  35299. /**
  35300. * Creates the HDR post-process and computes the luminance adaptation
  35301. */
  35302. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  35303. var _this = this;
  35304. var hdrLastLuminance = 0.0;
  35305. this._hdrOutputLuminance = -1.0;
  35306. this._hdrCurrentLuminance = 1.0;
  35307. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  35308. this._hdrPostProcess.onApply = function (effect) {
  35309. if (_this._hdrOutputLuminance < 0.0) {
  35310. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35311. }
  35312. else {
  35313. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  35314. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  35315. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  35316. }
  35317. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  35318. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  35319. }
  35320. else {
  35321. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  35322. }
  35323. }
  35324. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  35325. hdrLastLuminance += scene.getEngine().getDeltaTime();
  35326. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35327. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35328. effect.setFloat("exposure", _this.exposure);
  35329. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  35330. _this._needUpdate = false;
  35331. };
  35332. };
  35333. /**
  35334. * Texture Adder post-process
  35335. */
  35336. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  35337. var _this = this;
  35338. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  35339. this._textureAdderPostProcess.onApply = function (effect) {
  35340. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  35341. };
  35342. };
  35343. /**
  35344. * Down sample X4 post-process
  35345. */
  35346. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  35347. var _this = this;
  35348. var downSampleX4Offsets = new Array(32);
  35349. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  35350. this._downSampleX4PostProcess.onApply = function (effect) {
  35351. if (_this._needUpdate) {
  35352. var id = 0;
  35353. for (var i = -2; i < 2; i++) {
  35354. for (var j = -2; j < 2; j++) {
  35355. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  35356. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  35357. id += 2;
  35358. }
  35359. }
  35360. }
  35361. effect.setArray2("dsOffsets", downSampleX4Offsets);
  35362. };
  35363. };
  35364. /**
  35365. * Bright pass post-process
  35366. */
  35367. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  35368. var _this = this;
  35369. var brightOffsets = new Array(8);
  35370. var brightPassCallback = function (effect) {
  35371. if (_this._needUpdate) {
  35372. var sU = (1.0 / _this._brightPassPostProcess.width);
  35373. var sV = (1.0 / _this._brightPassPostProcess.height);
  35374. brightOffsets[0] = -0.5 * sU;
  35375. brightOffsets[1] = 0.5 * sV;
  35376. brightOffsets[2] = 0.5 * sU;
  35377. brightOffsets[3] = 0.5 * sV;
  35378. brightOffsets[4] = -0.5 * sU;
  35379. brightOffsets[5] = -0.5 * sV;
  35380. brightOffsets[6] = 0.5 * sU;
  35381. brightOffsets[7] = -0.5 * sV;
  35382. }
  35383. effect.setArray2("dsOffsets", brightOffsets);
  35384. effect.setFloat("brightThreshold", _this.brightThreshold);
  35385. };
  35386. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  35387. this._brightPassPostProcess.onApply = brightPassCallback;
  35388. };
  35389. /**
  35390. * Luminance generator. Creates the luminance post-process and down sample post-processes
  35391. */
  35392. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  35393. var _this = this;
  35394. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  35395. var luminanceOffsets = new Array(8);
  35396. var downSampleOffsets = new Array(18);
  35397. var halfDestPixelSize;
  35398. this._downSamplePostProcesses = new Array(lumSteps);
  35399. // Utils for luminance
  35400. var luminanceUpdateSourceOffsets = function (width, height) {
  35401. var sU = (1.0 / width);
  35402. var sV = (1.0 / height);
  35403. luminanceOffsets[0] = -0.5 * sU;
  35404. luminanceOffsets[1] = 0.5 * sV;
  35405. luminanceOffsets[2] = 0.5 * sU;
  35406. luminanceOffsets[3] = 0.5 * sV;
  35407. luminanceOffsets[4] = -0.5 * sU;
  35408. luminanceOffsets[5] = -0.5 * sV;
  35409. luminanceOffsets[6] = 0.5 * sU;
  35410. luminanceOffsets[7] = -0.5 * sV;
  35411. };
  35412. var luminanceUpdateDestOffsets = function (width, height) {
  35413. var id = 0;
  35414. for (var x = -1; x < 2; x++) {
  35415. for (var y = -1; y < 2; y++) {
  35416. downSampleOffsets[id] = (x) / width;
  35417. downSampleOffsets[id + 1] = (y) / height;
  35418. id += 2;
  35419. }
  35420. }
  35421. };
  35422. // Luminance callback
  35423. var luminanceCallback = function (effect) {
  35424. if (_this._needUpdate) {
  35425. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  35426. }
  35427. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  35428. effect.setArray2("lumOffsets", luminanceOffsets);
  35429. };
  35430. // Down sample callbacks
  35431. var downSampleCallback = function (indice) {
  35432. var i = indice;
  35433. return function (effect) {
  35434. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35435. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  35436. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  35437. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  35438. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  35439. effect.setArray2("dsOffsets", downSampleOffsets);
  35440. };
  35441. };
  35442. var downSampleAfterRenderCallback = function (effect) {
  35443. // Unpack result
  35444. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  35445. 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);
  35446. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  35447. };
  35448. // Create luminance post-process
  35449. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  35450. 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);
  35451. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  35452. // Create down sample post-processes
  35453. for (var i = lumSteps - 2; i >= 0; i--) {
  35454. var length = Math.pow(3, i);
  35455. ratio = { width: length, height: length };
  35456. var defines = "#define DOWN_SAMPLE\n";
  35457. if (i === 0) {
  35458. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  35459. }
  35460. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  35461. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  35462. if (i === 0) {
  35463. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  35464. }
  35465. }
  35466. };
  35467. /**
  35468. * Gaussian blur post-processes. Horizontal and Vertical
  35469. */
  35470. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  35471. var _this = this;
  35472. var blurOffsetsW = new Array(9);
  35473. var blurOffsetsH = new Array(9);
  35474. var blurWeights = new Array(9);
  35475. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  35476. // Utils for gaussian blur
  35477. var calculateBlurOffsets = function (height) {
  35478. var lastOutputDimensions = {
  35479. width: scene.getEngine().getRenderWidth(),
  35480. height: scene.getEngine().getRenderHeight()
  35481. };
  35482. for (var i = 0; i < 9; i++) {
  35483. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  35484. if (height) {
  35485. blurOffsetsH[i] = value;
  35486. }
  35487. else {
  35488. blurOffsetsW[i] = value;
  35489. }
  35490. }
  35491. };
  35492. var calculateWeights = function () {
  35493. var x = 0.0;
  35494. for (var i = 0; i < 9; i++) {
  35495. x = (i - 4.0) / 4.0;
  35496. 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));
  35497. }
  35498. };
  35499. // Callback
  35500. var gaussianBlurCallback = function (height) {
  35501. return function (effect) {
  35502. if (_this._needUpdate) {
  35503. calculateWeights();
  35504. calculateBlurOffsets(height);
  35505. }
  35506. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  35507. effect.setArray("blurWeights", blurWeights);
  35508. effect.setFloat("multiplier", _this.gaussMultiplier);
  35509. };
  35510. };
  35511. // Create horizontal gaussian blur post-processes
  35512. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  35513. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  35514. // Create vertical gaussian blur post-process
  35515. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  35516. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  35517. };
  35518. // Luminance generator
  35519. HDRRenderingPipeline.LUM_STEPS = 6;
  35520. return HDRRenderingPipeline;
  35521. })(BABYLON.PostProcessRenderPipeline);
  35522. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  35523. })(BABYLON || (BABYLON = {}));
  35524. var BABYLON;
  35525. (function (BABYLON) {
  35526. var FaceAdjacencies = (function () {
  35527. function FaceAdjacencies() {
  35528. this.edges = new Array();
  35529. this.edgesConnectedCount = 0;
  35530. }
  35531. return FaceAdjacencies;
  35532. })();
  35533. var EdgesRenderer = (function () {
  35534. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  35535. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  35536. if (epsilon === void 0) { epsilon = 0.95; }
  35537. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  35538. this._linesPositions = new Array();
  35539. this._linesNormals = new Array();
  35540. this._linesIndices = new Array();
  35541. this._buffers = new Array();
  35542. this._checkVerticesInsteadOfIndices = false;
  35543. this._source = source;
  35544. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  35545. this._epsilon = epsilon;
  35546. this._prepareRessources();
  35547. this._generateEdgesLines();
  35548. }
  35549. EdgesRenderer.prototype._prepareRessources = function () {
  35550. if (this._lineShader) {
  35551. return;
  35552. }
  35553. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  35554. attributes: ["position", "normal"],
  35555. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  35556. });
  35557. this._lineShader.disableDepthWrite = true;
  35558. this._lineShader.backFaceCulling = false;
  35559. };
  35560. EdgesRenderer.prototype.dispose = function () {
  35561. this._vb0.dispose();
  35562. this._vb1.dispose();
  35563. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  35564. this._lineShader.dispose();
  35565. };
  35566. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  35567. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  35568. return 0;
  35569. }
  35570. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  35571. return 1;
  35572. }
  35573. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  35574. return 2;
  35575. }
  35576. return -1;
  35577. };
  35578. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  35579. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  35580. return 0;
  35581. }
  35582. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  35583. return 1;
  35584. }
  35585. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  35586. return 2;
  35587. }
  35588. return -1;
  35589. };
  35590. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  35591. var needToCreateLine;
  35592. if (edge === undefined) {
  35593. needToCreateLine = true;
  35594. }
  35595. else {
  35596. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  35597. needToCreateLine = dotProduct < this._epsilon;
  35598. }
  35599. if (needToCreateLine) {
  35600. var offset = this._linesPositions.length / 3;
  35601. var normal = p0.subtract(p1);
  35602. normal.normalize();
  35603. // Positions
  35604. this._linesPositions.push(p0.x);
  35605. this._linesPositions.push(p0.y);
  35606. this._linesPositions.push(p0.z);
  35607. this._linesPositions.push(p0.x);
  35608. this._linesPositions.push(p0.y);
  35609. this._linesPositions.push(p0.z);
  35610. this._linesPositions.push(p1.x);
  35611. this._linesPositions.push(p1.y);
  35612. this._linesPositions.push(p1.z);
  35613. this._linesPositions.push(p1.x);
  35614. this._linesPositions.push(p1.y);
  35615. this._linesPositions.push(p1.z);
  35616. // Normals
  35617. this._linesNormals.push(p1.x);
  35618. this._linesNormals.push(p1.y);
  35619. this._linesNormals.push(p1.z);
  35620. this._linesNormals.push(-1);
  35621. this._linesNormals.push(p1.x);
  35622. this._linesNormals.push(p1.y);
  35623. this._linesNormals.push(p1.z);
  35624. this._linesNormals.push(1);
  35625. this._linesNormals.push(p0.x);
  35626. this._linesNormals.push(p0.y);
  35627. this._linesNormals.push(p0.z);
  35628. this._linesNormals.push(-1);
  35629. this._linesNormals.push(p0.x);
  35630. this._linesNormals.push(p0.y);
  35631. this._linesNormals.push(p0.z);
  35632. this._linesNormals.push(1);
  35633. // Indices
  35634. this._linesIndices.push(offset);
  35635. this._linesIndices.push(offset + 1);
  35636. this._linesIndices.push(offset + 2);
  35637. this._linesIndices.push(offset);
  35638. this._linesIndices.push(offset + 2);
  35639. this._linesIndices.push(offset + 3);
  35640. }
  35641. };
  35642. EdgesRenderer.prototype._generateEdgesLines = function () {
  35643. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35644. var indices = this._source.getIndices();
  35645. // First let's find adjacencies
  35646. var adjacencies = new Array();
  35647. var faceNormals = new Array();
  35648. var index;
  35649. var faceAdjacencies;
  35650. // Prepare faces
  35651. for (index = 0; index < indices.length; index += 3) {
  35652. faceAdjacencies = new FaceAdjacencies();
  35653. var p0Index = indices[index];
  35654. var p1Index = indices[index + 1];
  35655. var p2Index = indices[index + 2];
  35656. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  35657. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  35658. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  35659. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  35660. faceNormal.normalize();
  35661. faceNormals.push(faceNormal);
  35662. adjacencies.push(faceAdjacencies);
  35663. }
  35664. // Scan
  35665. for (index = 0; index < adjacencies.length; index++) {
  35666. faceAdjacencies = adjacencies[index];
  35667. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  35668. var otherFaceAdjacencies = adjacencies[otherIndex];
  35669. if (faceAdjacencies.edgesConnectedCount === 3) {
  35670. break;
  35671. }
  35672. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  35673. continue;
  35674. }
  35675. var otherP0 = indices[otherIndex * 3];
  35676. var otherP1 = indices[otherIndex * 3 + 1];
  35677. var otherP2 = indices[otherIndex * 3 + 2];
  35678. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  35679. var otherEdgeIndex;
  35680. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  35681. continue;
  35682. }
  35683. switch (edgeIndex) {
  35684. case 0:
  35685. if (this._checkVerticesInsteadOfIndices) {
  35686. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35687. }
  35688. else {
  35689. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  35690. }
  35691. break;
  35692. case 1:
  35693. if (this._checkVerticesInsteadOfIndices) {
  35694. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35695. }
  35696. else {
  35697. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  35698. }
  35699. break;
  35700. case 2:
  35701. if (this._checkVerticesInsteadOfIndices) {
  35702. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  35703. }
  35704. else {
  35705. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  35706. }
  35707. break;
  35708. }
  35709. if (otherEdgeIndex === -1) {
  35710. continue;
  35711. }
  35712. faceAdjacencies.edges[edgeIndex] = otherIndex;
  35713. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  35714. faceAdjacencies.edgesConnectedCount++;
  35715. otherFaceAdjacencies.edgesConnectedCount++;
  35716. if (faceAdjacencies.edgesConnectedCount === 3) {
  35717. break;
  35718. }
  35719. }
  35720. }
  35721. }
  35722. // Create lines
  35723. for (index = 0; index < adjacencies.length; index++) {
  35724. // 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
  35725. var current = adjacencies[index];
  35726. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  35727. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  35728. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  35729. }
  35730. // Merge into a single mesh
  35731. var engine = this._source.getScene().getEngine();
  35732. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  35733. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  35734. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  35735. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  35736. this._ib = engine.createIndexBuffer(this._linesIndices);
  35737. this._indicesCount = this._linesIndices.length;
  35738. };
  35739. EdgesRenderer.prototype.render = function () {
  35740. if (!this._lineShader.isReady()) {
  35741. return;
  35742. }
  35743. var scene = this._source.getScene();
  35744. var engine = scene.getEngine();
  35745. this._lineShader._preBind();
  35746. // VBOs
  35747. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  35748. scene.resetCachedMaterial();
  35749. this._lineShader.setColor4("color", this._source.edgesColor);
  35750. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  35751. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  35752. this._lineShader.bind(this._source.getWorldMatrix());
  35753. // Draw order
  35754. engine.draw(true, 0, this._indicesCount);
  35755. this._lineShader.unbind();
  35756. engine.setDepthWrite(true);
  35757. };
  35758. return EdgesRenderer;
  35759. })();
  35760. BABYLON.EdgesRenderer = EdgesRenderer;
  35761. })(BABYLON || (BABYLON = {}));
  35762. var BABYLON;
  35763. (function (BABYLON) {
  35764. (function (TonemappingOperator) {
  35765. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  35766. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  35767. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  35768. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  35769. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  35770. var TonemappingOperator = BABYLON.TonemappingOperator;
  35771. ;
  35772. var TonemapPostProcess = (function (_super) {
  35773. __extends(TonemapPostProcess, _super);
  35774. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  35775. var _this = this;
  35776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35777. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35778. this._operator = operator;
  35779. this._exposureAdjustment = exposureAdjustment;
  35780. var params = ["_ExposureAdjustment"];
  35781. var defines = "#define ";
  35782. if (operator === TonemappingOperator.Hable)
  35783. defines += "HABLE_TONEMAPPING";
  35784. else if (operator === TonemappingOperator.Reinhard)
  35785. defines += "REINHARD_TONEMAPPING";
  35786. else if (operator === TonemappingOperator.HejiDawson)
  35787. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  35788. else if (operator === TonemappingOperator.Photographic)
  35789. defines += "PHOTOGRAPHIC_TONEMAPPING";
  35790. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  35791. this.onApply = function (effect) {
  35792. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  35793. };
  35794. }
  35795. return TonemapPostProcess;
  35796. })(BABYLON.PostProcess);
  35797. BABYLON.TonemapPostProcess = TonemapPostProcess;
  35798. })(BABYLON || (BABYLON = {}));
  35799. var BABYLON;
  35800. (function (BABYLON) {
  35801. var ReflectionProbe = (function () {
  35802. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35803. var _this = this;
  35804. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35805. this.name = name;
  35806. this._viewMatrix = BABYLON.Matrix.Identity();
  35807. this._target = BABYLON.Vector3.Zero();
  35808. this._add = BABYLON.Vector3.Zero();
  35809. this.position = BABYLON.Vector3.Zero();
  35810. this._scene = scene;
  35811. this._scene.reflectionProbes.push(this);
  35812. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35813. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35814. switch (faceIndex) {
  35815. case 0:
  35816. _this._add.copyFromFloats(1, 0, 0);
  35817. break;
  35818. case 1:
  35819. _this._add.copyFromFloats(-1, 0, 0);
  35820. break;
  35821. case 2:
  35822. _this._add.copyFromFloats(0, -1, 0);
  35823. break;
  35824. case 3:
  35825. _this._add.copyFromFloats(0, 1, 0);
  35826. break;
  35827. case 4:
  35828. _this._add.copyFromFloats(0, 0, 1);
  35829. break;
  35830. case 5:
  35831. _this._add.copyFromFloats(0, 0, -1);
  35832. break;
  35833. }
  35834. if (_this._attachedMesh) {
  35835. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35836. }
  35837. _this.position.addToRef(_this._add, _this._target);
  35838. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35839. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35840. };
  35841. this._renderTargetTexture.onAfterUnbind = function () {
  35842. scene.updateTransformMatrix(true);
  35843. };
  35844. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35845. }
  35846. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35847. get: function () {
  35848. return this._renderTargetTexture.refreshRate;
  35849. },
  35850. set: function (value) {
  35851. this._renderTargetTexture.refreshRate = value;
  35852. },
  35853. enumerable: true,
  35854. configurable: true
  35855. });
  35856. ReflectionProbe.prototype.getScene = function () {
  35857. return this._scene;
  35858. };
  35859. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35860. get: function () {
  35861. return this._renderTargetTexture;
  35862. },
  35863. enumerable: true,
  35864. configurable: true
  35865. });
  35866. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35867. get: function () {
  35868. return this._renderTargetTexture.renderList;
  35869. },
  35870. enumerable: true,
  35871. configurable: true
  35872. });
  35873. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35874. this._attachedMesh = mesh;
  35875. };
  35876. ReflectionProbe.prototype.dispose = function () {
  35877. var index = this._scene.reflectionProbes.indexOf(this);
  35878. if (index !== -1) {
  35879. // Remove from the scene if found
  35880. this._scene.reflectionProbes.splice(index, 1);
  35881. }
  35882. };
  35883. return ReflectionProbe;
  35884. })();
  35885. BABYLON.ReflectionProbe = ReflectionProbe;
  35886. })(BABYLON || (BABYLON = {}));
  35887. var BABYLON;
  35888. (function (BABYLON) {
  35889. var SolidParticle = (function () {
  35890. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35891. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35892. this.position = BABYLON.Vector3.Zero(); // position
  35893. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35894. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35895. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35896. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35897. this.alive = true; // alive
  35898. this.idx = particleIndex;
  35899. this._pos = positionIndex;
  35900. this._model = model;
  35901. this.shapeId = shapeId;
  35902. this.idxInShape = idxInShape;
  35903. }
  35904. return SolidParticle;
  35905. })();
  35906. BABYLON.SolidParticle = SolidParticle;
  35907. var ModelShape = (function () {
  35908. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35909. this.shapeID = id;
  35910. this._shape = shape;
  35911. this._shapeUV = shapeUV;
  35912. this._positionFunction = posFunction;
  35913. this._vertexFunction = vtxFunction;
  35914. }
  35915. return ModelShape;
  35916. })();
  35917. BABYLON.ModelShape = ModelShape;
  35918. })(BABYLON || (BABYLON = {}));
  35919. var BABYLON;
  35920. (function (BABYLON) {
  35921. var SolidParticleSystem = (function () {
  35922. function SolidParticleSystem(name, scene, options) {
  35923. // public members
  35924. this.particles = new Array();
  35925. this.nbParticles = 0;
  35926. this.billboard = false;
  35927. this.counter = 0;
  35928. this.vars = {};
  35929. this._positions = new Array();
  35930. this._indices = new Array();
  35931. this._normals = new Array();
  35932. this._colors = new Array();
  35933. this._uvs = new Array();
  35934. this._index = 0; // indices index
  35935. this._updatable = true;
  35936. this._pickable = false;
  35937. this._alwaysVisible = false;
  35938. this._shapeCounter = 0;
  35939. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35940. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35941. this._computeParticleColor = true;
  35942. this._computeParticleTexture = true;
  35943. this._computeParticleRotation = true;
  35944. this._computeParticleVertex = false;
  35945. this._cam_axisZ = BABYLON.Vector3.Zero();
  35946. this._cam_axisY = BABYLON.Vector3.Zero();
  35947. this._cam_axisX = BABYLON.Vector3.Zero();
  35948. this._axisX = BABYLON.Axis.X;
  35949. this._axisY = BABYLON.Axis.Y;
  35950. this._axisZ = BABYLON.Axis.Z;
  35951. this._fakeCamPos = BABYLON.Vector3.Zero();
  35952. this._rotMatrix = new BABYLON.Matrix();
  35953. this._invertMatrix = new BABYLON.Matrix();
  35954. this._rotated = BABYLON.Vector3.Zero();
  35955. this._quaternion = new BABYLON.Quaternion();
  35956. this._vertex = BABYLON.Vector3.Zero();
  35957. this._normal = BABYLON.Vector3.Zero();
  35958. this._yaw = 0.0;
  35959. this._pitch = 0.0;
  35960. this._roll = 0.0;
  35961. this._halfroll = 0.0;
  35962. this._halfpitch = 0.0;
  35963. this._halfyaw = 0.0;
  35964. this._sinRoll = 0.0;
  35965. this._cosRoll = 0.0;
  35966. this._sinPitch = 0.0;
  35967. this._cosPitch = 0.0;
  35968. this._sinYaw = 0.0;
  35969. this._cosYaw = 0.0;
  35970. this._w = 0.0;
  35971. this.name = name;
  35972. this._scene = scene;
  35973. this._camera = scene.activeCamera;
  35974. this._pickable = options ? options.isPickable : false;
  35975. if (options && options.updatable) {
  35976. this._updatable = options.updatable;
  35977. }
  35978. else {
  35979. this._updatable = true;
  35980. }
  35981. if (this._pickable) {
  35982. this.pickedParticles = [];
  35983. }
  35984. }
  35985. // build the SPS mesh : returns the mesh
  35986. SolidParticleSystem.prototype.buildMesh = function () {
  35987. if (this.nbParticles === 0) {
  35988. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35989. this.addShape(triangle, 1);
  35990. triangle.dispose();
  35991. }
  35992. this._positions32 = new Float32Array(this._positions);
  35993. this._uvs32 = new Float32Array(this._uvs);
  35994. this._colors32 = new Float32Array(this._colors);
  35995. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35996. this._normals32 = new Float32Array(this._normals);
  35997. this._fixedNormal32 = new Float32Array(this._normals);
  35998. var vertexData = new BABYLON.VertexData();
  35999. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36000. vertexData.indices = this._indices;
  36001. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36002. if (this._uvs32) {
  36003. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36004. ;
  36005. }
  36006. if (this._colors32) {
  36007. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36008. }
  36009. var mesh = new BABYLON.Mesh(name, this._scene);
  36010. vertexData.applyToMesh(mesh, this._updatable);
  36011. this.mesh = mesh;
  36012. this.mesh.isPickable = this._pickable;
  36013. // free memory
  36014. this._positions = null;
  36015. this._normals = null;
  36016. this._uvs = null;
  36017. this._colors = null;
  36018. if (!this._updatable) {
  36019. this.particles.length = 0;
  36020. }
  36021. return mesh;
  36022. };
  36023. //reset copy
  36024. SolidParticleSystem.prototype._resetCopy = function () {
  36025. this._copy.position.x = 0;
  36026. this._copy.position.y = 0;
  36027. this._copy.position.z = 0;
  36028. this._copy.rotation.x = 0;
  36029. this._copy.rotation.y = 0;
  36030. this._copy.rotation.z = 0;
  36031. this._copy.quaternion = null;
  36032. this._copy.scale.x = 1;
  36033. this._copy.scale.y = 1;
  36034. this._copy.scale.z = 1;
  36035. this._copy.uvs.x = 0;
  36036. this._copy.uvs.y = 0;
  36037. this._copy.uvs.z = 1;
  36038. this._copy.uvs.w = 1;
  36039. this._copy.color = null;
  36040. };
  36041. // _meshBuilder : inserts the shape model in the global SPS mesh
  36042. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36043. var i;
  36044. var u = 0;
  36045. var c = 0;
  36046. this._resetCopy();
  36047. if (options && options.positionFunction) {
  36048. options.positionFunction(this._copy, idx, idxInShape);
  36049. }
  36050. if (this._copy.quaternion) {
  36051. this._quaternion.x = this._copy.quaternion.x;
  36052. this._quaternion.y = this._copy.quaternion.y;
  36053. this._quaternion.z = this._copy.quaternion.z;
  36054. this._quaternion.w = this._copy.quaternion.w;
  36055. }
  36056. else {
  36057. this._yaw = this._copy.rotation.y;
  36058. this._pitch = this._copy.rotation.x;
  36059. this._roll = this._copy.rotation.z;
  36060. this._quaternionRotationYPR();
  36061. }
  36062. this._quaternionToRotationMatrix();
  36063. for (i = 0; i < shape.length; i++) {
  36064. this._vertex.x = shape[i].x;
  36065. this._vertex.y = shape[i].y;
  36066. this._vertex.z = shape[i].z;
  36067. if (options && options.vertexFunction) {
  36068. options.vertexFunction(this._copy, this._vertex, i);
  36069. }
  36070. this._vertex.x *= this._copy.scale.x;
  36071. this._vertex.y *= this._copy.scale.y;
  36072. this._vertex.z *= this._copy.scale.z;
  36073. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36074. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36075. if (meshUV) {
  36076. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  36077. u += 2;
  36078. }
  36079. if (this._copy.color) {
  36080. this._color = this._copy.color;
  36081. }
  36082. else if (meshCol && meshCol[c]) {
  36083. this._color.r = meshCol[c];
  36084. this._color.g = meshCol[c + 1];
  36085. this._color.b = meshCol[c + 2];
  36086. this._color.a = meshCol[c + 3];
  36087. }
  36088. else {
  36089. this._color.r = 1;
  36090. this._color.g = 1;
  36091. this._color.b = 1;
  36092. this._color.a = 1;
  36093. }
  36094. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36095. c += 4;
  36096. }
  36097. for (i = 0; i < meshInd.length; i++) {
  36098. indices.push(p + meshInd[i]);
  36099. }
  36100. if (this._pickable) {
  36101. var nbfaces = meshInd.length / 3;
  36102. for (i = 0; i < nbfaces; i++) {
  36103. this.pickedParticles.push({ idx: idx, faceId: i });
  36104. }
  36105. }
  36106. };
  36107. // returns a shape array from positions array
  36108. SolidParticleSystem.prototype._posToShape = function (positions) {
  36109. var shape = [];
  36110. for (var i = 0; i < positions.length; i += 3) {
  36111. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36112. }
  36113. return shape;
  36114. };
  36115. // returns a shapeUV array from a Vector4 uvs
  36116. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36117. var shapeUV = [];
  36118. if (uvs) {
  36119. for (var i = 0; i < uvs.length; i++)
  36120. shapeUV.push(uvs[i]);
  36121. }
  36122. return shapeUV;
  36123. };
  36124. // adds a new particle object in the particles array
  36125. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  36126. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  36127. };
  36128. // add solid particles from a shape model in the particles array
  36129. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36130. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36131. var meshInd = mesh.getIndices();
  36132. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36133. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36134. var shape = this._posToShape(meshPos);
  36135. var shapeUV = this._uvsToShapeUV(meshUV);
  36136. var posfunc = options ? options.positionFunction : null;
  36137. var vtxfunc = options ? options.vertexFunction : null;
  36138. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36139. // particles
  36140. var idx = this.nbParticles;
  36141. for (var i = 0; i < nb; i++) {
  36142. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  36143. if (this._updatable) {
  36144. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  36145. }
  36146. this._index += shape.length;
  36147. idx++;
  36148. }
  36149. this.nbParticles += nb;
  36150. this._shapeCounter++;
  36151. return this._shapeCounter;
  36152. };
  36153. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36154. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36155. this._resetCopy();
  36156. if (particle._model._positionFunction) {
  36157. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36158. }
  36159. if (this._copy.quaternion) {
  36160. this._quaternion.x = this._copy.quaternion.x;
  36161. this._quaternion.y = this._copy.quaternion.y;
  36162. this._quaternion.z = this._copy.quaternion.z;
  36163. this._quaternion.w = this._copy.quaternion.w;
  36164. }
  36165. else {
  36166. this._yaw = this._copy.rotation.y;
  36167. this._pitch = this._copy.rotation.x;
  36168. this._roll = this._copy.rotation.z;
  36169. this._quaternionRotationYPR();
  36170. }
  36171. this._quaternionToRotationMatrix();
  36172. this._shape = particle._model._shape;
  36173. for (var pt = 0; pt < this._shape.length; pt++) {
  36174. this._vertex.x = this._shape[pt].x;
  36175. this._vertex.y = this._shape[pt].y;
  36176. this._vertex.z = this._shape[pt].z;
  36177. if (particle._model._vertexFunction) {
  36178. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36179. }
  36180. this._vertex.x *= this._copy.scale.x;
  36181. this._vertex.y *= this._copy.scale.y;
  36182. this._vertex.z *= this._copy.scale.z;
  36183. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36184. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36185. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36186. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36187. }
  36188. particle.position.x = 0;
  36189. particle.position.y = 0;
  36190. particle.position.z = 0;
  36191. particle.rotation.x = 0;
  36192. particle.rotation.y = 0;
  36193. particle.rotation.z = 0;
  36194. particle.quaternion = null;
  36195. particle.scale.x = 1;
  36196. particle.scale.y = 1;
  36197. particle.scale.z = 1;
  36198. };
  36199. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  36200. SolidParticleSystem.prototype.rebuildMesh = function () {
  36201. for (var p = 0; p < this.particles.length; p++) {
  36202. this._rebuildParticle(this.particles[p]);
  36203. }
  36204. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36205. };
  36206. // sets all the particles : updates the VBO
  36207. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  36208. if (start === void 0) { start = 0; }
  36209. if (end === void 0) { end = this.nbParticles - 1; }
  36210. if (update === void 0) { update = true; }
  36211. if (!this._updatable) {
  36212. return;
  36213. }
  36214. // custom beforeUpdate
  36215. this.beforeUpdateParticles(start, end, update);
  36216. this._cam_axisX.x = 1;
  36217. this._cam_axisX.y = 0;
  36218. this._cam_axisX.z = 0;
  36219. this._cam_axisY.x = 0;
  36220. this._cam_axisY.y = 1;
  36221. this._cam_axisY.z = 0;
  36222. this._cam_axisZ.x = 0;
  36223. this._cam_axisZ.y = 0;
  36224. this._cam_axisZ.z = 1;
  36225. // if the particles will always face the camera
  36226. if (this.billboard) {
  36227. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  36228. this._yaw = this.mesh.rotation.y;
  36229. this._pitch = this.mesh.rotation.x;
  36230. this._roll = this.mesh.rotation.z;
  36231. this._quaternionRotationYPR();
  36232. this._quaternionToRotationMatrix();
  36233. this._rotMatrix.invertToRef(this._invertMatrix);
  36234. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  36235. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  36236. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  36237. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  36238. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  36239. this._cam_axisY.normalize();
  36240. this._cam_axisX.normalize();
  36241. this._cam_axisZ.normalize();
  36242. }
  36243. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  36244. var idx = 0;
  36245. var index = 0;
  36246. var colidx = 0;
  36247. var colorIndex = 0;
  36248. var uvidx = 0;
  36249. var uvIndex = 0;
  36250. // particle loop
  36251. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  36252. for (var p = start; p <= end; p++) {
  36253. this._particle = this.particles[p];
  36254. this._shape = this._particle._model._shape;
  36255. this._shapeUV = this._particle._model._shapeUV;
  36256. // call to custom user function to update the particle properties
  36257. this.updateParticle(this._particle);
  36258. // particle rotation matrix
  36259. if (this.billboard) {
  36260. this._particle.rotation.x = 0.0;
  36261. this._particle.rotation.y = 0.0;
  36262. }
  36263. if (this._computeParticleRotation) {
  36264. if (this._particle.quaternion) {
  36265. this._quaternion.x = this._particle.quaternion.x;
  36266. this._quaternion.y = this._particle.quaternion.y;
  36267. this._quaternion.z = this._particle.quaternion.z;
  36268. this._quaternion.w = this._particle.quaternion.w;
  36269. }
  36270. else {
  36271. this._yaw = this._particle.rotation.y;
  36272. this._pitch = this._particle.rotation.x;
  36273. this._roll = this._particle.rotation.z;
  36274. this._quaternionRotationYPR();
  36275. }
  36276. this._quaternionToRotationMatrix();
  36277. }
  36278. for (var pt = 0; pt < this._shape.length; pt++) {
  36279. idx = index + pt * 3;
  36280. colidx = colorIndex + pt * 4;
  36281. uvidx = uvIndex + pt * 2;
  36282. this._vertex.x = this._shape[pt].x;
  36283. this._vertex.y = this._shape[pt].y;
  36284. this._vertex.z = this._shape[pt].z;
  36285. if (this._computeParticleVertex) {
  36286. this.updateParticleVertex(this._particle, this._vertex, pt);
  36287. }
  36288. // positions
  36289. this._vertex.x *= this._particle.scale.x;
  36290. this._vertex.y *= this._particle.scale.y;
  36291. this._vertex.z *= this._particle.scale.z;
  36292. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  36293. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  36294. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  36295. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  36296. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36297. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  36298. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  36299. // normals : if the particles can't be morphed then just rotate the normals
  36300. if (!this._computeParticleVertex && !this.billboard) {
  36301. this._normal.x = this._fixedNormal32[idx];
  36302. this._normal.y = this._fixedNormal32[idx + 1];
  36303. this._normal.z = this._fixedNormal32[idx + 2];
  36304. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  36305. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  36306. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  36307. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  36308. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  36309. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  36310. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  36311. }
  36312. if (this._computeParticleColor) {
  36313. this._colors32[colidx] = this._particle.color.r;
  36314. this._colors32[colidx + 1] = this._particle.color.g;
  36315. this._colors32[colidx + 2] = this._particle.color.b;
  36316. this._colors32[colidx + 3] = this._particle.color.a;
  36317. }
  36318. if (this._computeParticleTexture) {
  36319. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  36320. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  36321. }
  36322. }
  36323. index = idx + 3;
  36324. colorIndex = colidx + 4;
  36325. uvIndex = uvidx + 2;
  36326. }
  36327. if (update) {
  36328. if (this._computeParticleColor) {
  36329. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  36330. }
  36331. if (this._computeParticleTexture) {
  36332. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  36333. }
  36334. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  36335. if (!this.mesh.areNormalsFrozen) {
  36336. if (this._computeParticleVertex || this.billboard) {
  36337. // recompute the normals only if the particles can be morphed, update then the normal reference array
  36338. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  36339. for (var i = 0; i < this._normals32.length; i++) {
  36340. this._fixedNormal32[i] = this._normals32[i];
  36341. }
  36342. }
  36343. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  36344. }
  36345. }
  36346. this.afterUpdateParticles(start, end, update);
  36347. };
  36348. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  36349. this._halfroll = this._roll * 0.5;
  36350. this._halfpitch = this._pitch * 0.5;
  36351. this._halfyaw = this._yaw * 0.5;
  36352. this._sinRoll = Math.sin(this._halfroll);
  36353. this._cosRoll = Math.cos(this._halfroll);
  36354. this._sinPitch = Math.sin(this._halfpitch);
  36355. this._cosPitch = Math.cos(this._halfpitch);
  36356. this._sinYaw = Math.sin(this._halfyaw);
  36357. this._cosYaw = Math.cos(this._halfyaw);
  36358. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  36359. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  36360. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  36361. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  36362. };
  36363. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  36364. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  36365. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  36366. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  36367. this._rotMatrix.m[3] = 0;
  36368. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  36369. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  36370. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  36371. this._rotMatrix.m[7] = 0;
  36372. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  36373. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  36374. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  36375. this._rotMatrix.m[11] = 0;
  36376. this._rotMatrix.m[12] = 0;
  36377. this._rotMatrix.m[13] = 0;
  36378. this._rotMatrix.m[14] = 0;
  36379. this._rotMatrix.m[15] = 1.0;
  36380. };
  36381. // dispose the SPS
  36382. SolidParticleSystem.prototype.dispose = function () {
  36383. this.mesh.dispose();
  36384. this.vars = null;
  36385. // drop references to internal big arrays for the GC
  36386. this._positions = null;
  36387. this._indices = null;
  36388. this._normals = null;
  36389. this._uvs = null;
  36390. this._colors = null;
  36391. this._positions32 = null;
  36392. this._normals32 = null;
  36393. this._fixedNormal32 = null;
  36394. this._uvs32 = null;
  36395. this._colors32 = null;
  36396. this.pickedParticles = null;
  36397. };
  36398. // Visibilty helpers
  36399. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  36400. this.mesh.refreshBoundingInfo();
  36401. };
  36402. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  36403. // getter and setter
  36404. get: function () {
  36405. return this._alwaysVisible;
  36406. },
  36407. set: function (val) {
  36408. this._alwaysVisible = val;
  36409. this.mesh.alwaysSelectAsActiveMesh = val;
  36410. },
  36411. enumerable: true,
  36412. configurable: true
  36413. });
  36414. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  36415. // getters
  36416. get: function () {
  36417. return this._computeParticleRotation;
  36418. },
  36419. // Optimizer setters
  36420. set: function (val) {
  36421. this._computeParticleRotation = val;
  36422. },
  36423. enumerable: true,
  36424. configurable: true
  36425. });
  36426. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  36427. get: function () {
  36428. return this._computeParticleColor;
  36429. },
  36430. set: function (val) {
  36431. this._computeParticleColor = val;
  36432. },
  36433. enumerable: true,
  36434. configurable: true
  36435. });
  36436. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  36437. get: function () {
  36438. return this._computeParticleTexture;
  36439. },
  36440. set: function (val) {
  36441. this._computeParticleTexture = val;
  36442. },
  36443. enumerable: true,
  36444. configurable: true
  36445. });
  36446. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  36447. get: function () {
  36448. return this._computeParticleVertex;
  36449. },
  36450. set: function (val) {
  36451. this._computeParticleVertex = val;
  36452. },
  36453. enumerable: true,
  36454. configurable: true
  36455. });
  36456. // =======================================================================
  36457. // Particle behavior logic
  36458. // these following methods may be overwritten by the user to fit his needs
  36459. // init : sets all particles first values and calls updateParticle to set them in space
  36460. // can be overwritten by the user
  36461. SolidParticleSystem.prototype.initParticles = function () {
  36462. };
  36463. // recycles a particle : can by overwritten by the user
  36464. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  36465. return particle;
  36466. };
  36467. // updates a particle : can be overwritten by the user
  36468. // will be called on each particle by setParticles() :
  36469. // ex : just set a particle position or velocity and recycle conditions
  36470. SolidParticleSystem.prototype.updateParticle = function (particle) {
  36471. return particle;
  36472. };
  36473. // updates a vertex of a particle : can be overwritten by the user
  36474. // will be called on each vertex particle by setParticles() :
  36475. // particle : the current particle
  36476. // vertex : the current index of the current particle
  36477. // pt : the index of the current vertex in the particle shape
  36478. // ex : just set a vertex particle position
  36479. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  36480. return vertex;
  36481. };
  36482. // will be called before any other treatment by setParticles()
  36483. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  36484. };
  36485. // will be called after all setParticles() treatments
  36486. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  36487. };
  36488. return SolidParticleSystem;
  36489. })();
  36490. BABYLON.SolidParticleSystem = SolidParticleSystem;
  36491. })(BABYLON || (BABYLON = {}));
  36492. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","bricktexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudtexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"precision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\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\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\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\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\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\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\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\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\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 vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 view;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n\r\nfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\tfloat diskScale = (1.0 - (1.0 + depth * 3.0)) / mapSize;\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec3 poissonDisk[4];\r\n\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth - bias;\r\n\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * diskScale)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\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 unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\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#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#ifdef SHADOWPCF0\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#ifdef SHADOWPCF1\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#ifdef SHADOWPCF2\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#ifdef SHADOWPCF3\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#endif\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\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 vec2 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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\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#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\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\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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firetexturePixelShader":"precision highp float;\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grasstexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\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] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#else\r\nuniform samplerCube shadowSampler0;\r\n#endif\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\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#else\r\nuniform samplerCube shadowSampler1;\r\n#endif\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\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#else\r\nuniform samplerCube shadowSampler2;\r\n#endif\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\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#else\r\nuniform samplerCube shadowSampler3;\r\n#endif\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 REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 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\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\nfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 directionToLight = vPositionW - lightPosition;\r\n\tfloat depth = length(directionToLight);\r\n\r\n\tdepth = clamp(depth, 0., 1.);\r\n\r\n\tdirectionToLight.y = 1.0 - directionToLight.y;\r\n\r\n\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\tif (depth > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.0;\r\n}\r\n#endif\r\n\r\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\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\n// Thanks to http://devmaster.net/\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\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#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#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\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, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n#if defined(POINTLIGHT0)\r\n\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[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#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\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, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n#if defined(POINTLIGHT1)\r\n\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[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#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\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, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n#if defined(POINTLIGHT2)\r\n\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n#endif\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 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#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\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, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n#if defined(POINTLIGHT3)\r\n\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\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\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// 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#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif \r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\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\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform 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#ifdef 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#else\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#endif\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}","marbletexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#if NUM_BONE_INFLUENCERS > 0\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\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\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\tvec3 offsetPosition = position + normal * offset;\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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\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}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n\t// having bone influencers implies you have bones\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\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 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#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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\t\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadtexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#if NUM_BONE_INFLUENCERS > 0\r\n\r\n// having bone influencers implies you have bones\r\nuniform mat4 mBones[BonesPerMesh];\r\n\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#if NUM_BONE_INFLUENCERS > 4\r\nattribute vec4 matricesIndicesExtra;\r\nattribute vec4 matricesWeightsExtra;\r\n#endif\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\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#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n#if NUM_BONE_INFLUENCERS > 1\r\n\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 2\r\n\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 3\r\n\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n#endif\t\r\n\r\n#if NUM_BONE_INFLUENCERS > 4\r\n\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 5\r\n\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 6\r\n\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n#endif\t\r\n#if NUM_BONE_INFLUENCERS > 7\r\n\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\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\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(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, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodtexturePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  36493. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.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},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.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},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.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},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.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},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,p=t.y*a+r.y*u+n.y*m+o.y*y,f=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=f.X,c=f.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,c)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,c)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),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=e.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,p=y+c;return 0!==p&&1!==p?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*p),t.z=Math.atan2(e-h,u+m)):0===p?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,g=u*x-c*p,d=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,P=e*x-a*f,C=e*l-h*f,I=s*x-a*p,E=s*l-h*p,L=s*f-e*p,q=h*c-a*y,D=e*c-a*m,S=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*g+o*d)*b,t.m[9]=-(i*w-n*g+o*T)*b,t.m[13]=(i*v-n*d+r*T)*b,t.m[2]=(n*A-r*P+o*C)*b,t.m[6]=-(i*A-r*I+o*E)*b,t.m[10]=(i*P-n*I+o*L)*b,t.m[14]=-(i*C-n*E+r*L)*b,t.m[3]=-(n*q-r*D+o*S)*b,t.m[7]=(i*q-r*Z+o*N)*b,t.m[11]=-(i*D-n*Z+o*W)*b,t.m[15]=(i*S-n*N+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],L=t.m[14],q=t.m[15];return i[n]=r*v+o*R+s*b+e*I,i[n+1]=r*g+o*_+s*A+e*E,i[n+2]=r*d+o*M+s*P+e*L,i[n+3]=r*T+o*F+s*C+e*q,i[n+4]=h*v+a*R+u*b+m*I,i[n+5]=h*g+a*_+u*A+m*E,i[n+6]=h*d+a*M+u*P+m*L,i[n+7]=h*T+a*F+u*C+m*q,i[n+8]=y*v+c*R+p*b+f*I,i[n+9]=y*g+c*_+p*A+f*E,i[n+10]=y*d+c*M+p*P+f*L,i[n+11]=y*T+c*F+p*C+f*q,i[n+12]=l*v+x*R+z*b+w*I,i[n+13]=l*g+x*_+z*A+w*E,i[n+14]=l*d+x*M+z*P+w*L,i[n+15]=l*T+x*F+z*C+w*q,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=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(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,\nn.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.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,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,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 e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=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 e(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=v;var g=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),y=m.angle.radians()/e;m.orientation===x.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,p=0;e>p;p++){var f=Math.cos(c)*m.radius+m.centerPoint.x,l=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(f,l),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var y=u.normalize(),c=n-r;return new s(h.x+y.x*c,h.y+y.y*c)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=g;var d=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=d;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_}(BABYLON||(BABYLON={}));";
  36494. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  36495. module.exports = BABYLON;
  36496. };